boto3 code snippets

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

Name = 'myMetricName'
Namespace = 'myNameSpace'

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')
)
%d bloggers like this: