我的策略文件的目标:
- 如果没有适当的标记,则阻止创建资源
- 要求为特定标签提供某些值(例如,env 标签必须是 dev 或 stg 或 prd 等(
No. 2 按预期工作;但是,如果用户创建标签为空的 EC2 实例或只是忘记添加标签,则策略仍允许用户创建实例。
我尝试了 null 运算符(此处引用(,但它似乎不起作用。
另一个尝试是使用与 aws:tag-keys 值匹配的条件(此处引用(,但它似乎仅在使用 StringLike 比较运算符检查单个值时才有效
这是 Lambda 函数关闭开发实例的先决条件。
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RequireEnvTags",
"Effect": "Deny",
"Action": [
"ec2:RunInstances"
],
"Condition": {
"ForAnyValue:StringNotEquals": {
"ec2:ResourceTag/env": [
"dev",
"stg",
"prd",
"dev-noshutdown"
]
}
},
"Resource": [
"*"
]
},
{
"Sid": "RequireDataSensitivity1",
"Effect": "Deny",
"Action": [
"ec2:RunInstances"
],
"Condition": {
"ForAnyValue:StringNotEquals": {
"ec2:ResourceTag/data-sensitivity": [
"public",
"internal",
"confidential",
"highly confidential"
]
}
},
"Resource": [
"*"
]
},
{
"Sid": "NullChecksDontSeemToWork0",
"Effect": "Deny",
"Action": [
"ec2:RunInstances"
],
"Condition": {
"Null": {
"ec2:ResourceTag/Name": "true"
}
},
"Resource": [
"*"
]
},
{
"Sid": "NullChecksDontSeemToWork1",
"Effect": "Deny",
"Action": [
"ec2:RunInstances"
],
"Condition": {
"Null": {
"ec2:ResourceTag/team": "true"
}
},
"Resource": [
"*"
]
}
]
}
使用这个后,我发现它只需要稍微调整一下。出于某种原因,AWS 需要明确允许同一策略文档中的操作(即使附加到同一用户的另一个策略文档明确声明允许(才能正确实施预期的策略:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ec2:RunInstances",
"Resource": [
"arn:aws:ec2:*::image/ami-*",
"arn:aws:ec2:*:ACCOUNT_ID:subnet/*",
"arn:aws:ec2:*:ACCOUNT_ID:network-interface/*",
"arn:aws:ec2:*:ACCOUNT_ID:volume/*",
"arn:aws:ec2:*:ACCOUNT_ID:key-pair/*",
"arn:aws:ec2:*:ACCOUNT_ID:security-group/*"
],
"Sid": "AllowRunInstances"
},
{
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:ACCOUNT_ID:instance/*",
"Condition": {
"StringNotLike": {
"aws:RequestTag/env": [
"dev",
"stg",
"prd",
"dev-noshutdown",
"trn",
"tst"
]
}
},
"Sid": "RequireSpecificEnvTags"
}
]
}
它有效!
快速说明:目前,此策略似乎不允许创建 Spot 实例(因为 Spot 请求处理标签的方式存在差异(。我向 AWS 提交了功能请求。