Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Formation: How to get VPC from Subnet Id

I have a Cloud Formation to set up an EC2 instance. I'm currently using the Parameters to specify the Subnet Id for the EC2 instance as well as the VPC Id for the Security Group (to be used in turn by the EC2 instance).

In my situation the Subnet Id specified is required to be part of the VPC and I'd like to only have to specify the Subnet Id in the Parameters. But I can't find a way to derive the VPC from the Subnet Id (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html)

I see the GetAtt function can be used to return resource attributes. Is there something equivalent to return resource properties?

like image 896
ysalmi Avatar asked Oct 24 '25 07:10

ysalmi


2 Answers

From the documentation Fn:GetAtt, you can only retrieve AvailabilityZone and Ipv6CidrBlocks details of the Subnet. There is no inbuilt support to get VpcId of the given subnet in CFn Templates.

There is a work-around though. If you are using the aws-cli documentation, you can use the describe-subnets method to fetch the VpcId of the required subnet and pass it as input to the Cloudformation template create_stack call.

This method works even if you are using any SDK. for example, in Java.

//pseudo code only! 
DescribeSubnetsRequest request = new DescribeSubnetsRequest();
request.withSubnetIds("subnet-abcdefgh");

DescribeSubnetsResult result = awsClient.describeSubnets(request);
String myVpc = result.getSubnets().get(0).getVpcId();

// add the above VPC Id to the parameters of your Cloud formation template create stack request.

Hope this helps.

like image 140
krisnik Avatar answered Oct 25 '25 20:10

krisnik


I created a small project called cli2cloudformation. Using that you're able to execute cli commands inside your cloudformation stack and use the results of the commands.

Just check it here. I hope it helps you.

like image 28
Lucio Veloso Guimarães Avatar answered Oct 25 '25 20:10

Lucio Veloso Guimarães



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!