0

我有一个包含多个键值对的基本 JSON 文件。我想解析 JSON 中的值并运行 AWS 命令​​来创建 SSM 参数存储。

如何添加循环,以便我的 cmd 将从 JSON 中获取每个名称和每个值并创建每个参数存储。

参数 JSON:

{
  "Name" : "Account Summary",
  "Value" : "/some/values/to/be/there"
  "Name" : "Account Investment"
  "Value" : "/some/other/values/here"
}

Python脚本:

with open("parameters.json") as f:
   baselist = json.load(f)
   for key, value in baselist.items():
       aws ssm put-parameter --name "" --type "String" --value ""
4

1 回答 1

0

这是您正在寻找的 JSON 的有效格式

[
    {
        "Name": "Account Summary",
        "Value": "/some/values/to/be/there"
    },
    {
        "Name": "Account Investment",
        "Value": "/some/other/values/here"
    }
]

你的循环看起来像这样:

import json
ssm=[
     {
         "Name": "Account Summary",
         "Value": "/some/values/to/be/there"
     },
     {
         "Name": "Account Investment",
         "Value": "/some/other/values/here"
     }
 ]


for i in ssm:
     print(f"aws ssm put-parameter --name \"{i.get('Name')}\" --type \"String\" --value  \"{i.get('Value')}\"")

输出看起来像这样:

aws ssm put-parameter --name "Account Summary" --type "String" --value  "/some/values/to/be/there"
aws ssm put-parameter --name "Account Investment" --type "String" --value  "/some/other/values/here"

我不建议这样使用 AWS!这可能非常容易出错并且会带走很多功能,因为您需要将其作为子命令运行

您应该使用 AWS 提供的boto3 Python SDK 来处理这些事情。这是在脚本上访问 AWS 资源的推荐方式。

这是来自相同文档的示例代码片段put-parameter

response = client.put_parameter(
    Name='string',
    Description='string',
    Value='string',
    Type='String'|'StringList'|'SecureString',
    KeyId='string',
    Overwrite=True|False,
    AllowedPattern='string',
    Tags=[
        {
            'Key': 'string',
            'Value': 'string'
        },
    ],
    Tier='Standard'|'Advanced'|'Intelligent-Tiering',
    Policies='string',
    DataType='string'
)

如您所见,它具有更多功能,您可以更有效地检查响应,因为这会引发可以在脚本上检查的实际 Python 异常

于 2020-08-13T22:00:27.653 回答