如何解析Ansible URI模块获取请求结果?

问题描述 投票:0回答:1

我正在尝试访问 Gerrit 服务器上的其余 API,以通过 ansible 访问 ssh 密钥列表。这是代码:

- name: Get all the SSH public key from gerrit server
  ansible.builtin.uri:
    url: 'https://git.test.com/r/a/accounts/self/sshkeys'
    user: <username>
    password: <password>
    method: GET
    return_content: true
  register: data

- name: print returned json data
  debug:
    var: data.content

但是

data.content
格式非常奇怪,我似乎根本无法过滤它。

这是数据内容:

{

"data.content": ")]}'\n'[{\"seq\":1, \"ssh_public_key\":\"<public-key>\", \"comment\":\"<comment>\"},
{\"seq\":2, \"ssh_public_key\":\"<public-key>\", \"comment\":\"<comment>\"}

}

我正在尝试使用

data.content[0].comment
但它返回未定义的变量。 如何在 ansible 中过滤此数据集?

regex ansible
1个回答
0
投票

这看起来像是 Gerrit 中的一个错误。我使用例如看到同样的事情https://gerrithub.io

$ curl -n  https://gerrithub.io/a/accounts/self/sshkeys
)]}'
[{"seq":4,"ssh_public_key":"ssh-rsa ...","encoded_key":"...","algorithm":"ssh-rsa","comment":"[email protected]","valid":true},{"seq":5,"ssh_public_key":"ssh-rsa ...","encoded_key":"...","algorithm":"ssh-rsa","comment":"[email protected]","valid":true}]

这并不“完全奇怪”;这是一个有效的 JSON 对象,前面有一些随机文本(似乎是另一个引用的 JSON 对象的终端位)。幸运的是,看起来这个bug是一致的,这使得处理起来很容易;我们只要求第二行文本:

- hosts: localhost
  gather_facts: false
  tasks:
  - name: Get all the SSH public key from gerrit server
    ansible.builtin.uri:
      url: 'https://gerrithub.io/a/accounts/self/sshkeys'
      user: "{{ gerrit_username }}"
      password: "{{ gerrit_password }}"
      method: GET
      return_content: true
    register: data_raw

  - set_fact:
      data: "{{ data_raw.content.splitlines()[1] }}"

  - name: print returned json data
    debug:
      var: data

打印出预期的、格式良好的 JSON 结果:

TASK [print returned json data] **********************************************************************************************
ok: [localhost] => {
    "data": [
        {
            "algorithm": "ssh-rsa",
            "comment": "[email protected]",
            "encoded_key": "...",
            "seq": 4,
            "ssh_public_key": "ssh-rsa ...",
            "valid": true
        },
        {
            "algorithm": "ssh-rsa",
            "comment": "[email protected]",
            "encoded_key": "...",
            "seq": 5,
            "ssh_public_key": "ssh-rsa ...",
            "valid": true
        }
    ]
}

我们可以处理响应中的值,而无需执行任何异常操作:

  - debug:
      msg: "algorithm: {{ item.algorithm }}"
    loop: "{{ data }}"
    loop_control:
      label: "{{ item.seq }}"

产生:

TASK [debug] *****************************************************************************************************************
ok: [localhost] => (item=4) => {
    "msg": "algorithm: ssh-rsa"
}
ok: [localhost] => (item=5) => {
    "msg": "algorithm: ssh-rsa"
}
© www.soinside.com 2019 - 2024. All rights reserved.