简体   繁体   English

AWS Cloudformation,使用 Python 从键中获取值的最佳方法 3

[英]AWS Cloudformation, best way to get values from keys with Python 3

I have a Cloudformation template with that defines the following output values:我有一个 Cloudformation 模板,其中定义了以下 output 值:

Outputs:
  AccessKeyForUser:
    Value:
      !Ref CFNKeys
  SecretAccessKeyForUser:
    Value: !GetAtt CFNKeys.SecretAccessKey

In Python 3 with boto3, I currently get the output values this way:在带有 boto3 的 Python 3 中,我目前以这种方式获得 output 值:

session = boto3.session.Session()
cf_resource = session.resource('cloudformation')
stack = cf_resource.Stack(stackname)

code_commit_access_key = next(filter(lambda x: x['OutputKey'] == 'AccessKeyForUser', stack.outputs))['OutputValue']
code_commit_access_secret = next(filter(lambda x: x['OutputKey'] == 'SecretAccessKeyForUser', stack.outputs))['OutputValue']

I think that's not the best way.我认为这不是最好的方法。 Is there a better way to get the output values?有没有更好的方法来获取 output 值?

So what you actually want is to have a dictionary you can query for all keys you're interested in. So let's just create one using a dict comprehension , which is probably the shortest while still pythonic way to implement this:所以你真正想要的是有一个字典,你可以查询你感兴趣的所有键。所以让我们使用dict comprehension创建一个字典,这可能是实现这一点的最短但仍然是 python 的方法:

cf_resource = boto3.resource("cloudformation")
stack = cf_resource.Stack(stackname)

outputs = {output["OutputKey"]: output["OutputValue"] for output in stack.outputs}

code_commit_access_key = outputs["AccessKeyForUser"]
code_commit_access_secret = outputs["SecretAccessKeyForUser"]

Please note that this could result in unexpected results if stack.outputs would contain multiple items with the same OutputKey , as you would only get the latest of such items represented in the dictionary.请注意,如果stack.outputs包含具有相同OutputKey的多个项目,这可能会导致意外结果,因为您只会获得字典中表示的最新此类项目。 However I believe this isn't something to worry about in this particular case, as CloudFormation output value names have to be unique anyway.但是,我相信在这种特殊情况下不必担心,因为 CloudFormation output 值名称无论如何都必须是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM