如何在python中运行循环以运行AWS CLI?

2024-10-02 22:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个键值对的基本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 ""

Tags: 文件name命令awsjson参数valueaccount
1条回答
网友
1楼 · 发布于 2024-10-02 22:37:18

这是您要查找的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"

I do NOT recommend to use AWS like this! This can be very error-prone and takes a lot of the features away since you would require run this as subcommand

您应该使用AWS提供的boto3Python 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异常

相关问题 更多 >