Reputation: 1345
Is there a way to output the AWS cli with filters to csv format?
For example if I wanted to take this command and output to csv:
aws ec2 describe-images --owner self --query 'Images[*].{ID:ImageId,"Virtualization Type":VirtualizationType}'
How would I do that? Normally I would use jq to output the aws cli to csv. But in this case I was able to get to the info I wanted easier with the filter option instead of jq.
This is the full command I want to output to CSV:
aws ec2 describe-images --owner self --query 'Images[*].{ID:ImageId,"Virtualization Type":VirtualizationType,Architechture:Architecture,Hypervisor:Hypervisor,State:State,ImageID:ImageId,"Device Names":BlockDeviceMappings[].DeviceName,"Snapshot IDs":BlockDeviceMappings[].Ebs.SnapshotId,"Delete On Termination":BlockDeviceMappings[].Ebs.DeleteOnTermination,"Voluem Type":BlockDeviceMappings[].Ebs.VolumeType,"Volume Size":BlockDeviceMappings[].Ebs.VolumeSize,Encrypted:BlockDeviceMappings[].Ebs.Encrypted,"Image Location":ImageLocation,"Root Device Type":RootDeviceType,"Owner ID":OwnerId,"Creation Date":CreationDate,Public:Public,"Image Type":ImageType,Name:Name}'
Upvotes: 6
Views: 24126
Reputation: 1058
We had to do something very similar today and we used jq to get the csv output natively.
aws ec2 describe-instances --output json --query 'foo' | \
jq -r '.[][] | @csv'
Note: the .[][]
notation was required for us because our query was reformatting the output in a specific way. I would NOT expect most cases will require referencing the output in the same way.
Note 2: I don't recall the original question saying "without jq", so while my cli works, I now realize it does not meet the OP goal.
Upvotes: 7
Reputation: 52433
One solution I can think of is to output in text --output text
and then replace the spaces with a comma:
aws ec2 describe-images --owner self --query 'Images[*].{ID:ImageId,"Virtualization Type":VirtualizationType}' --output text
Output
ami-1234567890 hvm
ami-1a2b3c4d5e hvm
ami-9876543210 hvm
Replace the blanks with a comma. There are many ways to do this using sed
or tr
or awk
or paste
.
aws ec2 describe-images --owner self --query 'Images[*].{ID:ImageId,"Virtualization Type":VirtualizationType}' --output text | sed -E 's/\s+/,/g'
Output
ami-1234567890,hvm
ami-1a2b3c4d5e,hvm
ami-9876543210,hvm
Upvotes: 6