github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/builder/amazon/common/step_security_group.go (about) 1 package common 2 3 import ( 4 "cgl.tideland.biz/identifier" 5 "encoding/hex" 6 "fmt" 7 "github.com/mitchellh/goamz/ec2" 8 "github.com/mitchellh/multistep" 9 "github.com/mitchellh/packer/packer" 10 "log" 11 "time" 12 ) 13 14 type StepSecurityGroup struct { 15 SecurityGroupId string 16 SSHPort int 17 VpcId string 18 19 createdGroupId string 20 } 21 22 func (s *StepSecurityGroup) Run(state map[string]interface{}) multistep.StepAction { 23 ec2conn := state["ec2"].(*ec2.EC2) 24 ui := state["ui"].(packer.Ui) 25 26 if s.SecurityGroupId != "" { 27 log.Printf("Using specified security group: %s", s.SecurityGroupId) 28 state["securityGroupId"] = s.SecurityGroupId 29 return multistep.ActionContinue 30 } 31 32 if s.SSHPort == 0 { 33 panic("SSHPort must be set to a non-zero value.") 34 } 35 36 // Create the group 37 ui.Say("Creating temporary security group for this instance...") 38 groupName := fmt.Sprintf("packer %s", hex.EncodeToString(identifier.NewUUID().Raw())) 39 log.Printf("Temporary group name: %s", groupName) 40 group := ec2.SecurityGroup{ 41 Name: groupName, 42 Description: "Temporary group for Packer", 43 VpcId: s.VpcId, 44 } 45 groupResp, err := ec2conn.CreateSecurityGroup(group) 46 if err != nil { 47 ui.Error(err.Error()) 48 return multistep.ActionHalt 49 } 50 51 // Set the group ID so we can delete it later 52 s.createdGroupId = groupResp.Id 53 54 // Authorize the SSH access 55 perms := []ec2.IPPerm{ 56 ec2.IPPerm{ 57 Protocol: "tcp", 58 FromPort: s.SSHPort, 59 ToPort: s.SSHPort, 60 SourceIPs: []string{"0.0.0.0/0"}, 61 }, 62 } 63 64 ui.Say("Authorizing SSH access on the temporary security group...") 65 if _, err := ec2conn.AuthorizeSecurityGroup(groupResp.SecurityGroup, perms); err != nil { 66 err := fmt.Errorf("Error creating temporary security group: %s", err) 67 state["error"] = err 68 ui.Error(err.Error()) 69 return multistep.ActionHalt 70 } 71 72 // Set some state data for use in future steps 73 state["securityGroupId"] = s.createdGroupId 74 75 return multistep.ActionContinue 76 } 77 78 func (s *StepSecurityGroup) Cleanup(state map[string]interface{}) { 79 if s.createdGroupId == "" { 80 return 81 } 82 83 ec2conn := state["ec2"].(*ec2.EC2) 84 ui := state["ui"].(packer.Ui) 85 86 ui.Say("Deleting temporary security group...") 87 88 var err error 89 for i := 0; i < 5; i++ { 90 _, err = ec2conn.DeleteSecurityGroup(ec2.SecurityGroup{Id: s.createdGroupId}) 91 if err == nil { 92 break 93 } 94 95 log.Printf("Error deleting security group: %s", err) 96 time.Sleep(5 * time.Second) 97 } 98 99 if err != nil { 100 ui.Error(fmt.Sprintf( 101 "Error cleaning up security group. Please delete the group manually: %s", s.createdGroupId)) 102 } 103 }