Home > Back-end >  CloudFormation - how to reference subnet id in a service
CloudFormation - how to reference subnet id in a service

Time:10-24

I'm completely new to AWS so sorry for asking some lame questions.

This is a part of my ecs.yml file which I'm trying to deploy via CloudFormation:

AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  SubnetID:
    Type: String
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: '10.0.0.0/16'
  PublicSubnetOne:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: { Ref: 'AWS::Region' }
      VpcId: !Ref 'VPC'
      CidrBlock: '10.0.1.0/24'
      MapPublicIpOnLaunch: true
...
  Service:
    Type: AWS::ECS::Service
    Properties:
      ServiceName: tui-task-service
      Cluster: !Ref Cluster
      TaskDefinition: !Ref TaskDefinition
      DesiredCount: 1
      LaunchType: FARGATE
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          Subnets:
            - !Ref SubnetID
          SecurityGroups:
            - !GetAtt ContainerSecurityGroup.GroupId

At the moment I pass an existing subnet id (I assume it comes from the VPC which is created by default when you create an AWS account) like this:

aws cloudformation create-stack --stack-name my-deployment --template-body file://ecs.yml \
  --capabilities CAPABILITY_NAMED_IAM \
  --parameters 'ParameterKey=SubnetID,ParameterValue=subnet-069412dc3b3a4a639'

I want to reference the subnet I create at the beginning of the template, how exactly do I do that? I tried !GetAtt PublicSubnetOne, but not sure which property to reference.

CodePudding user response:

You are on the right track. To reference the ID of the Subnet you create at the beginning of your template you can use !GetAtt PublicSubnetOne.SubnetId or !Ref PublicSubnetOne

To determine the available attributes for a specific resource look at the Return Values for the resource type. e.g. AWS::EC2::Subnet

Ref

When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns the ID of the subnet.

In this case the !Ref function returns the ID of the subnet which is also what the !GetAtt function does when you specify the SubnetId attribute

SubnetId

The ID of the Subnet

  • Related