0
votes

In a CloudFormation stack, I am creating an Interface type VPC Endpoint, and that requires SubnetIds as one of the parameters. I want to configure the VPC Endpoint in the same CloudFormation stack where I am provisioning the VPC and subnets.

The question is - How do I refer SubnetIds for Subnets created in the same stack? The intrinsic function GetAtt for Subnet does not support retrieving the subnet ids.

2
You can import the existing resources to CF. See here.jellycsc

2 Answers

0
votes

You can use the Ref intrinsic function on your Subnet resource such as the example below.

As well as attributes each CloudFormation resource also can support a Ref value, for the subnet this is the subnet id.

Resources: 
  mySubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId:
        Ref: myVPC
      CidrBlock: 10.0.0.0/24
      AvailabilityZone: "us-east-1a"
  Ec2Instance: 
    Type: AWS::EC2::Instance
    Properties:
      SubnetId:
        Ref: mySubnet

Simply use the Ref function within the template on the additional resources, this will also create a dependency relationship preventing resources from being created if they rely on the subnet.

0
votes

requires SubnetIds as one of the parameters.

If you provide subnets ids as part of the parameters to your template, you can use parameter with List<AWS::EC2::Subnet::Id> type:

Parameters:

  Subnets:
    Type: List<AWS::EC2::Subnet::Id>

Then in the rest of the code, could refer to entire list or individual subnets as follows:

!Ref Subnets # entire list 

!Select [0, !Ref Subnets] # first subnet provided in the list

If you create subnets in your template:

Resources: 
   
   MySubnet1:
     Type: AWS::EC2::Subnet
     Properties:
       # properties 

   MySubnet2:
     Type: AWS::EC2::Subnet
     Properties:
       # properties other subnet

Then to refer to their ids, you can use Ref which returns subnet id:

!Ref MySubnet1

!Ref MySubnet2

However, if you want to use existing subnets, defined outside of CloudFormation, in your templates, you can import existing subnets into your stack:

But this is not automatic process. You have to manually modify your template first for that to work.