From e85974b319c6db1621b24dccfc21fcdd4c302a04 Mon Sep 17 00:00:00 2001 From: Helio Machado <0x2b3bfa0+git@googlemail.com> Date: Wed, 14 Sep 2022 20:00:40 +0200 Subject: [PATCH] Automate AWS availability zone selection (#670) * Automate AWS availability zone selection * Apply suggestions from code review * fixup! Apply suggestions from code review * Apply suggestions from code review --- iterative/aws/provider.go | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/iterative/aws/provider.go b/iterative/aws/provider.go index b1ded6fc..1b3abf3f 100644 --- a/iterative/aws/provider.go +++ b/iterative/aws/provider.go @@ -28,7 +28,7 @@ var ( } ) -//ResourceMachineCreate creates AWS instance +// ResourceMachineCreate creates AWS instance func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interface{}) error { userData := d.Get("startup_script").(string) pairName := d.Id() @@ -216,20 +216,45 @@ func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interf }, }, } - // use availability zone from user - if availabilityZone != "" && subnetId == "" { + + if subnetId == "" { + if availabilityZone == "" { + offeringsInput := &ec2.DescribeInstanceTypeOfferingsInput{ + LocationType: types.LocationTypeAvailabilityZone, + Filters: []types.Filter{ + { + Name: aws.String("instance-type"), + Values: []string{instanceType}, + }, + }, + } + + for offeringsPaginator := ec2.NewDescribeInstanceTypeOfferingsPaginator(svc, offeringsInput); offeringsPaginator.HasMorePages(); { + page, err := offeringsPaginator.NextPage(ctx) + if err != nil { + return err + } + + if offerings := page.InstanceTypeOfferings; len(offerings) > 0 { + availabilityZone = aws.ToString(offerings[0].Location) + break + } + } + } + + // use availability zone subnetOptions.Filters = append(subnetOptions.Filters, types.Filter{ Name: aws.String("availability-zone"), Values: []string{availabilityZone}, }) - } - // use exact subnet-id from user - if subnetId != "" { + } else { + // use exact subnet-id from user subnetOptions.Filters = append(subnetOptions.Filters, types.Filter{ Name: aws.String("subnet-id"), Values: []string{subnetId}, }) } + subDesc, err := svc.DescribeSubnets(ctx, subnetOptions) if err != nil { return decodeAWSError(region, err) @@ -385,7 +410,7 @@ func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interf return nil } -//ResourceMachineDelete deletes AWS instance +// ResourceMachineDelete deletes AWS instance func ResourceMachineDelete(ctx context.Context, d *schema.ResourceData, m interface{}) error { id := aws.String(d.Id()) region := GetRegion(d.Get("region").(string))