boto3 code snippits

EC2

Find all regions

import boto3

for region in [region['RegionName'] for region in boto3.client('ec2',region_name = 'us-east-1').describe_regions()['Regions']]:
    print(region)

Find the latest Amazon Linux 2 AMI

import boto3

def find_linux2_ami(region_name):
    x = boto3.client('ec2',region_name = region_name).describe_images(
        Filters=[{ 'Name': 'name', 'Values': ['amzn2-ami-hvm*'] }],
        Owners=[ 'amazon' ],
        IncludeDeprecated=False,
        DryRun=False
    )['Images']

    return sorted(x, key = lambda x: x['CreationDate'], reverse=True)[0]

Find unused Security Groups

def FindUnusedSGs(region):
    ec2 = boto3.client('ec2', region_name = region)
    SecurityGroupsinUse = []
    for eni in ec2.describe_network_interfaces()['NetworkInterfaces']:
        for sg in eni['Groups']:
            SecurityGroupsinUse.append(sg['GroupId'])

    result = []
    for sg in ec2.describe_security_groups()['SecurityGroups']:
        if sg['GroupId'] not in SecurityGroupsinUse:
            result.append(sg['GroupId'])

    return result

Extract all Security Group rules

import boto3

def extract_security_groups(region_name = None):
    ec2 = boto3.client('ec2',region_name = region_name)

    print('direction;type;GroupId;GroupName;FromPort;ToPort;IpProtocol;range')
    for sg in ec2.describe_security_groups()['SecurityGroups']:
        for direction in ['IpPermissions','IpPermissionsEgress']:
            for rule in sg[direction]:

                for IpRanges in rule['IpRanges']:
                    print(f"{direction};CidrIp;{sg['GroupId']};{sg['GroupName']};{rule.get('FromPort','*')};{rule.get('ToPort','*')};{rule['IpProtocol']};{IpRanges['CidrIp']}")

                for Ipv6Ranges in rule['Ipv6Ranges']:
                    print(f"{direction};CidrIpv6;{sg['GroupId']};{sg['GroupName']};{rule.get('FromPort','*')};{rule.get('ToPort','*')};{rule['IpProtocol']};{Ipv6Ranges['CidrIpv6']}")

                for UserIdGroupPairs in rule['UserIdGroupPairs']:
                    print(f"{direction};UserIdGroupPairs;{sg['GroupId']};{sg['GroupName']};{rule.get('FromPort','*')};{rule.get('ToPort','*')};{rule['IpProtocol']};{UserIdGroupPairs.get('GroupId')}")

extract_security_groups()       # use your default region
#extract_security_groups('ap-southeast-2')  # or force it to a specific region

S3

Write a Python dictionary as a json file to an S3 bucket

    import boto3
    import json

    S3Bucket = 'My-S3-Bucket-Name'
    key = 'this-file'
    data = {'some' : 'data'}

    boto3.resource('s3').Bucket(S3Bucket ).put_object(
        ACL     = 'bucket-owner-full-control',
        ContentType = 'application/json',
        Key     = key + '.json',
        Body        = json.dumps(data, indent=4, sort_keys=True)
    )

SSM

Read a value from a parameter store

    import boto3
    myParameterValue = boto3.client('ssm').get_parameter(Name='myParameterValue', WithDecryption=True)['Parameter']['Value']

CloudWatch

Write a metric value into CloudWatch

    import boto3

    def write_metric(Namespace,metric,Name,value):
        boto3.client('cloudwatch').put_metric_data(
            Namespace=Namespace,
                MetricData=[{
                'MetricName': metric,
                'Dimensions': [{
                        'Name': Name,
                        'Value': 'Percentage'
                }],
                        'Value': value,
                        'Unit': 'Percent'
            }]
        )

CloudTrail

Read CloudTrail event via API (typically the last 90 days of logs)

    import boto3
    import json

    for e in boto3.client('cloudtrail').get_paginator('lookup_events').paginate():
        for event in e.get('Events'):
            CloudTrailEvent = json.loads(event['CloudTrailEvent'])

Lambda

Invoke a Lambda function

    import json
    import boto3

    boto3.client('lambda').invoke(
        FunctionName='functionname',
        InvocationType='Event',
        Payload=bytes(json.dumps(payload), encoding='utf8')
    )