Explicit deny for user to runinstances in AWS when not using specific tag KeyValue

不羁的心 提交于 2019-12-06 04:15:03

You can use the below IAM Policy and edit as per your liking. I use this in production and works flawlessly. It will only launch instances if they are tagged with values present in the list.:

Here, Key = Environment, Value = mentioned below

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "TheseActionsDontSupportResourceLevelPermissions",
            "Effect": "Allow",
            "Action": [
                "ec2:Describe*"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:RunInstances",
            "Resource": [
                "arn:aws:ec2:*::image/ami-*",
                "arn:aws:ec2:*:ACCOUNT_ID:volume/*",
                "arn:aws:ec2:*:ACCOUNT_ID:subnet/*",
                "arn:aws:ec2:*:ACCOUNT_ID:network-interface/*",
                "arn:aws:ec2:*:ACCOUNT_ID:security-group/*",
                "arn:aws:ec2:*:ACCOUNT_ID:key-pair/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Deny",
            "Action": "ec2:RunInstances",
            "Resource": "arn:aws:ec2:*:ACCOUNT_ID:instance/*",
            "Condition": {
                "StringNotLike": {
                    "aws:RequestTag/Environment": [
                        "Testing",
                        "Staging",
                        "Production",
                        "Nightly",
                        "Sandbox",
                        "LoadTesting"
                    ]
                }
            }
        }
    ]
}

It is not working because the following block is implementing a logical OR. So, the instance will be launched if any of the condition is met. You have to create a logical AND by separating the condition keys in two different blocks as mentioned here.

"Condition": {
            "ForAllValues:StringNotEquals": {
                "aws:TagKeys": "Name",
                "aws:RequestTag/Name": "${aws:username}"
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!