首页 > 解决方案 > 如何在 EC2 实例与列入白名单的 AMI ID 不匹配时标记它并将其标记为“未批准”

问题描述

如何将处于运行状态的新实例标记为停止状态,此 lambda 函数用于匹配列入白名单的 AMI ID(AMI ID 在 S3 的记事本中),如果该实例与批准的 AMI ID 不匹配,则 ec2 将被迫停止并使用 Python 3 将其标记为“未批准”。

import boto3
import botocore
def lambda_handler(event, context):
    account = event['account']
    s3 = boto3.client("s3")
    bucketname = 'amivalidation-demo'
    filename = 'ami-s3.csv'
    fileObj = s3.get_object(Bucket=bucketname, Key=filename)
    file_content = fileObj["Body"].read().decode('utf-8')
    ec2_client = get_client('ec2',account)
    response = event['detail']['responseElements']['instancesSet']
    for res in response['items']:
        instance = res['instanceId']
        image = res['imageId']
        if image in file_content:
            #image in whitelist
            pass
        else:
            #image not in whitelist, kill it!
            ec2_client.stop_instances(InstanceIds=[instance],Force=True)
    return  

标签: python-3.xamazon-web-servicesamazon-ec2

解决方案


使用create_tags()

response = ec2_client.create_tags(
    Resources=['instance-id'],
    Tags=[
        {
            'Key': 'string',
            'Value': 'string'
        },
    ]
)

推荐阅读