How to use !FindInMap in !Sub | userdata section

2019-04-11 16:57发布

问题:

Currently I am converting CFT from JSON to Yaml. Everything works fine until Userdata section.I am having hard time to use any of functions like !Ref or !FindInMap in userdata section.

UserData:

Fn::Base64: !Sub |
        #!/bin/bash -v
        /command {Fn::FindInMap: [ "url", Ref: AWS::Region, Ref: EnvironmentType ] } 

It would be very helpful, If anyone can share any snippet of code.

回答1:

I've been having fun and games with this as well. Although the documentation says that Fn::FindInMap is supported in Fn::Sub, there's no example of use and I've tried all sorts of combinations of quotes and colons without success, but I finally seem to have hit upon a functional solution using mappings. The following should work:

Fn::Base64: !Sub
  - |+
    #!/bin/bash -v
    /command ${Url}
  - Url:
      Fn::FindInMap:
        - UrlMap
        - !Ref AWS::Region
        - !Ref EnvironmentType

The pipe at the start of arg0 tells YAML to preserve newlines, and the plus tells it to keep a newline afterwards. Arg1 tells it to substitute the result of the Fn::FindInMap for the Url in arg0.

The following shorter version should also work:

Fn::Base64: !Sub
  - |+
    #!/bin/bash -v
    /command ${Url}
  - Url:
      Fn::FindInMap: [UrlMap, Ref: "AWS::Region", Ref: EnvironmentType]

But you should test that. Note the commas, quotes, and reversion to Ref:s rather than !Refs. This probably tells us something about how the files are being pre-processed, but I'm not sure what that is.

I'm sure that this solution is obvious to experienced YAMLers, but I was only just starting to get my head around JSON when all this YAMLy goodness was added to CloudFormation.



回答2:

This works fine for me

UserData :
  Fn::Base64 : !Sub
  - |
    #!/bin/bash -v
    export some_variable = ${url}
  - url : !FindInMap [Mapping, !Ref AWS::Region, !Ref EnvironmentType]