如何使用 python 从 cloudformation 堆栈字典中获取特定字段的值
How to get the value of a specific field out of cloudformation stack dictionary with python
我正在使用 AWS Cloudformation 创建一个堆栈,并希望从 describe_stacks( ).
下面的示意图代码完成了工作,但它对字典结构的变化没有弹性:
#!/usr/bin/python
import sys
import boto3
import rest_client
if len(sys.argv) < 2:
print "Bad usage: missing stack name"
exit(1)
session = boto3.Session(profile_name='profile name')
client = session.client('cloudformation')
response = client.describe_stacks(StackName=sys.argv[1])
try:
ip = response['Stacks'][0]['Outputs'][1]['OutputValue']
print "Extracted instance IP address ({0})".format(ip)
except IndexError:
print "IP address not found"
exit(1)
是否有更具体的 API 我可以用来直接获取此字段?
遗憾的是,AWS 不支持按名称过滤输出。但是做一个过滤器很容易:
#!/usr/bin/python
import sys
import boto3
import rest_client
OUTPUT_KEY = 'InstanceIp' # <-- Use the proper output name here
if len(sys.argv) < 2:
print "Bad usage: missing stack name"
exit(1)
stack_name = sys.argv[1]
session = boto3.Session(profile_name='profile name')
cf_resource = session.resource('cloudformation')
stack = cf_resource.Stack(stack_name)
try:
ip = filter(lambda x: x['OutputKey'] == OUTPUT_KEY, stack.outputs)[0]['OutputValue']
print "Extracted instance IP address ({0})".format(ip)
except IndexError:
print OUTPUT_KEY + " not found in " + stack_name
exit(1)
此外,我可以向您保证,它是面向未来的,因为一旦 API 正式发布,他们(据我所知)永远不会更新其响应有效负载的语法。
我正在使用 AWS Cloudformation 创建一个堆栈,并希望从 describe_stacks( ). 下面的示意图代码完成了工作,但它对字典结构的变化没有弹性:
#!/usr/bin/python
import sys
import boto3
import rest_client
if len(sys.argv) < 2:
print "Bad usage: missing stack name"
exit(1)
session = boto3.Session(profile_name='profile name')
client = session.client('cloudformation')
response = client.describe_stacks(StackName=sys.argv[1])
try:
ip = response['Stacks'][0]['Outputs'][1]['OutputValue']
print "Extracted instance IP address ({0})".format(ip)
except IndexError:
print "IP address not found"
exit(1)
是否有更具体的 API 我可以用来直接获取此字段?
遗憾的是,AWS 不支持按名称过滤输出。但是做一个过滤器很容易:
#!/usr/bin/python
import sys
import boto3
import rest_client
OUTPUT_KEY = 'InstanceIp' # <-- Use the proper output name here
if len(sys.argv) < 2:
print "Bad usage: missing stack name"
exit(1)
stack_name = sys.argv[1]
session = boto3.Session(profile_name='profile name')
cf_resource = session.resource('cloudformation')
stack = cf_resource.Stack(stack_name)
try:
ip = filter(lambda x: x['OutputKey'] == OUTPUT_KEY, stack.outputs)[0]['OutputValue']
print "Extracted instance IP address ({0})".format(ip)
except IndexError:
print OUTPUT_KEY + " not found in " + stack_name
exit(1)
此外,我可以向您保证,它是面向未来的,因为一旦 API 正式发布,他们(据我所知)永远不会更新其响应有效负载的语法。