Scouse_Bob
Scouse_Bob

Reputation: 546

AWS CLI Loading Output Onto Multiple Lines

I am using the aws cli to give me some output which I require in .csv format.

The below shows the commands I've put together:

aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].[VpcId, SubnetId, InstanceId, InstanceType, ImageId, State.Name, LaunchTime, Placement.AvailabilityZone, Placement.Tenancy, PrivateIpAddress, PrivateDnsName, PublicDnsName,[Tags[?Key==`Name`].Value],[Tags[?Key==`PowerData`].Value] ]' --output text | sed -E 's/\s+/,/g'

For some reason, the final two pieces of info, "Name" and "PowerData" end up on separate lines. This screws up my formatting when I open it up in a spreadsheet.

Anyone have any ideas on what might be causing that or how I may resolve it please?

Upvotes: 1

Views: 1848

Answers (1)

Adiii
Adiii

Reputation: 60046

The reason is TAGs return array so you need to print the only value on 0 index to display the TAGs on a single line. You can verify this

aws ec2 describe-instances --output json --query 'Reservations[*].Instances[*].Tags[]' 

output

    [
        {
            "Key": "Name",
            "Value": "demo"
        },
        {
            "Key": "PowerData",
            "Value": "demo"
        }
    ]

so you need pipe expression

Tags[?Key==`Name`].Value| [0]

With the addition of filters, we could pass the result of one expression to another, operating on the result of a projection (or any expression).

Expression:

foo.*.bar | [0]

jmespath-pipe-expressions

So try this

aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].[VpcId, SubnetId, InstanceId, InstanceType, ImageId, State.Name, LaunchTime, Placement.AvailabilityZone, Placement.Tenancy, PrivateIpAddress, PrivateDnsName, PublicDnsName,Tags[?Key==`Name`].Value| [0],Tags[?Key==`PowerData`].Value | [0] ]' --output text | sed -E 's/\s+/,/g'

Upvotes: 3

Related Questions