AWS Cloud Automation with Python and Boto3 – Part 2

In the last article, we learnt a bit about Python and Boto and how to install them. In this part, we will create a simple script and see how to automate a task on AWS.

Before we get into scripting, we need to first create a user on AWS console and assign permissions so that this user can interact and run AWS services and then drive through boto sessions.

Step 1 -> Open AWS console – https://console.aws.amazon.com/console/home

Step 2 -> Navigate to the Identity Access Management (IAM) link and click on “Add User”. Name the user and select the option – “Programmatic access”.

Also, grant “AWS Management Console access” option. Now, attach policies to this user role.

So, this role will have a username, access type and permissions. Post creating this user, download the details in a file.

Step 3 -> Configure scripting environment with the AWS CLI tool to perform actions on AWS services. And this is done by creating “boto3” session using the authentication details. Also note- there are 2 types of sessions – default and custom (created when a change is to be reflected across different regions).

Once boto3 is installed and configured, we can now focus on creating scripts for various tasks that consume time. Let us take an example on retrieving list of EC2 instances through Python script-

Step a -> Import “boto3” library and create EC2 client. This client will be used to fetch details of all existing EC2 instances with their instance IDs.

Step b -> Lets create a python script with a name “myscript.py” , refer snapshot-

Step c -> To run the above script, go to terminal and type in below command-

python myscript.py

The output will be a list of all EC2 instance based on in “us-east-1” region.

Sounds cool, right 🙂 Stay tuned for more such scripts !!