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