AWS CloudFormation YAML 模板中的一个转义策略变量如何
How does one escape policy variables in AWS CloudFormation YAML templates
我一直在尝试以 YAML 格式编写许多 AWS CloudFormation 模板。
我在尝试结合替换解析 IAM 策略变量(例如 ${aws:username}
)时遇到了 CloudFormation 问题。示例如下:
CommonUserGroup:
Type: AWS::IAM::Group
Properties:
GroupName: Common
Path: /project/
Policies:
- PolicyName: ClusterPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: "iam:GetAccountPasswordPolicy"
Resource: "*"
- Effect: Allow
Action: "iam:ChangePassword"
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${aws:username}'
当使用 CloudFormation 模板尝试创建堆栈时,返回以下错误:
Template validation error: Template format error: Unresolved resource dependencies [aws:username] in the Resources block of the template
如果我手动指定用户名,而不是使用策略变量,例如:
'arn:aws:iam::${AWS::AccountId}:user/bob'
然后错误消失。
有没有一种方法可以使 CloudFormation 不尝试将策略变量解析为模板的一部分?
经过一番搜索后,我发现了以下 Reddit post,其中提到了同样的问题:Creating No MFA No Access policy via YAML template - substitution issues
对该主题的回复引用了以下 AWS CloudFormation 文档:Filter View: Fn::Sub,其中指出:
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}.
这可以用来逃避策略变量。
因此在我的问题示例中,${aws:username}
可以在 YAML 中转义为 ${!aws:username}
。
我一直在尝试以 YAML 格式编写许多 AWS CloudFormation 模板。
我在尝试结合替换解析 IAM 策略变量(例如 ${aws:username}
)时遇到了 CloudFormation 问题。示例如下:
CommonUserGroup:
Type: AWS::IAM::Group
Properties:
GroupName: Common
Path: /project/
Policies:
- PolicyName: ClusterPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: "iam:GetAccountPasswordPolicy"
Resource: "*"
- Effect: Allow
Action: "iam:ChangePassword"
Resource: !Sub 'arn:aws:iam::${AWS::AccountId}:user/${aws:username}'
当使用 CloudFormation 模板尝试创建堆栈时,返回以下错误:
Template validation error: Template format error: Unresolved resource dependencies [aws:username] in the Resources block of the template
如果我手动指定用户名,而不是使用策略变量,例如:
'arn:aws:iam::${AWS::AccountId}:user/bob'
然后错误消失。
有没有一种方法可以使 CloudFormation 不尝试将策略变量解析为模板的一部分?
经过一番搜索后,我发现了以下 Reddit post,其中提到了同样的问题:Creating No MFA No Access policy via YAML template - substitution issues
对该主题的回复引用了以下 AWS CloudFormation 文档:Filter View: Fn::Sub,其中指出:
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}.
这可以用来逃避策略变量。
因此在我的问题示例中,${aws:username}
可以在 YAML 中转义为 ${!aws:username}
。