3
votes

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?

2
This would be a useful feature but I don't believe that CloudFormation has a native way to do it. If it's important enough, perhaps you could use a Lambda-backed custom resource to do the lookup (similar example: docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/…).jarmod

2 Answers

2
votes

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.

1
votes

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.