Umar
Umar

Reputation: 1072

CloudFormation Joining List of Strings with FindInMap

I am facing issue with Cloudformation on joining a list of strings after getting it from a map.

Error caused is Security Group expects a list of string.

"123456":
    us-east-1:
      #VPC1
      VpcId: vpc-xxxx
      VpcCidr: 10.78.160.0/20
      SecurityGroups: sg-123
      AvailabilityZones: us-east-1a,us-east-1b,us-east-1c
"123457":
    us-east-1:
      #VPC
      VpcId: vpc-xxxx
      VpcCidr: 10.78.160.0/20
      SecurityGroups: sg-123,sg-124
      AvailabilityZones: us-east-1a,us-east-1b,us-east-1c
LaunchConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Metadata:
      AWS::CloudFormation::Init:
        config:
    Properties:
      InstanceType:
        Ref: InstanceType
      SecurityGroups: !Join [ ",", [!FindInMap [!Ref "AWS::AccountId", !Ref "AWS::Region", SecurityGroups], !Ref EC2SG ]]
      IamInstanceProfile:

please let me know how to get the list for securitygroups and adding it to another resource

Solved by using this question

How do I use nested lists or append to a list in Cloudformation?

Upvotes: 2

Views: 3150

Answers (1)

Balu Vyamajala
Balu Vyamajala

Reputation: 10333

Lets take mappings:

Mappings:
  "111222333444":
    us-east-1:
      SecurityGroups:
        - sg-abc
        - sg-xyz
    us-west-2:
      SecurityGroups:
        - sg-1234
        - sg-3456

Security groups can be referred as

SecurityGroupIds:
  "Fn::FindInMap":
    [!Ref AWS::AccountId, !Ref AWS::Region, SecurityGroups]

Define as array in mappings and pass the full array, this way we can avoid splitting and joining.

Full Template , tested on a Lambda

AWSTemplateFormatVersion: "2010-09-09"
Description: "Test"
Mappings:
  "111222333444":
    us-east-1:
      SecurityGroups:
        - sg-abc
        - sg-xyz
    us-west-2:
      SecurityGroups:
        - sg-1234
        - sg-3456
Resources:
  TestLambda:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: com.test.MainClass::handleRequest
      Runtime: java8
      FunctionName: "Test-Lambda"
      Code:
        S3Bucket: code-bucket
        S3Key: !Sub "artifacts/test.jar"
      Description: "Test Lambda"
      MemorySize: 512
      Timeout: 60
      Role: !Ref my-role-arn
      VpcConfig:
        SecurityGroupIds:
          "Fn::FindInMap":
            [!Ref AWS::AccountId, !Ref AWS::Region, SecurityGroups]
        SubnetIds:
          - subnet-1
          - subnet-2

Upvotes: 2

Related Questions