Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash getting escaped variable key value with script

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading