Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cloudformation create resource conditionally

I was looking at the Condition Function Fn::If: to create or provision a resource only if a condition is evaluated to true. In my case, created a policy if the environment is prod.

Parameters:
  Env:
    Description: Environment
    Type: String

Conditions:
  IsProd: !Equals [!Ref Env, 'prod']

I know how to do it for a property, but not for the entire resource block.

Type: 'AWS::IAM::Policy'
Properties:
  PolicyName: root
  PolicyDocument:
    Version: 2012-10-17
    Statement:
      - Effect: Allow
        Action: '*'
        Resource: '*'
  Roles:
    - !Ref RootRole

Is this something possible?

like image 710
Peter Avatar asked Jun 23 '20 22:06

Peter


People also ask

Which section of CloudFormation does not allow for conditions?

According to the docs, Conditions should be used at the top level of the resource you want to conditionally create. Putting a Condition inside the Instance UserData section isn't supported. To use Conditions in your situation, you'd want separate Resources conditionally created based on the Parameter.

What is pseudo parameter in AWS CloudFormation?

Pseudo parameters are parameters that are predefined by AWS CloudFormation. You don't declare them in your template. Use them the same way as you would a parameter, as the argument for the Ref function.

What is FN :: if?

Fn::If. Returns one value if the specified condition evaluates to true and another value if the specified condition evaluates to false .


1 Answers

You can do it using Condition: resource attribute. For example:


Resources:

    MyIAMPolicy:

        Condition: IsProd

        Type: 'AWS::IAM::Policy'
        Properties:
          PolicyName: root
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action: '*'
                Resource: '*'
          Roles:
            - !Ref RootRole

More on this can be found here:

  • Conditionally launch AWS CloudFormation resources based on user input
like image 155
Marcin Avatar answered Nov 15 '22 05:11

Marcin