ansible将json与几个具有相同名称的键解析为一个列表变量

时间:2016-11-09 13:47:57

标签: json ansible ansible-playbook

我有一个问题是使用ansible解析json 我有一个连接到牧场主的任务并获得一个json文件

任务:

- uri:
    url: http://rancher.local:8080/v1/hosts
    method: GET
    user: ##################
    password: ################
    body_format: json
  register: hosts_json

- name: test
  set_fact:
    rancher_env_hosts: "{{ item.hostname }}"
  #when: item.hostname == "*-i-*"
  with_items: "{{hosts_json.json.data}}"

- name: output
  debug:
    msg: "hosts: {{rancher_env_hosts}}"

我得到以下json(编辑后更易读):

{
    "json": {
        "data": [
            {
                "hostname": "rancher-i-host-02",
                "id": "adsfsa"
            },
            {
                "hostname": "rancher-i-host-01",
                "id": "gfdgfdg"
            },
            {
                "hostname": "rancher-q-host-01",
                "id": "dfgdg"
            },
            {
                "hostname": "rancher-q-host-02",
                "id": "dfgdg"
            }
        ]

    }

}

当我启动playbook时,我只得到变量中的最后一个主机名,而不是主机名列表。我可以将所有列表注册到同一个变量吗?

此外,我还添加了一行注释“#”,以便只获取与字符串“-i-”匹配的主机名,它不起作用。任何想法?

2 个答案:

答案 0 :(得分:3)

试试这个

- uri:
    url: http://rancher.local:8080/v1/hosts
    method: GET
    user: ##################
    password: ################
    body_format: json
  register: hosts_json

- name: init fact
  set_fact:
    rancher_env_hosts: "[]"

- name: test
  set_fact:
    rancher_env_hosts: "{{rancher_env_hosts}} + [ {{item.hostname}} ]"
  when: item.hostname | search(".*-i-.*")
  with_items: "{{hosts_json.json.data}}"

- name: output
  debug:
    msg: "hosts: {{rancher_env_hosts}}"

关于search,您可以在此处阅读http://docs.ansible.com/ansible/playbooks_tests.html

UPD:
关于在此处向数组添加值:Is it possible to set a fact of an array in Ansible?

答案 1 :(得分:3)

filters(和this)适用于:

NATS.stop

NATS.start do ...do your messaging... NATS.flush # Ensure processing of pending messages NATS.stop # Immidiate exit end 将包含所有主机名,- set_fact: hosts_all: "{{ hosts_json.json.data | map(attribute='hostname') | list }}" hosts_i: "{{ hosts_json.json.data | map(attribute='hostname') | map('regex_search','.*-i-.*') | select('string') | list }}" 将仅包含host_all个匹配的主机名。