github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/jujuclient/bootstrapconfig.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package jujuclient 5 6 import ( 7 "os" 8 9 "github.com/juju/errors" 10 "github.com/juju/utils/v3" 11 "gopkg.in/yaml.v2" 12 13 "github.com/juju/juju/juju/osenv" 14 ) 15 16 // JujuBootstrapConfigPath is the location where bootstrap config is 17 // expected to be found. 18 func JujuBootstrapConfigPath() string { 19 return osenv.JujuXDGDataHomePath("bootstrap-config.yaml") 20 } 21 22 // ReadBootstrapConfigFile loads all bootstrap configurations defined in a 23 // given file. If the file is not found, it is not an error. 24 func ReadBootstrapConfigFile(file string) (map[string]BootstrapConfig, error) { 25 data, err := os.ReadFile(file) 26 if err != nil { 27 if os.IsNotExist(err) { 28 return nil, nil 29 } 30 return nil, err 31 } 32 configs, err := ParseBootstrapConfig(data) 33 if err != nil { 34 return nil, err 35 } 36 return configs, nil 37 } 38 39 // WriteBootstrapConfigFile marshals to YAML details of the given bootstrap 40 // configurations and writes it to the bootstrap config file. 41 func WriteBootstrapConfigFile(configs map[string]BootstrapConfig) error { 42 data, err := yaml.Marshal(bootstrapConfigCollection{configs}) 43 if err != nil { 44 return errors.Annotate(err, "cannot marshal bootstrap configurations") 45 } 46 return utils.AtomicWriteFile(JujuBootstrapConfigPath(), data, os.FileMode(0600)) 47 } 48 49 // ParseBootstrapConfig parses the given YAML bytes into bootstrap config 50 // metadata. 51 func ParseBootstrapConfig(data []byte) (map[string]BootstrapConfig, error) { 52 var result bootstrapConfigCollection 53 err := yaml.Unmarshal(data, &result) 54 if err != nil { 55 return nil, errors.Annotate(err, "cannot unmarshal bootstrap config") 56 } 57 return result.ControllerBootstrapConfig, nil 58 } 59 60 type bootstrapConfigCollection struct { 61 ControllerBootstrapConfig map[string]BootstrapConfig `yaml:"controllers"` 62 }