Get AZ of a subnet through cloudformation script

Viewed 1205

I need to do something like... "echo --zones ", { "Ref": "az_of_subnet" }, " >> aws_details.txt\n"

in the user-data of an EC2 instance which is being created through the cloudformation script. The Subnet ID of an EXISTING subnet is known. Is there a way to get the availability zone of the subnet? Currently I'm taking this as an input (az_of_subnet) from the user, which seems redundant/not right, since I already know the subnet-id.

4 Answers

You will need to write a custom Lambda function to get the AZ for the VPC subnet ID.

There are a number of oddities about availability zones. My us-west-2a may or my not be the same as your us-west-2a. Amazon randomizes the actual data centers to load balance, etc.

Here is a link on how to create a custom function that CloudFormation can call.

AWS Lambda-backed Custom Resources

An interesting article about CloudFormation and Availability Zones

Using Lambda to get a users Availability Zone list in Cloud Formation

I have been kicking this around a bit and wonder why you just can't use an SSM Stored Parameter? Yes, it's a few minutes of work to get it set up, but once it's set, it's not like it will change much.

Go into SSM, create a Stored Parameter... SubnetId for the name, AZ for the parameter. Since the Subnets are already created, then the info is there. You can even output this info from CFN into SSM if you work at it to auto-populate SSM when CFN creations are done.

You can then pull that into your CloudFormation template pretty easy.

Best place to go look is here: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html

I feel that SSM Stored Parameters is often overlooked when you want to make your CFN templates a lot more dynamic. I have templates that, literally, can run in any environment without modification by using SSM.

Like I said though, it takes a little work to set it up, but a little bit here and there goes a long way.

You can see an example here on my repo. I have both YAML and JSON examples.

Just a thought.

EDIT:

Looks like AP wanted to use existing subnet which is not created in that cloud formation. So this is not currently supported in CloudFormation , so there might be 2 options(may be more) 1. Call APIs in user data script to get the AZ 2. Use terrform which supports this functionality

Lambda seems overkill; you can issue a curl command against the instance metadata:

curl http://169.254.169.254/latest/meta-data/placement/availability-zone

Throw this into your user-data to get the AZ

Related