-4

within the python script i've aws-cli command to print ec2 information

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}"

then i get the following output from the above command

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

the question, is it possible that the output can be converted to something like the following ,expected result:

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

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

1 Answer 1

0

Rather than using Python to "call out" to an AWS CLI command, it is better to use the boto3 library to directly make the API call:

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'])
4
  • i just copied your code and adjust the values but not sure why return error expecting '}', found ':' in the 'Name': 'tag:Environment',
    – fahri
    Commented May 4, 2023 at 12:03
  • Perhaps you have some incorrect brackets or commas? Commented May 4, 2023 at 12:36
  • I have checked which should be correct but somehow this error still appears and I happen to run this Boto3 script on Jenkins pipeline, Is there a possibility that it needs to be adjusted there?
    – fahri
    Commented May 12, 2023 at 8:41
  • The error message you provided in the comment above doesn't seem complete. I'm not sure where it got the word the in the message. Commented May 12, 2023 at 8:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.