github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cloudconfig/providerinit/renderers/common.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Copyright 2015 Cloudbase Solutions SRL 3 // Licensed under the AGPLv3, see LICENCE file for details. 4 5 package renderers 6 7 import ( 8 "encoding/base64" 9 "fmt" 10 11 "github.com/juju/juju/cloudconfig" 12 "github.com/juju/juju/cloudconfig/cloudinit" 13 "github.com/juju/utils" 14 ) 15 16 // ToBase64 just transforms whatever userdata it gets to base64 format 17 func ToBase64(data []byte) []byte { 18 buf := make([]byte, base64.StdEncoding.EncodedLen(len(data))) 19 base64.StdEncoding.Encode(buf, data) 20 return buf 21 } 22 23 // WinEmbedInScript for now is used on windows and it returns a powershell script 24 // which has the userdata embedded as base64(gzip(userdata)) 25 func WinEmbedInScript(udata []byte) []byte { 26 encUserdata := ToBase64(utils.Gzip(udata)) 27 // place the encUseData inside the "%s" marked sign 28 return []byte(fmt.Sprintf(cloudconfig.UserDataScript, encUserdata)) 29 } 30 31 // AddPowershellTags adds <powershell>...</powershell> to it's input 32 func AddPowershellTags(udata []byte) []byte { 33 return []byte(`<powershell>` + 34 string(udata) + 35 `</powershell>`) 36 } 37 38 // Decorator is a function that can be used as part of a rendering pipeline. 39 type Decorator func([]byte) []byte 40 41 // RenderYAML renders the given cloud-config as YAML, and then passes the 42 // YAML through the given decorators. 43 func RenderYAML(cfg cloudinit.RenderConfig, ds ...Decorator) ([]byte, error) { 44 out, err := cfg.RenderYAML() 45 if err != nil { 46 return nil, err 47 } 48 return applyDecorators(out, ds), nil 49 } 50 51 // RenderScript renders the given cloud-config as a script, and then passes the 52 // script through the given decorators. 53 func RenderScript(cfg cloudinit.RenderConfig, ds ...Decorator) ([]byte, error) { 54 out, err := cfg.RenderScript() 55 if err != nil { 56 return nil, err 57 } 58 return applyDecorators([]byte(out), ds), nil 59 } 60 61 func applyDecorators(out []byte, ds []Decorator) []byte { 62 for _, d := range ds { 63 out = d(out) 64 } 65 return out 66 }