Home > database >  In AWS cloud formation template how attach policy to a role based on environment
In AWS cloud formation template how attach policy to a role based on environment

Time:09-01

I am trying to attach policy to a role only if the environment is dev or qa. I tried the below code but it is giving template error. 'Template error: every Fn::Or object requires a list of at least 2 and at most 10 boolean parameters.'

The Role contains other policies as well but i would like to attach the policy "arn:aws:iam::111111111111:policy/attach-s3-policy" only if the environment is dev or qa.

Any help would be highly appreciated. If below is not the right way could you please suggest a right way to achieve this.

AWSTemplateFormatVersion: '2010-09-09'
Description: AWS CloudFormation template

Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - qa
      - prod
    Description: Enter dev, qa, prod. Default is dev.

Conditions:
  dev: !Equals [!Ref Environment, dev]
  qa: !Equals [!Ref Environment, qa]
  prd: !Equals [!Ref Environment, prod]
  devandqa: !Or [!Equals [!Ref Environment, dev],  [!Ref Environment, qa]]
  

Resources:
  ManagedInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::111111111111:policy/service-role/AWSGlueServiceRole-test-glue-crawler-role
      - Fn::If:
         - devandqa
         - "arn:aws:iam::111111111111:policy/attach-s3-policy"
         - "Ref" : "AWS::NoValue"

CodePudding user response:

Your approach is correct, you can use the Fn::If construct to conditionally use a certain property.

The issue with the template you've shared is the devandqa condition. It should be:

devandqa: !Or [!Equals [!Ref Environment, dev], !Equals [!Ref Environment, qa]]

you were missing the second !Equals, so !Or couldn't be resolved hence the error.

  • Related