I want to use jq to get value's out of a the Traefik API service. The output of the service looks like this:
{
"loadBalancer": {
"servers": [
{
"url": "http://172.18.0.19:3000"
},
{
"url": "http://172.18.0.17:3000"
},
{
"url": "http://172.20.0.3:3000"
}
],
"healthCheck": {
"path": "/health",
"interval": "10s",
"timeout": "10s",
"followRedirects": true
},
"passHostHeader": true
},
"status": "enabled",
"serverStatus": {
"http://172.18.0.17:3000": "UP",
"http://172.18.0.19:3000": "UP",
"http://172.20.0.3:3000": "DOWN"
},
"provider": "docker",
"type": "loadbalancer"
}
I want to get the value of the serverStatus
dynamically. First assigning a variable with the correct IP address from docker inspect. I'm using curl
with jq
to check if the container is being serviced.
The problem is when getting it with a variable I cannot seem to escape the special characters in the url key. Nothing is returned.
This is the command I use is:
TRAEFIK_URL="http://someurl.com/"
TRAEFIK_URL="'Authorization: Basic hashkey"
NEW_IPADDRESS=$(docker container inspect some_container_name | jq -r .[].NetworkSettings.Networks.proxy.IPAddress)
NEW_ENV_URL="http://${NEW_IPADDRESS}:3000"
curl --location --request GET "$TRAEFIK_URL" --header "$TRAEFIK_AUTH_HEADER" | jq -r '.serverStatus["${NEW_ENV_URL}"]'
I've tried using this command and some other obvious options but all didn't work.
jq -r .serverStatus[$NEW_ENV_URL]
I do get the correct value when I'm not using a variable to get the status using:
jq -r '.serverStatus["http://172.18.0.17:3000"]'
Any help is welcome.
CodePudding user response:
Use the option --arg
to pass arguments to jq
.
jq --arg url http://172.18.0.17:3000 -r '.serverStatus[$url]'
Always use this option to avoid security problems by injections.
CodePudding user response:
One of the preferred ways to pass specific environment variables into jq is using the --arg
command-line option; in your case:
jq -r --arg url "${NEW_ENV_URL}" '.serverStatus[$url]'