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

问题描述

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

解决方法

这是您要查找的JSON的有效格式

gg_fun()

您的循环看起来像这样:

[
    {
        "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!这可能很容易出错,并且会剥夺许多功能,因为您需要以子命令的身份运行它

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

这是文档中同一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" 的示例代码段:

put-parameter

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...