简体   繁体   中英

How to tag EC2 instance when it does not match the whitelisted AMI ID and tag it as “not approved”

How to tag a new instance when it is in runstate to stopstate, this lambda function is to match the whitelisted AMI ID (AMI ID's are in notepad in S3), if the Instance is not matching the approved AMI ID, then the ec2 will be forced to stop and tag it as "not approved" using 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  

Use create_tags() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM