Ansible遍历列表并在列表中收集输出

时间:2019-12-09 08:40:58

标签: ansible

我只是不明白您应该如何遍历一个列表,并将结果收集到一个可重复的列表中:

- name: Collect all containers
  command: docker ps --all --no-trunc --format {% raw %}"{{json .}}"{% endraw %}
  register: docker_raw_containers

- debug:
    msg: "{{ docker_raw_containers.stdout_lines }}"


- name: Convert variables
  set_fact:
    docker_raw_container_item: "{{ item | to_json }}"
  loop: "{{ docker_raw_containers.stdout_lines }}"

- name: Convert to list
  set_fact:
    docker_parsed_containers: " {{ docker_raw_container_item | map(attribute='ID') | list }} "

- debug:
    msg: "{{ docker_parsed_containers }}"

此代码应产生一个容器ID和CreatedAt属性的列表。但这只会生成AnsibleUndefined对象的列表。我的错在哪里?

1 个答案:

答案 0 :(得分:1)

将json字符串转换为ansible变量需要from_json过滤器。您使用了to_json,它的作用恰恰相反。

您可以mapping from_json过滤器一次为每个结果行创建一个列表。以下剧本应该可以满足您的要求,并能完成最少的任务。

---
- name: Parse docker ps output formated as json
  hosts: all
  gather_facts: false

  tasks:

    - name: Collect all containers
      command: docker ps --all --no-trunc --format {% raw %}"{{json .}}"{% endraw %}
      register: docker_raw_containers
      # This is an info only command so it never changes the target
      changed_when: false

    - name: Convert variable
      set_fact:
        docker_parsed_containers: "{{ docker_raw_containers.stdout_lines | map('from_json') | list }}"

    - debug:
        msg: "{{ docker_parsed_containers }}"

哪个在我的机器上给出以下结果(为此推出了一些测试容器...)

$ ansible --version
ansible 2.9.2
  config file = None
  configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.9 (default, Nov  7 2019, 10:44:02) [GCC 8.3.0]

$ ansible-playbook test.yml 

PLAY [Parse docker ps output formated as json] **************************************************************************************************************************************************************************************************************************

TASK [Collect all containers] *******************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Convert variable] *************************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ************************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        {
            "Command": "\"bash -c 'while true; do sleep 20000; done'\"",
            "CreatedAt": "2019-12-09 10:05:18 +0100 CET",
            "ID": "9e6ea71499df19f5c1e33e069c533f43b3ec18c957b31bcca571b0a194b23027",
            "Image": "python:3.8",
            "Labels": "",
            "LocalVolumes": "0",
            "Mounts": "",
            "Names": "demo2",
            "Networks": "bridge",
            "Ports": "",
            "RunningFor": "39 minutes ago",
            "Size": "0B",
            "Status": "Up 39 minutes"
        },
        {
            "Command": "\"bash -c 'while true; do sleep 20000; done'\"",
            "CreatedAt": "2019-12-09 10:05:17 +0100 CET",
            "ID": "038f1e4b1f4dd627f6ccea2ddce858e1055474c6a092f32c773e842e938dec68",
            "Image": "python:3.8",
            "Labels": "",
            "LocalVolumes": "0",
            "Mounts": "",
            "Names": "demo1",
            "Networks": "bridge",
            "Ports": "",
            "RunningFor": "39 minutes ago",
            "Size": "0B",
            "Status": "Up 39 minutes"
        },
        {
            "Command": "\"/bin/sh -c 'virtualenv venv'\"",
            "CreatedAt": "2019-12-04 18:26:14 +0100 CET",
            "ID": "88427258f30226ee9ba8af420978ffb2d4046206a7b6b7dc3ee3f5494236e12b",
            "Image": "sha256:8a3e76ff0da0dd43a305461f3a6bf6abd320770fb6c3c2c365b5ea1a0062de0b",
            "Labels": "",
            "LocalVolumes": "0",
            "Mounts": "",
            "Names": "cocky_brattain",
            "Networks": "bridge",
            "Ports": "",
            "RunningFor": "4 days ago",
            "Size": "0B",
            "Status": "Exited (127) 4 days ago"
        }
    ]
}

PLAY RECAP **************************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0