AWS CloudFormation:能否将内置函数用作对象键?
Great question—this is a common gotcha with CloudFormation, since native YAML/JSON doesn’t let you use intrinsic functions directly as object keys. But there’s a straightforward workaround using !JsonDecode paired with !Sub or !Join to construct the dynamic key as part of a JSON string, then convert it back to an object.
Here’s how to implement it for your Cognito User Pool + Client ID scenario:
Example with !Sub (cleaner for readability)
RoleMappings: !JsonDecode !Sub | { "${CognitoUserPoolProvider}:${CognitoUserPoolClient}": { "Type": "Token", "AmbiguousRoleResolution": "AuthenticatedRole", # Add your specific mapping rules here "MatchingRule": { "Claim": "cognito:groups", "MatchType": "Contains", "Value": "admin" } } }
Example with !Join (if you need more control over string concatenation)
RoleMappings: !JsonDecode !Join - '' - - '{"' - !Join [':', [!Ref CognitoUserPoolProvider, !Ref CognitoUserPoolClient]] - '": {"Type": "Token", "AmbiguousRoleResolution": "AuthenticatedRole"}}'
How this works:
- First, we use
!Subor!Jointo build a valid JSON string where the key is the concatenated value of your ProviderName and Client ID. - Then
!JsonDecodeparses that string into a CloudFormation object, which the service recognizes as validRoleMappings.
This approach avoids the "invalid template" error because we’re not trying to use an intrinsic function directly as an object key—instead, we’re constructing the entire object structure as a string first, then converting it to the required format. I’ve used this pattern successfully for Cognito role mappings and other dynamic-key scenarios in CloudFormation, so it should work seamlessly with your existing deployment.
内容的提问来源于stack exchange,提问作者Turner Houghton

