我需要使用 jinja2 和 ansible 中的 csv 文件生成 ansible-playbook

我需要使用 jinja2 和 ansible 中的 csv 文件生成 ansible-playbook

我需要创建 jinja 模板来生成 ansible 剧本,因为我需要从 csv 文件读取数据

csv 文件类似于下面(文件名 ansi.csv)

aaa,bbb,ccc,ddd
aa01,ansi,directory,yes
aa02,jinj,directory,yes
aa01,play,direvtory,yes
aa02,tem,directory,yes

我生成模板的剧本是


---
- hosts: localhost
  vars: 
    csvfile: "{{ lookup('file', 'csv_files/ansi.csv')}}"
  tasks:
  - name: generate template
    template:
       src: template.j2
       dest: playbook.yml

我创建了如下所示的模板

---
{% for item in csvfile.split("\n") %}
{% if loop.index != 1 %}
{%   set list = item.split(",") %}
- name: 'make directory'
  hosts: {{ list[0]|trim()}}
  become: {{ list[3]}}
  tasks:
  - name: {{ list[1] }}
    file:
      path: {{list[1]}}
      state: {{ list[2] }}
{%  endif %}
{% endfor %}

我得到的输出剧本更简单

---
- name: 'make directory'
  hosts: aa01
  become: yes
  tasks:
  - name: ansi
    file:
      path: ansi
      state: directory
- name: make directory
  hosts: aa02
  become: yes
  tasks:
  - name: jinj
    file:
      path: jinj
      state: directory
- name: make directory
  hosts: aa01
  become: yes
  tasks:
  - name: play
    file:
      path: play
      state: directory
- name: make directory
  hosts: aa01
  become: yes
  tasks:
  - name: tem
    file:
      path: tem
      state: directory

但需要像下面这样的剧本


---
- name: 'make directory'
  hosts: aa01
  become: yes
  tasks:
  - name: ansi
    file:
      path: ansi
      state: directory

  - name: play
    file:
      path: play
      state: directory

- name: make directory
  hosts: aa02
  become: yes
  tasks:
  - name: jinj
    file:
      path: jinj
      state: directory

  - name: tem
    file:
      path: tem
      state: directory

在上面的剧本中,我的期望是按第一列分组,只有我必须重复任务部分(如果主机相同),有人可以帮助我实现这一目标吗?提前致谢

答案1

使用模块读取csv文件读取csv并使用过滤器通过...分组。例如下面的剧本和模板

shell> cat playbook.yml
- hosts: localhost
  tasks:
    - read_csv:
        path: ansi.csv
      register: data
    - template:
        src: template.j2
        dest: playbook.yml
shell> cat template.j2
---
{% for host in data.list|groupby('aaa') %}
- name: 'make directory'
  hosts: {{ host.0 }}
  become: yes
  tasks:
{% for task in host.1 %}
    - name: {{ task.bbb }}
      file:
        path: {{ task.bbb }}
        state: {{ task.ccc }}

{% endfor %}
{% endfor %}

shell> cat playbook.yml 
---
- name: 'make directory'
  hosts: aa01
  become: yes
  tasks:
    - name: ansi
      file:
        path: ansi
        state: directory

    - name: play
      file:
        path: play
        state: direvtory

- name: 'make directory'
  hosts: aa02
  become: yes
  tasks:
    - name: jinj
      file:
        path: jinj
        state: directory

    - name: tem
      file:
        path: ten
        state: directory

相关内容