首页 > 解决方案 > 为什么我的 Boto3 脚本只为我的默认配置文件运行?

问题描述

我写这个是为了按多个地区的 Costcenter 标签的值列出实例。我将两个参数传递给脚本,profile 和 div。当我更改配置文件参数时,它会继续使用默认配置文件。我测试了打印变量内容,发现变量中的数据是我传递的。我有多个配置文件,并希望能够针对我设置的任何配置文件运行它。

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]))

标签: python-3.xamazon-web-servicesamazon-ec2boto3

解决方案


import boto3, sys

def intances_by_tag(profile, div):
    session = boto3.session.Session(profile_name=profile)
    ec2 = session.client('ec2')

    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]))

下面的代码与您的原始代码一样,将使用自动创建的默认会话,而不是您要使用您的配置文件使用的会话。

boto3.resource('ec2')

推荐阅读