问题描述
我正在尝试限制我的 IAM 角色,因此我只能启动/停止具有特定标签名称的 EC2 实例 大概这是一个常见的用例,以确保您不会启动/停止/删除错误的 EC2 实例!
我创建了这个角色:
"Effect": "Allow","Action": [
"ec2:RunInstances","ec2:StartInstances","ec2:StopInstances","ec2:TerminateInstances"
],"Resource": "*","Condition": {
"StringEquals": {
"ec2:ResourceTag/Name": [
"InstanceName","InstanceName_Two"
]
}
}
}
(基于 https://github.com/hashicorp/packer/issues/1928 处的示例)
我正在尝试通过 boto3 创建一个实例:
{'ResourceType': 'instance','Tags': [{'Key': 'Name','Value': 'InstanceName'} }
但是我得到了错误
botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation
无需添加“ec2:ResourceTag/Name”条件即可正常工作
如何创建只能启动/停止具有特定名称的 EC2 实例的角色?
解决方法
您应该按照文档 Condition keys for Amazon EC2
使用aws:ResourceTag/${TagKey}
ResourceTag 全局条件。
以下政策运行良好。
{
"Version": "2012-10-17","Statement": [
{
"Sid": "VisualEditor0","Effect": "Allow","Action": [
"ec2:TerminateInstances","ec2:RunInstances","ec2:StartInstances","ec2:StopInstances"
],"Resource": "*","Condition": {
"StringEquals": {
"aws:ResourceTag/Name": [
"InstanceName","InstanceName_Two"
]
}
}
}
]
}
我不知道为什么你需要 ec2:RunInstances
许可,即使你提到了
仅启动/停止具有特定标签名称的 EC2 实例