Reputation: 1345
I have a script that creates AWS instances and puts them in a subnet and availability zone.
But the availability zone has to correspond to the subnet, or else you get an error that says:
An error occurred (InvalidParameterValue) when calling the RunInstances operation: Value (us-east-1f) for parameter availabilityZone is invalid. Subnet 'subnet-87bd70ca' is in the availability zone us-east-1c
This is the code I have so far:
import boto3
import objectpath
subnet_id = input("Enter the subnet id: ")
public_ip = input("Create a public ip (True|False): ")
private_ip = input("Enter the private IP address: ")
availability_zones = ec2_client.describe_availability_zones()
tree = objectpath.Tree(availability_zones)
availability_zones = set(tree.execute('$..ZoneName'))
availability_zones = list(availability_zones)
availability_zones = str(availability_zones).replace('[','').replace(']','').replace('\'','')
availability_zone = input("Enter the availability zone: ")
instances = ec2_resource.create_instances(
ImageId=image_id,
InstanceType=instance_type,
KeyName=key_name,
MaxCount=max_count,
MinCount=1,
DryRun=False,
DisableApiTermination=True,
EbsOptimized=False,
Placement={
'AvailabilityZone': availability_zone,
'Tenancy': tenancy,
},
InstanceInitiatedShutdownBehavior='stop',
NetworkInterfaces=[
{
'AssociatePublicIpAddress': public_ip,
'DeleteOnTermination': True,
'DeviceIndex': 0,
'PrivateIpAddress': private_ip,
'SubnetId': subnet_id,
'Groups': [
sg_id
]
}
]
)
Is there a way I can find out what availabilty zone a subnet belongs to?
Upvotes: 1
Views: 960
Reputation: 270224
If you specify a subnet, there is no need to specify an Availability Zone.
This is because a subnet exists in only one Availability Zone. Therefore, supplying the subnet also tells EC2 which AZ to use.
Upvotes: 2
Reputation: 349
While i don't have the exact answer, i'm thinking you could find the function in boto
that returns similar results to aws ec2 describe-subnets
then create a validation function from that.
You should look into terraform, this is a wheel i had reinvented but doesn't need to be.
HTH
Upvotes: 0