简体   繁体   English

Bash 使用脚本获取转义的变量键值

[英]Bash getting escaped variable key value with script

I want to use jq to get value's out of a the Traefik API service.我想使用 jq 从 Traefik API 服务中获取价值。 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.我想动态获取serverStatus的值。 First assigning a variable with the correct IP address from docker inspect.首先从 docker inspect 分配一个具有正确 IP 地址的变量。 I'm using curl with jq to check if the container is being serviced.我正在使用带有jq curl来检查容器是否正在被服务。

The problem is when getting it with a variable I cannot seem to escape the special characters in the url key.问题是当使用变量获取它时,我似乎无法转义 url 键中的特殊字符。 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.欢迎任何帮助。

Use the option --arg to pass arguments to jq .使用选项--arg将参数传递给jq

jq --arg url http://172.18.0.17:3000 -r '.serverStatus[$url]'

Always use this option to avoid security problems by injections.始终使用此选项来避免注入带来的安全问题。

One of the preferred ways to pass specific environment variables into jq is using the --arg command-line option;将特定环境变量传递给 jq 的首选方法之一是使用--arg命令行选项; in your case:在你的情况下:

jq -r --arg url "${NEW_ENV_URL}"  '.serverStatus[$url]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM