当条件没有以jinja2格式包装时,ansible忽略

时间:2017-06-20 05:07:19

标签: ansible ansible-2.x

无论我设置为ansible_distribution,以下任务都在运行。

- name: install packages
  yum: name={{item.name}} state=installed
  when: item.when
  with_items:
  - { name: 'telnet', when: "ansible_distribution == 'CentOS'" }
  - { name: 'net-tools', when: "ansible_distribution == 'Debian'" }
  - { name: 'net-tools', when: "ansible_distribution == 'blahblahblah'" }

结果

TASK [Gathering Facts] ***************************************************************************************************************************************************************************************
 ok: [172.16.2.3]

TASK [test : install packages] *********************************************************************************************************************************************************************************
ok: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'CentOS'", u'name': u'telnet'})
ok: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'Debian'", u'name': u'net-tools'})
ok: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'blahblahblah'", u'name': u'httpd'})

这是我的ansible版本

ansible 2.3.0.0
 config file = /etc/ansible/ansible.cfg
 configured module search path = Default w/o overrides
 python version = 2.7.5 (default, Nov  6 2016, 00:28:07) [GCC 4.8.520150623 (Red Hat 4.8.5-11)]

但是当以jinja2格式包装when条件时,如"{{item.when}}",我会得到以下警告。

TASK [test : install packages] *********************************************************************************************************************************************************************************
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{item.when}}

skipping: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'blahblahblah'", u'name': u'httpd'})
skipping: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'Debian'", u'name': u'net-tools'})
ok: [172.16.2.3] => (item={u'when': u"ansible_distribution == 'CentOS'", u'name': u'telnet'})

任何想法如何重写此任务而不必以jinja2格式包装when条件?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

- name: install packages
  package:
    name: "{{ pkgs[ansible_distribution] | default(pkgs.default) }}"
    state: present
  vars:
    pkgs:
      CentOS: telnet
      Debian: net-tools
      default: net-tools

我将yum模块替换为package以使其与发行版无关,因为yum肯定会在Debian上失败。

我同意@ techraf的评论,如果每个发行版有很多不同的任务,请考虑使用include / include_varswith_first_found来包含发行版特定的任务/变量集(见example)。