github.com/ddnomad/packer@v1.3.2/common/step_cleanup_temp_keys.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "github.com/hashicorp/packer/helper/communicator" 9 "github.com/hashicorp/packer/helper/multistep" 10 "github.com/hashicorp/packer/packer" 11 ) 12 13 type StepCleanupTempKeys struct { 14 Comm *communicator.Config 15 } 16 17 func (s *StepCleanupTempKeys) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 18 // This step is mostly cosmetic; Packer deletes the ephemeral keys anyway 19 // so there's no realistic situation where these keys can cause issues. 20 // However, it's nice to clean up after yourself. 21 22 comm := state.Get("communicator").(packer.Communicator) 23 ui := state.Get("ui").(packer.Ui) 24 25 if !s.Comm.SSHClearAuthorizedKeys { 26 return multistep.ActionContinue 27 } 28 29 if s.Comm.Type != "ssh" { 30 return multistep.ActionContinue 31 } 32 33 if s.Comm.SSHTemporaryKeyPairName == "" { 34 return multistep.ActionContinue 35 } 36 37 cmd := new(packer.RemoteCmd) 38 39 ui.Say("Trying to remove ephemeral keys from authorized_keys files") 40 41 cmd.Command = fmt.Sprintf("sed -i.bak '/ssh-rsa.*%s$/d' ~/.ssh/authorized_keys; rm ~/.ssh/authorized_keys.bak", s.Comm.SSHTemporaryKeyPairName) 42 if err := cmd.StartWithUi(comm, ui); err != nil { 43 log.Printf("Error cleaning up ~/.ssh/authorized_keys; please clean up keys manually: %s", err) 44 } 45 cmd = new(packer.RemoteCmd) 46 cmd.Command = fmt.Sprintf("sudo sed -i.bak '/ssh-rsa.*%s$/d' /root/.ssh/authorized_keys; sudo rm /root/.ssh/authorized_keys.bak", s.Comm.SSHTemporaryKeyPairName) 47 48 if err := cmd.StartWithUi(comm, ui); err != nil { 49 log.Printf("Error cleaning up /root/.ssh/authorized_keys; please clean up keys manually: %s", err) 50 } 51 52 return multistep.ActionContinue 53 } 54 55 func (s *StepCleanupTempKeys) Cleanup(state multistep.StateBag) { 56 }