我有以下python boto3代码。它可以很好地为我提供所有AutoScalingGroup名称,其标签为“SubEnvironment”,其值为“teal”
我真正想要的是为此添加值为“foo”的“StackName”,以便我得到我想要的结果。我不熟悉JMESPath,所以我不知道该怎么做。
def get_autoscale_groups():
asg_name_list =[]
while True:
paginator = client.get_paginator('describe_auto_scaling_groups')
page_iterator = paginator.paginate(
PaginationConfig={'PageSize': 100}
)
for page in page_iterator:
filtered_asgs = page_iterator.search(
'AutoScalingGroups[] | [?contains(Tags[?Key==`{}`].Value, `{}`)]'.format(
'SubEnvironment', 'teal')
#Want to add 'StackName', 'foo' somehow
)
for asg in filtered_asgs:
asg_name_list.append(asg['AutoScalingGroupName'])
try:
marker = page['Marker']
print(marker)
except KeyError:
break
#print(asg_name_list)
return asg_name_list
答案 0 :(得分:1)
类似的事情对我有用:
import boto3
client = boto3.client('autoscaling')
paginator = client.get_paginator('describe_auto_scaling_groups')
page_iterator = paginator.paginate(PaginationConfig={'PageSize': 100})
filtered_asgs = page_iterator.search(
'AutoScalingGroups[] | [?contains(Tags[?Key==`{}`].Value, `{}`) && contains(Tags[?Key==`{}`].Value, `{}`)]'.format(
'Purpose', 'loc-save', 'deployment_stage', 'blue')
)
for asg in filtered_asgs:
print(asg['AutoScalingGroupName'])
答案 1 :(得分:0)
<强> Code:
强>
import boto3
asg_name_list =[]
client = boto3.client('autoscaling')
while True:
paginator = client.get_paginator('describe_auto_scaling_groups')
page_iterator = paginator.paginate(
PaginationConfig={'PageSize': 100}
)
for page in page_iterator:
filtered_asgs = page_iterator.search(
'AutoScalingGroups[] | [?contains(Tags[?Key==`{}`].Value, `{}`) && contains(Tags[?Key==`{}`].Value,`{}`)]'.format(
'SubEnvironment', 'teal','StackName','foo')
)
for asg in filtered_asgs:
asg_name_list.append(asg['AutoScalingGroupName'])
try:
marker = page['Marker']
print(marker)
except KeyError:
break
print(asg_name_list)
如果您只想要aws-cli命令,请使用下面的命令:
aws autoscaling describe-auto-scaling-groups --query 'AutoScalingGroups[?contains(Tags[?Key==`SubEnvironment`].Value,`teal`) && contains(Tags[?Key==`StackName`].Value,`foo`)].[AutoScalingGroupName]' --output text
答案 2 :(得分:0)
您可以通过传递多个标签而不是两个标签来使其动态:
import boto3
def get_asg_name(client, tags):
filter = 'AutoScalingGroups[]'
paginator = client.get_paginator('describe_auto_scaling_groups')
page_iterator = paginator.paginate(
PaginationConfig={'PageSize': 100}
)
for tag in tags:
filter = ('{} | [?contains(Tags[?Key==`{}`].Value, `{}`)]'.format(filter, tag, tags[tag]))
filtered_asgs = list(page_iterator.search(filter))[-1]#['AutoScalingGroupName']
return filtered_asgs
if __name__ == '__main__':
client = boto3.client('autoscaling')
tags = {'environment': 'test', 'service': 'web'}
autoscalling_details = get_asg_name(client, tags)
print(autoscalling_details)