Veer Muchandi
Veer Muchandi

Reputation: 277

AWS EC2 CLI : Passing Environment Variables in the filter criteria

I am trying to pass an environment variable in the filter criteria while running CLI for AWS EC2.

For example I want to pass environment variables for vpc-id and cidr-block in this code snippet

$ aws ec2 describe-subnets --filter 'Name=vpc-id,Values=vpc-0ce822f7ef200f28k',"Name=cidr-block,Values=10.0.0.0/24" --query "Subnets[].SubnetId" --output=text --region=us-west-1
subnet-0ec2d15eda8f20484

and I am trying this:

aws ec2 describe-subnets --filter 'Name=vpc-id,Values=$EC2_VPC_ID','Name=cidr-block,Values=$EC2_CIDR_BLOCK' --query "Subnets[].SubnetId" --output=text --region=us-west-1

But it doesn't work. It tried multiple combinations such as -

aws ec2 describe-subnets --filter "Name=vpc-id,Values='$EC2_VPC_ID'","Name=cidr-block,Values='$EC2_CIDR_BLOCK'" --query "Subnets[].SubnetId" --output=text --region=us-west-1

aws ec2 describe-subnets --filter "Name=vpc-id,Values=$EC2_VPC_ID","Name=cidr-block,Values=$EC2_CIDR_BLOCK" --query "Subnets[].SubnetId" --output=text --region=us-west-1

aws ec2 describe-subnets --filter 'Name=vpc-id,Values='$EC2_VPC_ID'','Name=cidr-block,Values='$EC2_CIDR_BLOCK'' --query "Subnets[].SubnetId" --output=text --region=us-west-1

None of them work!!!

BTW, this was working before and it stopped working recently.

aws ec2 describe-subnets --filter 'Name=vpc-id,Values='$EC2_VPC_ID'','Name=cidr-block,Values='$EC2_CIDR_BLOCK'' --query "Subnets[].SubnetId" --output=text --region=us-west-1

Upvotes: 1

Views: 1840

Answers (2)

Varun Chandak
Varun Chandak

Reputation: 971

You cannot pass variables in single quotes in BASH or shell script. This is the basic 1-0-1 of Shell Scripting. It needs to have double quotes around variables.

For example:

a=2

echo $a
echo "$a"
echo '$a'

The output will be:

2
2
$a

Upvotes: 1

John Rotenstein
John Rotenstein

Reputation: 270039

This works (on Amazon Linux):

aws ec2 describe-subnets --filter "Name=vpc-id,Values=$EC2_VPC_ID,Name=cidr-block,Values=$EC2_CIDR_BLOCK" --query "Subnets[].SubnetId" --output text

Upvotes: 3

Related Questions