如何将端口添加到列表列表中的每个主机?

How to add port to each host in list of lists?

我有一个主机列表列表:

[['host-0', 'host-1'], ['host-2', 'host-3'], ['host-4', 'host-5', 'host-6']]

如何使用 ansible/jinja2 向每个主机添加端口号,例如 8000 以获得:

[['host-0:8000', 'host-1:8000'], ['host-2:8000', 'host-3:8000'], ['host-4:8000', 'host-5:8000', 'host-6:8000']]

这个任务应该完成:

  - name: convert items in list
    set_fact:
      my_new_list: "{{ my_new_list | default([])+ [ my_var ] }}"
    vars:
      my_var: "{{ item | map('regex_replace', '$', ':8000') | list }}"
    with_items:
    - "{{ my_list }}"

运行 的完整剧本作为演示:

---
- hosts: localhost
  gather_facts: false
  vars:
    my_list: 
    - ['host-0', 'host-1']
    - ['host-2', 'host-3']
    - ['host-4', 'host-5', 'host-6']

  tasks:
  - name: print original variable
    debug:
      var: my_list

  - name: convert items in list
    set_fact:
      my_new_list: "{{ my_new_list | default([])+ [ my_var ] }}"
    vars:
      my_var: "{{ item | map('regex_replace', '$', ':8000') | list }}"
    with_items:
    - "{{ my_list }}"

  - name: print new variable
    debug:
      var: my_new_list

结果:

TASK [print new variable] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "my_new_list": [
        [
            "host-0:8000",
            "host-1:8000"
        ],
        [
            "host-2:8000",
            "host-3:8000"
        ],
        [
            "host-4:8000",
            "host-5:8000",
            "host-6:8000"
        ]
    ]
}

PLAY RECAP

使用map + regex_replace.

    - debug:
        msg: "{{ foo | map('map', 'regex_replace', '$', ':8000') }}"
      vars:
        foo: [['host-0', 'host-1'], ['host-2', 'host-3'], ['host-4', 'host-5', 'host-6']]
    "msg": [
        [
            "host-0:8000",
            "host-1:8000"
        ],
        [
            "host-2:8000",
            "host-3:8000"
        ],
        [
            "host-4:8000",
            "host-5:8000",
            "host-6:8000"
        ]
    ]