Home > Software design >  how to add a condition when writing a aws policy via cloudformation?
how to add a condition when writing a aws policy via cloudformation?

Time:11-02

I am creating some IAM roles, policies via cloudformation but I would like to add policies based on the condition I have, say if it is dev then i would like to add certain policy statement. any suggestions ?

Parameters:
    environment:
        Type: String
        Default: dev
        AllowedValues:
            - dev
            - prd
Condition:
    isDev: !Equals [ !Ref environment, dev]

Resources:
  StandAlonePolicy:
    Type: AWS::IAM::Policy
    Properties:
      #How to add a condition - isDev
      PolicyName: "s3-policy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Resource: "*"
          Action:
            - "s3:Get*"

CodePudding user response:

You can do this using If:

Parameters:
    environment:
        Type: String
        Default: dev
        AllowedValues:
            - dev
            - prd
Conditions:
    isDev: !Equals [ !Ref environment, dev]

Resources:
  StandAlonePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: "s3-policy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Resource: "*"
          Action:
            - "s3:Get*"
        - !If    
            - isDev
            - Sid: new-statement-for-dev-only
              Effect: Allow
              Resource: "*"
              Action:
                - "s3:Put*"
            - !Ref "AWS::NoValue"
  • Related