github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/alicloud/ecs/step_config_vpc.go (about) 1 package ecs 2 3 import ( 4 "errors" 5 "fmt" 6 "time" 7 8 "github.com/denverdino/aliyungo/common" 9 "github.com/denverdino/aliyungo/ecs" 10 "github.com/hashicorp/packer/packer" 11 "github.com/mitchellh/multistep" 12 ) 13 14 type stepConfigAlicloudVPC struct { 15 VpcId string 16 CidrBlock string //192.168.0.0/16 or 172.16.0.0/16 (default) 17 VpcName string 18 isCreate bool 19 } 20 21 func (s *stepConfigAlicloudVPC) Run(state multistep.StateBag) multistep.StepAction { 22 config := state.Get("config").(Config) 23 client := state.Get("client").(*ecs.Client) 24 ui := state.Get("ui").(packer.Ui) 25 26 if len(s.VpcId) != 0 { 27 vpcs, _, err := client.DescribeVpcs(&ecs.DescribeVpcsArgs{ 28 VpcId: s.VpcId, 29 RegionId: common.Region(config.AlicloudRegion), 30 }) 31 if err != nil { 32 ui.Say(fmt.Sprintf("Failed querying vpcs: %s", err)) 33 state.Put("error", err) 34 return multistep.ActionHalt 35 } 36 if len(vpcs) > 0 { 37 vpc := vpcs[0] 38 state.Put("vpcid", vpc.VpcId) 39 s.isCreate = false 40 return multistep.ActionContinue 41 } 42 message := fmt.Sprintf("The specified vpc {%s} doesn't exist.", s.VpcId) 43 state.Put("error", errors.New(message)) 44 ui.Say(message) 45 return multistep.ActionHalt 46 47 } 48 ui.Say("Creating vpc") 49 vpc, err := client.CreateVpc(&ecs.CreateVpcArgs{ 50 RegionId: common.Region(config.AlicloudRegion), 51 CidrBlock: s.CidrBlock, 52 VpcName: s.VpcName, 53 }) 54 if err != nil { 55 state.Put("error", err) 56 ui.Say(fmt.Sprintf("Failed creating vpc: %s", err)) 57 return multistep.ActionHalt 58 } 59 err = client.WaitForVpcAvailable(common.Region(config.AlicloudRegion), vpc.VpcId, ALICLOUD_DEFAULT_SHORT_TIMEOUT) 60 if err != nil { 61 state.Put("error", err) 62 ui.Say(fmt.Sprintf("Failed waiting for vpc to become available: %s", err)) 63 return multistep.ActionHalt 64 } 65 66 state.Put("vpcid", vpc.VpcId) 67 s.isCreate = true 68 s.VpcId = vpc.VpcId 69 return multistep.ActionContinue 70 } 71 72 func (s *stepConfigAlicloudVPC) Cleanup(state multistep.StateBag) { 73 if !s.isCreate { 74 return 75 } 76 77 client := state.Get("client").(*ecs.Client) 78 ui := state.Get("ui").(packer.Ui) 79 80 message(state, "VPC") 81 timeoutPoint := time.Now().Add(60 * time.Second) 82 for { 83 if err := client.DeleteVpc(s.VpcId); err != nil { 84 e, _ := err.(*common.Error) 85 if (e.Code == "DependencyViolation.Instance" || e.Code == "DependencyViolation.RouteEntry" || 86 e.Code == "DependencyViolation.VSwitch" || 87 e.Code == "DependencyViolation.SecurityGroup") && time.Now().Before(timeoutPoint) { 88 time.Sleep(1 * time.Second) 89 continue 90 } 91 ui.Error(fmt.Sprintf("Error deleting vpc, it may still be around: %s", err)) 92 return 93 } 94 break 95 } 96 }