Formatting set_fact variable

2019-08-30 09:15发布

I need to have all the userid in a single variable, all separated by \n. Code is as below.

  - name: Retrieve the user id and instance
    shell: ls -l {{item}} | grep -v total| awk '{print $3}'
    register: find_result_userid
    with_items:
     - /tmp/log/logs/log1
     - /tmp/log/logs/log2
     - /tmp/log/logs/log3


  - name: Combine all userid
    set_fact:
     server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list }}"

The output is as below.

ok: [localhost] => {
    "ansible_facts": {
        "server_names": [
            [
                "root",
                "root",
                "root"
            ],
            [
                "root",
                "root",
                "root"
            ],
            [
                "root",
                "root",
                "root"
            ]
        ]
    },
    "changed": false
}

I need something like below: i.e all ids separated by a line in a single variable.

 "server_names": [
            [
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root",
                "root"
            ]

Kindly advise.

3条回答
你好瞎i
2楼-- · 2019-08-30 09:32

Combining with what Vladmir Botka suggested, to get result in a single task.

  - name: Combine all userid
    set_fact:
      server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list | flatten }}"
查看更多
▲ chillily
3楼-- · 2019-08-30 09:39

flatten the lists

- set_fact:
    server_names: "{{ server_names|flatten }}"
查看更多
做个烂人
4楼-- · 2019-08-30 09:40

If the number of items you are iterating with is static, I would guess, that you can use the + operator to append the your results

- name: Combine all userid
    set_fact:
     server_names: "{{ find_result_userid.results[0].stdout_lines + find_result_userid.results[1].stdout_lines + find_result_userid.results[2].stdout_lines}}"

Otherwise if it is not static, I think Vladimir Botkas answer is better.

查看更多
登录 后发表回答