AWS Python automation Fetch_VPC

#Python #PythonAutomation #AWS

AWS Python automation Fetch_VPC

Overview

AWS introduced a boto library for Python, Which provides a powerful automation tool. with boto library, you can do lots of things like ec2, VPC creation, etc; however, there are other powerful tools that provide infrastructure as a service like Terraform, which means Python Boto library is very powerful for query executer, fetching data, so forth... You can find the Boto documentation here

How to

  • Open boto package

  • Install the library by running the following: pip install boto3

  • make sure that the AWS configuration file is correct, and that you're able to communicate with AWS by awscli.

Code explanation

  • Open the documentaion, search for 'ec2', The 'ec2' Class have the most functions you going to use >> Here

  • Search for "describe_vpcs" Will use this function to collect The VPC data >> Here

  • At ec_client Variable, selected 'ec2' class and specified the region

  • At all_available_vpcs Variable, Selected the 'describe_vpcs' function from the 'ec2' Class.

  • At vpcs Variable, specified Vpcs list, So we can use it to loop on each dictionary in it.

  • check out Response Syntax in Docs describe_vpcs, The response values it's a list, Therefore to get its values, we should loop on the items.

  • Now let's iterate and select the VpcId, CidrBlock, and State values.

import boto3

ec_client = boto3.client('ec2', region_name="us-east-1")
all_available_vpcs = ec_client.describe_vpcs()
vpcs = all_available_vpcs["Vpcs"]

# looping
for vpc in vpcs:
    vpc_id = vpc["VpcId"]
    cidr_block = vpc["CidrBlock"]
    state = vpc["State"]

    print(f"VPC ID: {vpc_id} with {cidr_block} state = {state}")