JMESPath query expression with bash variable
Asked Answered
N

3

21

Messing around with a simple aws cli query to check for the existence of a Lambda function and echo the associated role if it exists:

#!/bin/bash

fname=$1
role=$(aws lambda list-functions --query 'Functions[?FunctionName == `$fname`].Role' --output text)

echo "$fname role: $role"

However, $fname appears to be resolving to an empty string in the aws command. I've tried escaping the back ticks, swapping ` to ' and a miriad of other thrashing edits (and yes, I'm passing a string on the cl when invoking the script :)

How do I properly pass a variable into JMESPath query inside a bash script?

Nunnery answered 14/10, 2015 at 16:54 Comment(0)
C
35

Because the whole JMESPath expression is enclosed in single quotes, bash is not expanding the $fname variable. To fix this you can surround the value with double quotes and then use single quotes (raw string literals) for the $fname var:

aws lambda list-functions --query "Functions[?FunctionName == '$fname'].Role" --output text
Cummerbund answered 14/10, 2015 at 21:20 Comment(0)
L
11

Swapping the backticks to single quotes, didn't work for me... :(

But escaping the backticks works :)

Here are my outputs:

aws elbv2 describe-listeners --load-balancer-arn $ELB_ARN --query "Listeners[?Port == '$PORT'].DefaultActions[].TargetGroupArn | [0]"

null

aws elbv2 describe-listeners --load-balancer-arn $ELB_ARN --query "Listeners[?Port == \`$PORT\`].DefaultActions[].TargetGroupArn | [0]"

"arn:aws:elasticloadbalancing:ap-southeast-2:1234567:targetgroup/xxx"

Leprechaun answered 17/3, 2017 at 4:8 Comment(1)
That's because raw quotes (single quotes) always create strings, and if Listeners[].Port is a number, then a string won't match. That is, '1234' is really short for `"1234"`.Indulgence
C
3

7 years later and same problem. I finally figured it out by trying some dumb syntaxes.

found out the one that worked for me: simply add simple quotes inbetween the bacckquotes. It's working because bash evaluates the first string (Functions[?FunctionName == ` ), the variable $fname and then the last string `].Role

#!/bin/bash

fname=$1
role=$(aws lambda list-functions --query 'Functions[?FunctionName == `'$fname'`].Role' --output text)

echo "$fname role: $role"

And here you are !

Cementum answered 15/12, 2023 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.