Boto3: Connecting your AWS with Python, EC2 edition
Tags: python, aws, devops
Published: 2021-11-22 16:24:10

One way to automate your AWS administration is using python3 and its Boto3 library.  It can be more secure if you make a IAM role that has limited programmatic access with temporary credentials to limit session time.
It is possible to pull information out of the EC2 instances regarding services, configs, or settings.  We will go through the complete script below to explain the different parts.

```
import boto3

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(RoleArn="arn:aws:iam::<ACCOUNTNUMBER>:role/AuthorizedRole",RoleSessionName="AssumeRoleSession1")
credentials=assumed_role_object['Credentials']
client = boto3.client('servicediscovery')

ec2_resource=boto3.resource('ec2',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
)
productionbox = []
intbox = []
for instance in ec2_resource.instances.all():

        print(instance.id)

        for box in instance.tags:
                if box['Key'] == 'environment' and box['Value'] == 'production':
                        productionbox.append(instance.id+" : "+ instance.public_ip_address)
                elif box['Key'] =='environment' and box['Value'] != 'production':
                        intbox.append(instance.id+" : "+ instance.public_ip_address)
print("Critical: Production")
print(productionbox)
print("Other Boxes")
print(intbox)
```



So the first chunk deals with the initial connection settings.
```
sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(RoleArn="arn:aws:iam::<ACCOUNTNUMBER>:role/AuthorizedRole",RoleSessionName="AssumeRoleSession1")
credentials=assumed_role_object['Credentials']
client = boto3.client('servicediscovery')
```
The STS is [AWS Security Token Service (STS)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html).  It gives the temporary, limited credentials for the service.  
Using STS, you can use the assume_role to take the role of an authorized role and assign it a RoleSessionName.
From there, you can stores the Credentials of the Assumed Role and store them for use later.

```
ec2_resource=boto3.resource('ec2',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
)
```
This stores the necessary credentials for use later.  These keys and tokens will change every time you connect to preserve security.

```
productionbox = []
intbox = []
for instance in ec2_resource.instances.all():

        print(instance.id)

        for box in instance.tags:
                if box['Key'] == 'environment' and box['Value'] == 'production':
                        productionbox.append(instance.id+" : "+ instance.public_ip_address)
                elif box['Key'] =='environment' and box['Value'] != 'production':
                        intbox.append(instance.id+" : "+ instance.public_ip_address)
print("Critical: Production")
print(productionbox)
print("Other Boxes")
print(intbox)
```

This part is pretty straight forward.  The ec2_resource.instances.all allows you to go through all the EC2 instances and filter what you need.  The rest of the script goes through the tags on the instances and presents the instances in separate arrays that are Production environment and the other environments.  You can go further and separate them down to different types or settings.  

Hope this helps someone out there.