AWS Cloud Formation !Sub & !Ref functions inside AWS::Serverless::Function Policies

Viewed 16734

I have been using the !Sub function in my CloudFormation Yaml templates just fine. And when used it as an object property value it works for me

Object:
  Property1: !Sub some-value-with-a-${variable}-in-it

The value of variable gets replaced as expected.

However, I can't figure out how to use the !Sub function in an element of a string array

Array:
  - !Sub some-value-with-a-${variable}-in-it

That array element just gets ignored.

I am trying this in the context of a SAM template creating a AWS::Serverless::Function type resource. The Policies property can take an array of strings:

lambda:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: api
    FunctionName: !Sub api-${MyStageName}
    Handler: Lambda:Api.Function::HandleAsync
    Runtime: dotnetcore1.0
    Policies: 
    - AWSLambdaBasicExecutionRole
    - !Sub arn:aws:iam::${AWS::AccountId}:policy/some-policy
    - arn:aws:iam::123456789:policy/another-policy

The !Sub function works in the FunctionName property in this example. But I only end up with 2 Policies attached to my generated role - AWSLambdaBasicExecutionRole and arn:aws:iam::123456789:policy/another-policy. The one including the !Sub function gets ignored.

I have tried options like putting the function on a new line:

Array:
  - 
    !Sub some value with a ${variable} in it

Can anyone help?

Update

@Tom Melo pointed out that this is not a array problem so I have adjusted my question.

Further investigation has revealed it is not a Cloud Formation issue exactly, but very specific to the AWS::Serverless::Function resource type, and the Policies property within in. I suspect it has something to do with the fact that the Policies property is so flexible in what it can accept. It can accept strings referring to policy names or Arns, and it can also accept policy documents describing new policy. I suspect this means it is not able to support the functions.

2 Answers
Related