AWS学习记录

2022-08-29 如何在AWS上限制使用AMI创建EC2

2022-08-29  本文已影响0人  清风晓星辰

写写我的个人学习心德,本文仅为个人学习心德,与AWS无关

通过Amazon Organization使用SCP可以限制多个aws accounts

将下列SCP复制,在aws organization管理account中,创建SCP并将其attach到相应OU或account中即可.SCP的说明请参考官方文档[1]
注意中国区,A要将所有ARN中的aws换成aws-cn

直接列出允许的AMI,拒绝其它

但是与IAM不同的是由于SCP不支持NotResource,唉!所以我们还是需要使用Condition。以下sample会对所有regions适用,只允许使用us-east-1和us-east-2这两个region的Amazon Linux AMI(同样的AMI在不同region其AMI ID也是不同的,所以需要穷举),如果只想对特定region限制,可以将*改为相应的region名

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "LaunchingEC2withAMIsAndTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": [
        "arn:aws:ec2:*::image/*"
      ],
      "Condition": {
        "StringNotEquals": {
          "ec2:ImageID": [
            "ami-05fa00d4c63e32376",
            "ami-0568773882d492fc8"
          ]
        }
      }
    }
  ]
}

使用Tag筛选AMI

Resource中ARN中的region,只对其一个region有效果,不会阻止其它region,如果想适用于所有region,可以请us-east-1替换为*

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "LaunchingEC2withAMIsAndTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1::image/ami-*",
      "Condition": {
        "StringNotEquals": {
          "ec2:ResourceTag/Environment":[ "Prod","Certified"]
        }
      }
    }
  ]
}

得到报错效果如下图:


Screen Shot 2022-08-31 at 08.58.27.png

使用IAM,可以控制单个user,role或group

直接列出允许的AMI

"arn:aws:ec2:us-east-1::image/ami-090fa75af13c156b4",
"arn:aws:ec2:us-east-2::image/ami-051dfed8f67f095f5",
为允许使用的AMI值,可以自行添加需要的值

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:RunInstances",
            "Resource": [
                "arn:aws:ec2:us-east-1::image/ami-090fa75af13c156b4",
                "arn:aws:ec2:us-east-2::image/ami-051dfed8f67f095f5",
                "arn:aws:ec2:*:<accountid>:subnet/*",
                "arn:aws:ec2:*:<accountid>:network-interface/*",
                "arn:aws:ec2:*:<accountid>:volume/*",
                "arn:aws:ec2:*:<accountid>:instance/*",
                "arn:aws:ec2:*:<accountid>:key-pair/*",
                "arn:aws:ec2:*:<accountid>:security-group/*"
            ]
        }
    ]
}

使用Tag筛选AMI,参考官方文章[2]

以下例子表明当AMI的tag key是"Environment",其value为"Prod"时,才可以使用此AM启动Iec2.请根据需要自行修改最后一行中的标签KV值

{
      "Sid": "LaunchingEC2withAMIsAndTags",
      "Effect": "Allow",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1::image/ami-*",
      "Condition": {
        "StringEquals": {
          "ec2:ResourceTag/Environment": "Prod"
        }
      } 
    }

参考文献

[1]SCP syntax
[2]How can I restrict access to launch Amazon EC2 instances from only tagged AMIs?

上一篇下一篇

猜你喜欢

热点阅读