代码之家  ›  专栏  ›  技术社区  ›  omer

如何用python从cloudformation堆栈字典中获取特定字段的值

  •  1
  • omer  · 技术社区  · 8 年前

    我正在使用aws cloudformation创建一个堆栈,并希望获得 出版商 '从descripe_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可以直接获取这个字段?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Laurent Jalbert Simard    8 年前

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