Skip to content

Commit e85974b

Browse files
authored
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
1 parent a6d5d52 commit e85974b

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

iterative/aws/provider.go

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ var (
2828
}
2929
)
3030

31-
//ResourceMachineCreate creates AWS instance
31+
// ResourceMachineCreate creates AWS instance
3232
func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interface{}) error {
3333
userData := d.Get("startup_script").(string)
3434
pairName := d.Id()
@@ -216,20 +216,45 @@ func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interf
216216
},
217217
},
218218
}
219-
// use availability zone from user
220-
if availabilityZone != "" && subnetId == "" {
219+
220+
if subnetId == "" {
221+
if availabilityZone == "" {
222+
offeringsInput := &ec2.DescribeInstanceTypeOfferingsInput{
223+
LocationType: types.LocationTypeAvailabilityZone,
224+
Filters: []types.Filter{
225+
{
226+
Name: aws.String("instance-type"),
227+
Values: []string{instanceType},
228+
},
229+
},
230+
}
231+
232+
for offeringsPaginator := ec2.NewDescribeInstanceTypeOfferingsPaginator(svc, offeringsInput); offeringsPaginator.HasMorePages(); {
233+
page, err := offeringsPaginator.NextPage(ctx)
234+
if err != nil {
235+
return err
236+
}
237+
238+
if offerings := page.InstanceTypeOfferings; len(offerings) > 0 {
239+
availabilityZone = aws.ToString(offerings[0].Location)
240+
break
241+
}
242+
}
243+
}
244+
245+
// use availability zone
221246
subnetOptions.Filters = append(subnetOptions.Filters, types.Filter{
222247
Name: aws.String("availability-zone"),
223248
Values: []string{availabilityZone},
224249
})
225-
}
226-
// use exact subnet-id from user
227-
if subnetId != "" {
250+
} else {
251+
// use exact subnet-id from user
228252
subnetOptions.Filters = append(subnetOptions.Filters, types.Filter{
229253
Name: aws.String("subnet-id"),
230254
Values: []string{subnetId},
231255
})
232256
}
257+
233258
subDesc, err := svc.DescribeSubnets(ctx, subnetOptions)
234259
if err != nil {
235260
return decodeAWSError(region, err)
@@ -385,7 +410,7 @@ func ResourceMachineCreate(ctx context.Context, d *schema.ResourceData, m interf
385410
return nil
386411
}
387412

388-
//ResourceMachineDelete deletes AWS instance
413+
// ResourceMachineDelete deletes AWS instance
389414
func ResourceMachineDelete(ctx context.Context, d *schema.ResourceData, m interface{}) error {
390415
id := aws.String(d.Id())
391416
region := GetRegion(d.Get("region").(string))

0 commit comments

Comments
 (0)