Last active
March 2, 2017 13:51
-
-
Save flavio/4900dd698b88e6efc2b21afda86b5224 to your computer and use it in GitHub Desktop.
terraform cloudinit merge example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/imdario/mergo" | |
"gopkg.in/yaml.v2" | |
) | |
type UserData struct { | |
SSHKeys []string `yaml:"ssh_authorized_keys,omitempty"` | |
} | |
// Convert a UserData instance to a map with string as key and interface as value | |
func convertUserDataToMap(data UserData) (map[string]interface{}, error) { | |
userDataMap := make(map[string]interface{}) | |
// This is required to get the right names expected by cloud-init | |
// For example: SSHKeys -> ssh_authorized_keys | |
tmp, err := yaml.Marshal(&data) | |
if err != nil { | |
return userDataMap, err | |
} | |
err = yaml.Unmarshal([]byte(tmp), &userDataMap) | |
return userDataMap, err | |
} | |
func convertUserDataRawToMap(raw string) (map[string]interface{}, error) { | |
m := make(map[string]interface{}) | |
err := yaml.Unmarshal([]byte(raw), &m) | |
return m, err | |
} | |
func mergeUserDataIntoUserDataRaw(userData UserData, userDataRaw string) { | |
userDataMap, err := convertUserDataToMap(userData) | |
if err != nil { | |
fmt.Printf("error1: %v\n", err) | |
} | |
fmt.Printf("UserData: %+v\n", userDataMap) | |
userDataRawMap, err := convertUserDataRawToMap(userDataRaw) | |
if err != nil { | |
fmt.Printf("error2: %v\n", err) | |
} | |
fmt.Printf("UserDataRaw: %+v\n", userDataRawMap) | |
if err = mergo.Merge(&userDataRawMap, userDataMap); err != nil { | |
fmt.Printf("error3: %v\n", err) | |
} | |
fmt.Printf("\nMerge result: %+v\n", userDataRawMap) | |
} | |
func main() { | |
userDataWithSSHKeys := UserData{ | |
SSHKeys: []string{"key1"}, | |
} | |
userDataEmpty := UserData{} | |
var userDataRaw = ` | |
new-key: new-value-set-by-extra | |
ssh_authorized_keys: | |
- key2-from-extra-data | |
` | |
var userDataRawNoSSH = ` | |
new-key: new-value-set-by-extra | |
` | |
mergeUserDataIntoUserDataRaw(userDataWithSSHKeys, userDataRaw) | |
fmt.Println("---") | |
mergeUserDataIntoUserDataRaw(userDataWithSSHKeys, userDataRawNoSSH) | |
fmt.Println("---") | |
mergeUserDataIntoUserDataRaw(userDataEmpty, userDataRaw) | |
fmt.Println("---") | |
mergeUserDataIntoUserDataRaw(userDataEmpty, userDataRawNoSSH) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will produce the following output: