简体   繁体   English

格式化set_fact变量

[英]Formatting set_fact variable

I need to have all the userid in a single variable, all separated by \\n. 我需要将所有用户ID放在一个变量中,并用\\ 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: ie all ids separated by a line in a single variable. 我需要类似下面的内容:即,所有ID由单个变量中的一行分隔。

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

Kindly advise. 好心提醒。

flatten the lists 整理列表

- set_fact:
    server_names: "{{ server_names|flatten }}"

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. 否则,如果不是静态的,我认为弗拉基米尔·博特卡斯的答案会更好。

Combining with what Vladmir Botka suggested, to get result in a single task. 结合弗拉德米尔·博特卡(Vladmir Botka)提出的建议,只需完成一项任务即可获得结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM