Search code examples
amazon-web-servicesaws-cloudformation

Cloudformation proper way of passing in variables


I have a cloudformation role that I want to setup with a parameter that gets passed in, right now it looks like this:

  ClusterAutoscalerRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub ${Environment}-cluster-autoscaler
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Federated: !Sub "arn:aws:iam::${AWS::AccountId}:oidc-provider/${OIDCProviderUrl}"
            Action: sts:AssumeRoleWithWebIdentity
            Condition:
              StringEquals:
                "${OIDCProviderUrl}:sub": "system:serviceaccount:kube-system:cluster-autoscaler"
                "${OIDCProviderUrl}:aud": "sts.amazonaws.com"

But right now it seems OIDCProviderUrl gets subbed out correctly in the federated field, but not for string equals, and adding a !Sub prefix gives the error unhashable type: 'dict'


Solution

  • I think you can assign AssumeRolePolicyDocument as JSON string instead which you can then sub in OIDCProviderUrl variable in StringEquals condition keys

      ClusterAutoscalerRole:
        Type: AWS::IAM::Role
        Properties:
          RoleName: !Sub ${Environment}-cluster-autoscaler
          AssumeRolePolicyDocument:
            Fn::Sub: |
                {
                  "Version": "2012-10-17",
                  "Statement": [
                    {
                      "Effect": "Allow",
                      "Principal": {
                        "Federated": "arn:aws:iam::${AWS::AccountId}:oidc-provider/${OIDCProviderUrl}"
                      },
                      "Action": "sts:AssumeRoleWithWebIdentity",
                      "Condition": {
                        "StringEquals": {
                          "${OIDCProviderUrl}:sub": "system:serviceaccount:kube-system:cluster-autoscaler",
                          "${OIDCProviderUrl}:aud": "sts.amazonaws.com"
                        }
                      }
                    }
                  ]
                }