user391
user391

Reputation: 105

Conditions in cloudformation

I have a cloudformation that creates two instances. I want to create a condition that only creates one instance in Beta i.e. (PrimaryEC2Instance) and creates (PrimaryEC2Instance & SecondaryEC2Instances) in Gamma and prod.

Mappings:
    AccountToStage:
        "123456789123":
            StageName: Beta
        "98765432101":
            StageName: Gamma
        "12365432101":
            StageName: Prod
    
    Beta:
      us-east-1:
        AmiId: "ami-0edae12356789012"
    Gamma:
      us-east-1:
        AmiId: "ami-0edae99999989012"
    Prod:
      us-east-1:
        AmiId: "ami-0edae88888889012"

Resources:

  PrimaryEC2Instance:
    Type: AWS::EC2::Instance

  SecondaryEC2Instance:
    Type: AWS::EC2::Instance

Below is the condition, that I have created.

Conditions:
  ISNotProduction: !Equals
    - !FindInMap
      - AccountToStage
      - !Ref "AWS::AccountId"
      - StageName
    - "Beta"
  ISProduction:
      "Fn::Not":
        - Condition: ISNotProduction

If I use the above condition in the resources section when deploying in Beta stage, cloudformation ignores the condition and and still creates two instances. Note: Since I want to create (PrimaryEC2Instance) in all stages, i have not added the condition in PrimaryEC2Instance section.

Resources:

  PrimaryEC2Instance:
    Type: AWS::EC2::Instance

  SecondaryEC2Instance:
    Condition: ISProduction
    Type: AWS::EC2::Instance

Any pointers are much appreciated ?

Upvotes: 2

Views: 430

Answers (1)

Marcin
Marcin

Reputation: 238209

You can simply your condition, by simply checking for Not Beta:

Conditions:

  IsNotBeta: 
   "Fn::Not":
      - !Equals
          - !FindInMap
            - AccountToStage
            - !Ref "AWS::AccountId"
            - StageName
          - "Beta"

Resources:

  PrimaryEC2Instance:
    Type: AWS::EC2::Instance

  SecondaryEC2Instance:
    Condition: IsNotBeta
    Type: AWS::EC2::Instance

Upvotes: 1

Related Questions