Python 3.x 为什么我的Boto3脚本只针对我的默认配置文件运行?
我写这篇文章是为了根据Costcenter标记的值列出多个区域的实例。我将两个参数传递给脚本profile和div。当我更改profile参数时,它将继续使用默认的profile。我已经测试了打印变量内容,并看到变量中的数据就是我传递给它的数据。我有多个配置文件,并希望能够运行对任何配置文件,我已经设置了这个Python 3.x 为什么我的Boto3脚本只针对我的默认配置文件运行?,python-3.x,amazon-web-services,amazon-ec2,boto3,Python 3.x,Amazon Web Services,Amazon Ec2,Boto3,我写这篇文章是为了根据Costcenter标记的值列出多个区域的实例。我将两个参数传递给脚本profile和div。当我更改profile参数时,它将继续使用默认的profile。我已经测试了打印变量内容,并看到变量中的数据就是我传递给它的数据。我有多个配置文件,并希望能够运行对任何配置文件,我已经设置了这个 import boto3, sys def intances_by_tag(profile, div): ec2 = boto3.resource('ec2') boto
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]))
下面的代码与您的原始代码一样,将使用自动创建的默认会话,而不是要使用您的配置文件使用的会话
boto3.resource('ec2')
当我使用Mon的答案时,脚本无法找到EC2实例属性。这就是我现在使用的:
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)
ec2=boto3.resource('ec2')boto3.session.session(profile\u name=profile)切换这两个命令。
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)