Reputation: 12047
When using JQ to test the value of a key, the filter is unexpectantly returning false
when it expected to instead return true
.
Assume the following variables -
TAGS='{"kubernetes.io/cluster/my-cluster":"owned"}
CLUSTER_NAME="my-cluster"
When testing $TAGS
using a hardcoded value the filter returns true
, as expected.
echo $TAGS | jq '."kubernetes.io/cluster/my-cluster" == "owned"'
However, after introducing clusterName
as a JQ argument, the filter now returns false
.
echo $TAGS | jq --arg clusterName $CLUSTER_NAME '."kubernetes.io/cluster/" + $clusterName == "owned"'
I first wondered if the -
in the $CLUSTER_NAME
was the issue, but removing that (and updating $TAGS
to match) yields the same result.
I've tried the following in the filter, all of which also yield the same result.
."kubernetes.io/cluster/" + "$clusterName"
."kubernetes.io/cluster/ + $clusterName"
."kubernetes.io/cluster/$clusterName"
How can the filter be amended to work as expected?
Upvotes: 0
Views: 85
Reputation: 43904
You can use string interpolation (\()
) docs to concat that variable to the rest like so:
'."kubernetes.io/cluster/\($clusterName)" == "owned"'
echo $TAGS | jq --arg clusterName $CLUSTER_NAME '."kubernetes.io/cluster/\($clusterName)" == "owned"'
Shows true
when testing with the supplied variables.
That said, I'd recommend using here-string (<<<
) instead off echo |
like so:
$ TAGS='{"kubernetes.io/cluster/my-cluster":"owned"}'
$ CLUSTER_NAME="my-cluster"
$
$ jq --arg clusterName $CLUSTER_NAME '."kubernetes.io/cluster/\($clusterName)" == "owned"' <<< "$TAGS"
true
$
Can I pass a string variable to jq not the file?
Upvotes: 3