【问题标题】:How to get the value of a specific field out of cloudformation stack dictionary with python如何使用python从cloudformation堆栈字典中获取特定字段的值
【发布时间】:2018-11-16 23:51:21
【问题描述】:

我正在使用 AWS Cloudformation 创建一个堆栈,并希望从 describe_stacks() 返回的字典中获取“PublicIP”字段的值。 下面的原理图代码可以完成这项工作,但它对字典结构的变化没有弹性:

#!/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 来直接获取此字段吗?

【问题讨论】:

    标签: python aws-sdk amazon-cloudformation


    【解决方案1】:

    很遗憾,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 正式发布,他们(据我所知)永远不会更新其响应负载的语法。

    【讨论】:

    • 感谢您的回答。希望您对他们没有更改 API 的看法是正确的,但您知道他们在说什么 - 永远不要说永远 :)
    • :) 我不愿意说“从不”,但我真的认为他们会在尝试更改此类内容之前创建另一个端点或 boto4 版本。
    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多