python-3.x - 为什么我的 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]))
解决方案
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')
推荐阅读
- android - 调用`setX()`后如何恢复正常的子定位行为
- java - kafka-producer-perf-test.sh 有多少生产者?
- html - 如何在固定元素之后定位相对元素
- ruby-on-rails - HABTM:无法创建资源
- solr - MoreLikeThisComponent SOLR 上的 NullPointerException
- ios - 在以编程方式创建的 UIViewController 内具有安全区域的 UITabBar
- angularjs - 带参数的资源,如何在登录时更新参数?
- swift - 自定义类到 CoreData 并返回
- node.js - Azure 机器人应用在修改后不更新
- java - RxJava 在 Observable 中收集 AMPQ 事件并使用缓冲区订阅