aws-cloudformation

CloudFormation Combine Sub - Import - Sub


I am trying to create a parameter and would like to combine !Sub and !Import several times.

Parameters:
  Environment:
    Description: Stackname of Environment
    Type: String

Resources:

  IAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: '*'
          Action: ['sts:AssumeRole']
      Path: /
      Policies:
      - PolicyName: S3Files
        PolicyDocument:
          Statement:
          - Sid: 'S3Files'
            Effect: Allow
            Action:
              - 's3:DeleteObjectTagging'
              - 's3:GetObjectRetention'
              - 's3:ListMultipartUploadParts'
              - 's3:PutObject'
              - 's3:GetObjectAcl'
              - 's3:GetObject'
              - 's3:AbortMultipartUpload'
              - 's3:PutObjectRetention'
              - 's3:GetObjectVersionAcl'
              - 's3:GetObjectTagging'
              - 's3:PutObjectTagging'
              - 's3:DeleteObject'
              - 's3:PutObjectAcl'
              - 's3:GetObjectVersion'
            Resource: !Sub
                - '${ARN}/*'
                - ARN: 
                  Fn::ImportValue: !Sub ${Environment}:S3:Arn

According to the documentation it should be possible, but unfortunately I always get an error message Template contains errors.: [/Resources/IAMRole/Type/Policies/0/PolicyDocument/Statement/0/Resource/Fn::Sub/1/ARN] 'null' values are not allowed in templates

How could the UseCase work?


Solution

  • There is an indentation issue in the Resource section.

    Resource: !Sub
        - '${ARN}/*'
        - ARN: 
          Fn::ImportValue: !Sub ${Environment}:S3:Arn
    

    It should be

    Resource: !Sub
        - '${ARN}/*'
        - ARN: 
            Fn::ImportValue: !Sub ${Environment}:S3:Arn
    

    Note: Fn starts under N of ARN instead of A.

    Explanation: With the first indentation the line with Fn::ImportValue is considered as an input for !Sub, with the second indentation it becomes the value for ARN: defined the line above it.

    Side note: Use 2 spaces or 4 spaces or tabs uniformly throughout the template.