Tuesday, October 26, 2021

[SOLVED] Why is my Boto3 script only running for my default profile?

Issue

I wrote this to list out instances by the value of a Costcenter tag for multiple regions. I am passing it two arguments to the script, profile and div. When I change the profile argument it keeps using the default profile. I’ve tested printing the variable content and see that the data in the variable is what I passed it. I have multiple profiles and would like to be able to run this against any profile I have setup.

import boto3, sys

def intances_by_tag(profile, div):
    ec2 = boto3.resource('ec2')
    boto3.session.Session(profile_name=profile)
    instances = ec2.instances.filter(
        Filters=[
            {'Name': 'tag:Costcenter', 'Values': [div]}
            ]
        )
    for x in instances:
        for tag in x.tags:
            if tag["Key"] == 'Name':
                a = tag["Value"]
        print('{}'.format(a))

intances_by_tag(str(sys.argv[1]), str(sys.argv[2]))

Solution

When I used the answer from Mon the script wasn't able to find the EC2 instance attributes. This is what I am using now:

import boto3, sys

profile = str(sys.argv[1])
boto3.setup_default_session(profile_name=profile)
ec2 = boto3.resource('ec2')
div = str(sys.argv[2])

def intances_by_tag(profile, div):
    instances = ec2.instances.filter(
        Filters=[
            {'Name': 'tag:Costcenter', 'Values': [div]}
        ]
    )
    for x in instances:
        for tag in x.tags:
            if tag["Key"] == 'Name':
                a = tag["Value"]
                print('{}'.format(a))

intances_by_tag(profile, div)


Answered By - jmoorhead