51

I want this resource to work with the !Sub (or Fn::Sub) intrinsic function

Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${aws:username}'

The aws:username is a policy variable that mustn't be replaced.

One solution would be to use Fn::Join instead and write a bit more boilerplate code.

Better: Can you escape the ${aws:username} so that !Sub will work here? Unfortunately, the documentation does not mention anything about escaping.

1 Answer 1

95

You actually can escape $ characters with ${!}.

So your resource would look like this:

Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${!aws:username}'

It is mentioned in the docs under the string parameter section.

To write a dollar sign and curly braces (${}) literally, add an exclamation point (!) after the open curly brace, such as ${!Literal}. AWS CloudFormation resolves this text as ${Literal}.

4
  • Yep, it was in the documentation. I'm feeling so silly right now.
    – mana
    Jun 12, 2017 at 7:44
  • 6
    That's a weird way to escape tho Oct 8, 2020 at 14:13
  • @mana Don't feel silly. There are a billion AWS doc pages - easy to miss things.
    – DarkNeuron
    Jul 28, 2021 at 14:24
  • @JayeshLalwani The ! is probably a flag for the parser similar the way it's used in intrinsic functions like !Sub, !Ref etc, in this case it just evaluates to literal text. But I don't know.
    – abk
    Apr 5 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.