【问题标题】:Using regex in scraping value from json in ansible task在ansible任务中使用正则表达式从json中抓取值
【发布时间】:2021-11-17 19:59:50
【问题描述】:

我在 ansible 中有一个任务,我必须从 json 对象中提取令牌的值,如下所示:

{
"token.stdout_lines": [
    "{",
    "\t\"id\": \"08320829d85c7000\",",
    "\t\"description\": \"\",",
    "\t\"token\": \"zMiyCw7X6u_IjBpTbD1Nvt4eGk-dxBXWWOqRCgWh_KiYtp7AjD5mML5mBIEtApncBSXwU3QqexT_4VVmEv0WeA==\",",
    "\t\"status\": \"active\",",
    "\t\"userName\": \"telegraf\",",
    "\t\"userID\": \"0831cb0c68dc7000\",",
    "\t\"permissions\": [",
    "\t\t\"read:orgs/ea37b04111f50748/buckets\",",
    "\t\t\"write:orgs/ea37b04111f50748/buckets\"",
    "\t]",
    "}"
]
}

为了检索令牌的值,我按照以下步骤操作:

- set_fact:
myvalue: "{{ token.stdout_lines | regex_search('regexp')}}"
  vars:
regexp: 'token([^"]+)":([^"]+)"([^.{\\}$"]+)'
- debug:
var: myvalue

我得到的输出是 myvalue 中的一个空值。

谁能指出我哪里出错了?

非常感谢

【问题讨论】:

    标签: regex ansible influxdb-2


    【解决方案1】:

    不太确定 regexp 在这种情况下是否是最佳答案。

    为什么不做类似的事情

    - set_fact:
        myvalue: "{{ token.stdout_lines | from_json }}"
    - debug:
        var: myvalue.token
    

    在Ansible's website上查看更多信息。

    【讨论】:

      【解决方案2】:

      我会尝试删除不必要的组。正则表达式:token[^"]+":[^"]+"([^.{\\}$"]+)

      Example

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多