将带有转义字符的字符串解析为 JSON 并解析为 Bash 中的变量

Parsing string with escape characters into JSON and to Variable in Bash

问题:

我正在尝试从我的终端中的 AWS Secrets Manager 获取凭证,但是我想要的键和值需要在 JSON 中,但是由于引号,它们带有很多转义字符。

场景:

在我触发 aws secretsmanager get-secret-value --secret-id snowflake-access-uat 命令后,我得到如下凭证:

{
    "ARN": "arn:aws:secretsmanager:ap-regionnm-1:111111111111:secret:my-secret",
    "Name": "snowflake-access-uat",
    "VersionId": "dont-care",
    "SecretString": "{\"sf-user\":\"USER_123_ADMIN\",\"sf-password\":\"FooBaarPassword\",\"sf-db\":\"MY_SPL_DB\",\"wh_name\":\"JOB_EXECUTOR\",\"sf-role\":\"JOB_EXECUTOR_ROLE\",\"sf-account\":\"icy-party\"}",
    "VersionStages": [
        "AWSCURRENT"
    ],
    "CreatedDate": 1627104812.142
}

但是,我只对 Secret String 感兴趣,为此我触发了 aws secretsmanager get-secret-value --secret-id snowflake-programmatic-access-uat | jq '.SecretString' 命令并收到了这个:

"{\"sf-user\":\"USER_123_ADMIN\",\"sf-password\":\"FooBaarPassword\",\"sf-db\":\"MY_SPL_DB\",\"wh_name\":\"JOB_EXECUTOR\",\"sf-role\":\"JOB_EXECUTOR_ROLE\",\"sf-account\":\"icy-party\"}"

但是因为它有多个转义字符,我无法在 jq 树中利用它。我试图从 获取参考,但我无法使其工作。此外,我需要键和值在我的 bash 会话中成为变量。

注意:我不能使用任何第三方工具,因为我需要在 CodeBuild 上自动执行此操作(运行 将选择时间新鲜实例)

存在转义字符是因为您没有将 -rjq '.SecretString' 一起使用。将其更改为 jq -r '.SecretString',您的输出将改为:

{"sf-user":"USER_123_ADMIN","sf-password":"FooBaarPassword","sf-db":"MY_SPL_DB","wh_name":"JOB_EXECUTOR","sf-role":"JOB_EXECUTOR_ROLE","sf-account":"icy-party"}

...有效 JSON,您可以反馈到 jq -r 以检索各个字段。

SecretStringJson=$(... | jq -r '.SecretString')
### one jq call per field isn't the most efficient possible way but it's easy
sfUser=$(jq -r '.["sf-user"]' <<<"$SecretStringJson")
sfDb=$(jq -r '.["sf-db"]' <<<"$SecretStringJson")
# ...etc