使用python脚本将aws cli输出转换为json格式

rsaldnfx  于 2023-05-08  发布在  Python
关注(0)|答案(1)|浏览(158)

在python脚本中我有aws-cli命令来打印ec2信息

def ec2Output = sh(returnStdout: true, script: "aws ec2 describe-instances --region ${Region} --filters Name=tag:Environment,Values=${Environment} --query 'Reservations[].Instances[].[Tags[?Key==`Version`].Value|[0],InstanceId]'")
 echo "${ec2Output}"

然后我从上面的命令得到以下输出

[
    [
        "2023_v1", 
        "i-0xxxxxxxxxx"
        "Dev"
    ], 
    [
        "2023_v2", 
        "i-0xxxxxxxxxx"
        "Dev"
    ], 
    [
        "2023_v2", 
        "i-xxxxxxxxxx"
        "Prod"
    ]
]

问题是,是否可以将输出转换为类似以下的预期结果:

{
    "Dev":{
        "Release": "2023",
        "Version": "v1", 
        "ID": "i-0xxxxxxxxxx"

    }, 
    "Dev":{
        "Release": "2023",
        "Version": "v2", 
        "ID": "i-0xxxxxxxxxx"
    }, 
    "Prod":{
        "Release": "2023",
        "Version": "v2", 
        "ID": "i-xxxxxxxxxx"
    }
}
kyxcudwk

kyxcudwk1#

与其使用Python“调用”AWS CLI命令,不如使用boto3 library直接进行API调用:

import boto3

ec2_client = boto3.client('ec2')

environment = 'foo'

response = ec2_client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Environment',
            'Values': [environment]
        },
    ]
)

for reservation in response['Reservations']:
  for instance in reservation['Instances']:
    for tag in instance['Tags']:
      if tag['Key'] == 'Version':
        print(instance['InstanceId'], tag['Value'])

相关问题