Search code examples
bashamazon-web-servicesaws-cliaws-security-group

How to expand variable in aws-cli --query parameter


I am trying to write a very simple script and am fairly new to aws cli. With my script, I am outputting all the security group ids that are allowing all open IPs (0.0.0.0/0), and I am using

aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values='0.0.0.0/0' --region "$region" --query 'SecurityGroups[*].{Name:GroupName,vpc:VpcId,sg:GroupId,Region:"$region"}' --output table. 

The region is defined in the earlier part of the script since I am going through all the regions.

However, when the table is presented, The column for region says None. How can I include the region with only aws ec2 describe-security-groups filter so it doesn't output None?


Solution

  • The region does not exist in the output of the command, so you can not look for value region.

    describe-security-groups-output

    So the other option is to expand the value of $region variable and then use escape sequence to print the value as a static value.

    Region:\``echo $region`\`
    
    

    you can use

    export region=us-east-1 && aws ec2 describe-security-groups --region=$region --filters Name=ip-permission.cidr,Values='0.0.0.0/0' --query "SecurityGroups[*].{Name:GroupName,vpc:VpcId,sg:GroupId,Region:\``echo $region`\` }" --output table
    

    Sample output

    ---------------------------------------------------------------------------------------
    |                               DescribeSecurityGroups                                |
    +-------------------------------+------------+------------------------+---------------+
    |             Name              |  Region    |          sg            |      vpc      |
    +-------------------------------+------------+------------------------+---------------+
    |  launch-wizard-17             |  us-west-2 |  sg-12345  |  vpc-12345 |
    
    

    AWS-cli look against region, so you can get all-region at once, to get security group from all region use below script.

    #!/bin/bash
    
    for region in $(aws ec2 describe-regions --query "Regions[].RegionName" --output text); do 
        echo "SG for region ${region}"
        aws ec2 describe-security-groups --region=$  --filters Name=ip-permission.cidr,Values='0.0.0.0/0' --query "SecurityGroups[*].{Name:GroupName,vpc:VpcId,sg:GroupId,Region:\``echo $region`\` }" --output table
    done
    
    

    aws-cli-cheatsheet