Ansible - 使用{{item}}和csvfile查找

时间:2016-09-30 13:42:08

标签: ansible ansible-2.x

我试图找到一种方法来减少各种模块的代码行,重复节似乎毫无意义。我想使用csvfile查找来帮助填补空白。例如,以下CSV:

# groups.csv
# name, gid [optional - leave blank], state [present|absent], system [yes|no]

accounts,502,present,no
engineering,504,present,no

所以,我的所有组定义都是csv格式。问题是,处理它,无论我尝试什么,我都无法在组模块内部进行查找。 所以最初,我想这样做:

---

- hosts: localhost

  become: True
  become_user: root

  tasks:

  - name: get groups
    command: /usr/bin/awk -F',' '!/^#/ && !/^$/ { print $1 }' groups.csv
    register: groups_out

  - debug: var=groups_out.stdout_lines


  - name: Process groups
    group: >
      name="{{ lookup('csvfile', 'item file=groups.csv col=0') }}"
      gid="{{ lookup('csvfile', 'item file=groups.csv col=1') }}"
      state="{{ lookup('csvfile', 'item file=groups.csv col=2') }}"
      system="{{ lookup('csvfile', 'item file=groups.csv col=3') }}"
    # with_lines: "/usr/bin/awk -F',' '!/^#/ && !/^$/ { print $1 }' groups.csv"
    # with_items: "{{ groups_out.stdout_lines }}"
    with_lines: "{{ groups_out.stdout_lines }}"

结果如下:

    TASK [Process groups] **********************************************************
/bin/sh: accounts: command not found
fatal: [localhost]: FAILED! => {"failed": true, "msg": "lookup_plugin.lines(accounts) returned 127"}

正如您从代码中看到的那样,我还尝试直接使用awk命令使用with_items和with_lines,但看起来群组模块并不喜欢我这样做。

Centos 7上的Ansible 2.1.1.0。 Python 2.7.5 Jinja 2.8

我有什么想法可以实现这个目标?

提前致谢,

[R

1 个答案:

答案 0 :(得分:0)

以下答案。感谢Jon和Kai对ansible-project googlegroup的帮助。

---

- hosts: localhost

  become: True
  become_user: root

  tasks:

  - name: get groups
    command: /usr/bin/awk -F',' '!/^#/ && !/^$/ { print $1 }' /var/tmp/groups.csv
    register: groups_out

  - name: Process groups one
    group: >
      name={{ lookup('csvfile', item + ' file=groups.csv col=0 delimiter=,') }}
      gid={{ lookup('csvfile', item + ' file=groups.csv col=1 delimiter=,') }}
      state={{ lookup('csvfile', item + ' file=groups.csv col=2 delimiter=,') }}
      system={{ lookup('csvfile', item + ' file=groups.csv col=3 delimiter=,') }}
    with_items: "{{ groups_out.stdout_lines }}"
    ignore_errors: True

  - name: Process groups two
    group: >
      name={{ lookup('csvfile', item + ' file=groups.csv col=0 delimiter=,') }}
      gid={{ lookup('csvfile', item + ' file=groups.csv col=1 delimiter=,') }}
      state={{ lookup('csvfile', item + ' file=groups.csv col=2 delimiter=,') }}
      system={{ lookup('csvfile', item + ' file=groups.csv col=3 delimiter=,') }}
    with_lines: /usr/bin/awk -F',' '!/^#/ && !/^$/ { print $1 }' /var/tmp/groups.csv