获取 csv 列表并使用序列对其进行迭代

Taking a csv list and iterating through it with a sequence

我有一个剧本,它从用户那里获取逗号分隔值的输入列表:

a,b,c,d

并使用 split 将其转换为列表(extra_hosts 是存储用户输入的变量)

- name: Generate hosts list
  set_fact:
    hosts_list: []

- name: Build hosts list
  set_fact:
    san_list: "{{ hosts_list + [host] }}"
  loop_control:
    loop_var: host
  with_items: "{{ extra_hosts | split(',') }}"

目前为止一切正常。如果此时我 debug,我得到:

ok: [localhost] => {
    "msg": [
        "a",
        "b",
        "c",
        "d"
    ]
}

我现在要做的是输出到文件中,列表格式为:

Host 1: a
Host 2: b
Host 3: c
Host 4: d

我可以轻松地遍历列表并使用这个输出:

- name: Append hosts to file
  lineinfile:
    path: "hosts.conf"
    line: "Host: {{ host }}"
  loop_control:
    loop_var: host
  with_items: "{{ hosts_list }}"

然而,这输出(显然)为:

Host: a
Host: b
Host: c
Host: d

但我不认为我可以用两个变量进行迭代(第二个是 sequence 模块),所以我不能做类似的事情:

- name: Append hosts to file
  lineinfile:
    path: "hosts.conf"
    line: "Host: {{ host }}"
  loop_control:
    loop_var: host
  with_items: "{{ hosts_list }}"
  loop_control:
    loop_var: id
  with_sequence: start=1

我在想也许能以某种方式将列表转换成字典,所以我最终会得到类似的东西:

{id: 1, host: "a"},
{id: 2, host: "b"},
{id: 3, host: "c"},
{id: 4, host: "d"}

然后我就可以使用 {{ item.id }}{{ item.host }} 之类的东西来写出来——但是为了构建字典,我仍然需要用两个指针迭代——一个增量值, 以及列表中的指针。

有什么方法可以做到这一点,best/correct 方法是什么?

例如,如果extra_hosts未定义,下面的任务将被跳过

    - copy:
        dest: hosts.conf
        content: |-
          {% for i in extra_hosts.split(',') %}
          Host {{ loop.index }}: {{ i }}
          {% endfor %}
      when: extra_hosts|d('')|length > 0

如果定义了变量 extra_hosts(例如 -e extra_hosts='a,b,c,d'),任务将创建文件 hosts.conf

shell> cat hosts.conf 
Host 1: a
Host 2: b
Host 3: c
Host 4: d

关于你的问题

... the list in the format ...

您可以利用 Extended loop variables

---
- hosts: localhost
  become: no
  gather_facts: no

  vars:

   LIST: ['a', 'b', 'c', 'd']

  tasks:

  - name: Show result
    debug:
      msg: "Host {{ ansible_loop.index }}: {{ LIST[ansible_loop.index0] }}"
    loop: "{{ LIST }}"
    loop_control:
      label: "{{ item }}"
      extended: yes

结果为

的输出
TASK [Show result] ***********
ok: [localhost] => (item=a) =>
  msg: 'Host 1: a'
ok: [localhost] => (item=b) =>
  msg: 'Host 2: b'
ok: [localhost] => (item=c) =>
  msg: 'Host 3: c'
ok: [localhost] => (item=d) =>
  msg: 'Host 4: d'