George
George

Reputation: 1

Is there a way to select from a list of subnets where to launch an EC2 instance in CloudFormation?

I'm trying to do a CF template to spin up three different environments but I want to be able to select in which subnet the EC2 instance is launched without hardcoding a specific subnet in the template. In my example below however I get an error that SubnetId must be a string. I can't think of any other way to achieve this. Any thoughts?

Parameters:
  EnvironmentType:
    Type: String
    Default: Dev  
    AllowedValues:
      - Dev  
      - Test 
      - Production
    Description: Select Environment Type (Dev, Test, Production)
  SubnetIdList:
    Type: String
    AllowedValues: 
      - Public1
      - Public2
      - Private
    Description: Select a subnet
  
    

Mappings:
  InstanceSize:
    Dev:
      "EC2" : "t3.micro"
    Test:
      "EC2" : "t3.small"
    Production:
      "EC2" : "t3.medium"
  Sub:
    Public1:
      "Subnet" : "subnet-05daa558dc3f65529" #public 1
    Public2:
      "Subnet" : "subnet-0f57bb83e0fc545f4" #public 2
    Private:
      "Subnet" : "subnet-0eb76c49954acc803" #Private
    
    
    

Resources:
  EC2:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0080e4c5bc078760e
      InstanceType: !FindInMap [InstanceSize, !Ref EnvironmentType, EC2]
      KeyName: Ashkelon
      SubnetId: [Sub, !Ref SubnetIdList, Subnet]

Upvotes: 0

Views: 518

Answers (1)

mmuppidi
mmuppidi

Reputation: 101

I think you are just missing !FindInMap in your Ec2 subnet parameter definition. See below

Resources:
  EC2:
     Type: AWS::EC2::Instance
     Properties:
     ImageId: ami-0080e4c5bc078760e
     InstanceType: !FindInMap [InstanceSize, !Ref EnvironmentType, EC2]
     KeyName: Ashkelon
     SubnetId: !FindInMap [Sub, !Ref SubnetIdList, Subnet]

Upvotes: 1

Related Questions