github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/upgrades/systemsshkey.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package upgrades 5 6 import ( 7 "fmt" 8 "io/ioutil" 9 "os" 10 "path" 11 12 "launchpad.net/juju-core/environs/cloudinit" 13 "launchpad.net/juju-core/environs/config" 14 "launchpad.net/juju-core/state/api/keymanager" 15 "launchpad.net/juju-core/utils/ssh" 16 ) 17 18 func ensureSystemSSHKey(context Context) error { 19 identityFile := path.Join(context.AgentConfig().DataDir(), cloudinit.SystemIdentity) 20 // Don't generate a key unless we have to. 21 keyExists, err := systemKeyExists(identityFile) 22 if err != nil { 23 return fmt.Errorf("failed to check system key exists: %v", err) 24 } 25 if keyExists { 26 return nil 27 } 28 privateKey, publicKey, err := ssh.GenerateKey(config.JujuSystemKey) 29 if err != nil { 30 return fmt.Errorf("failed to create system key: %v", err) 31 } 32 // Write new authorised key. 33 keyManager := keymanager.NewClient(context.APIState()) 34 errResults, err := keyManager.AddKeys(config.JujuSystemKey, publicKey) 35 apiErr := err 36 if apiErr == nil { 37 apiErr = errResults[0].Error 38 } 39 if err != nil || errResults[0].Error != nil { 40 return fmt.Errorf("failed to update authoised keys with new system key: %v", apiErr) 41 } 42 return ioutil.WriteFile(identityFile, []byte(privateKey), 0600) 43 } 44 45 func systemKeyExists(identityFile string) (bool, error) { 46 _, err := os.Stat(identityFile) 47 if err == nil { 48 return true, nil 49 } 50 if !os.IsNotExist(err) { 51 return false, err 52 } 53 return false, nil 54 }