AWS Automation with Python Boto3

Automation plays a major role in In Cloud and DevOps, we have many tools to automate manual processes like Infrastructure automation with Terraform, for CICD Jenkins, GitLab, AWS, code pipeline, etc. In the same way, we can automate some of the AWS tasks with a simple python script using the oto3 library.

Let’s see some basic as well as advanced examples of python scripts to automate some day-to-day AWS tasks.

If we check some background details of boto3, it uses the AWS SDK for Python to interact with AWS services and send requests to AWS API endpoints.

First, you have to install python and boto3 library on your laptop also AWS CLI should be configured.

  1. Download and install the latest version of python
  2. Install pip by running command python
  3. Install boto3 by running command pip install boto3

To configure aws cli: <url>

Example 1:

This is a simple and basic script to start, stop and reboot ec2 instances

import boto3

ec2 = boto3.client('ec2',region_name='ap-south-1') 
#Add your region

instances = ["<instance-id>"] 
# or ["<instance-id-1>","<instance-id-2>",...,"<instance-id-n>"]

#start the instance

#stop the instance

#reboot the instance

Example 2:

In this example, we will list ec2 instances from all regions with details in .csv format

Also, it will scan all configured AWS profiles automatically and use those credentials and create one .csv file with ec2 details.

import csv
import jmespath
import boto3
import itertools
import configparser
import os
# Get list of profiles
config = configparser.ConfigParser()
path = os.path.join(os.path.expanduser('~'), '.aws/credentials')
profiles = config.sections()
# Get list of regions
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
            for region in ec2_client.describe_regions()['Regions']]
# Get list of EC2 attributes from all profiles and regions
myData = []
for profile in profiles:
    for region in regions:
        current_session = boto3.Session(profile_name = profile, region_name = region)
        client = current_session.client('ec2')
        response = client.describe_instances()
        output ="Reservations[].Instances[].[NetworkInterfaces[0].OwnerId, InstanceId, InstanceType, \
            State.Name, Placement.AvailabilityZone, PrivateIpAddress, PublicIpAddress, KeyName, [Tags[?Key=='Name'].Value] [0][0]]", response)
# Write myData to CSV file with headers
output = list(itertools.chain(*myData))
with open("ec2-inventory-latest.csv", "w", newline="") as f:
    writer = csv.writer(f)

To execute this script open cmd on script path and run

python <>

These are some examples of boto3 but we can automate hundreds of aws tasks using boto3, also we can use boto3 in the Lambda function. 

To understand more about boto3 you can refer to the official documentation.

Leave A Comment

Your email address will not be published. Required fields are marked *