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