Ansible如何在jinja2模板中引用项目

Ansible如何在jinja2模板中引用项目,ansible,ansible-playbook,Ansible,Ansible Playbook,我有一个剧本如下 - name: create the unison preference file template: src: default.prf.j2 dest: /root/.unison/{{ item }}.prf with_items: groups['ndeployslaves'] root = /home root = ssh://root@{{ item }}//home ignore =

我有一个剧本如下

    - name: create the unison preference file
      template:
      src: default.prf.j2
      dest: /root/.unison/{{ item }}.prf
      with_items: groups['ndeployslaves']
    root = /home
    root = ssh://root@{{ item }}//home
    ignore = Path virtfs
    ignore = Path */mail
default.prf.j2文件的内容如下

    - name: create the unison preference file
      template:
      src: default.prf.j2
      dest: /root/.unison/{{ item }}.prf
      with_items: groups['ndeployslaves']
    root = /home
    root = ssh://root@{{ item }}//home
    ignore = Path virtfs
    ignore = Path */mail
item变量在模板中不起作用,我收到错误消息

任务[unison\u master:创建unison优先文件]************************ 致命:[127.0.0.1]:失败!=>{“failed”:true,“msg”:“'item'未定义”}


如何在剧本中使用的模板中引用项目?

由于它不允许您在模板中使用{{item}},您可以这样做:

- name: create the unison preference file
  copy:
    src: default.prf
    dest: "/root/.unison/{{ item }}.prf"
    force: no
  with_items: "{{ groups['ndeployslaves'] }}"

- name: edit preference file
  lineinfile:
    dest: "/root/.unison/{{ item }}.prf"
    line: "root = ssh://root@{{item}}//home"
    regexp: '^root = ssh://'
  with_items: "{{ groups['ndeployslaves'] }}"
本地主机上default.prf的内容应为:

root = /home
root = ssh://
ignore = Path virtfs
ignore = Path */mail
但是,我有{{item}}在模板中工作。你确定你的空格是正确的吗?src和dest需要比模板缩进一级,但with_项需要与模板位于同一级

- name: create the unison preference file
  template:
    src: default.prf.j2
    dest: "/root/.unison/{{ item }}.prf"
  with_items: "{{ groups['ndeployslaves'] }}"

该错误是由缩进错误引起的。

带有_items:groups['ndeployslaves']的
缩进深度超过了应有的深度。

您确定为当前剧本正确设置了
ndeployslaves
?能否在模板呈现任务之前添加调试任务并打印该变量,以验证其内容是否如您所期望的那样?我的意思是打印
组['ndeployslaves']
task[unison\u master:debug this]************************************************************[弃用警告]:不推荐使用裸变量。更新您的剧本,以便环境值使用完整的变量语法(“{groups['ndeployslaves']}”)。此功能将在将来的版本中删除。可以通过在ansible.cfg中设置Deprecation\u warnings=False来禁用弃用警告。确定:[127.0.0.1]=>(item=cpanel.host.net)=>{“item”:“cpanel.sysally.net”,“msg”:“Hello world!”}{“failed”:true,“msg”:“item”未定义”}该项的值正确;只是它不能在jinja2模板中作为可变错误引用。我甚至尝试将该项添加为变量vars:the_host:“{{item}}”,然后在j2模板中引用该_host,该模板没有帮助,只是编辑了我的答案。我想我有一个语法错误。对于_items:groups['ndeployslaves']工作正常,并且item=在debug中正确显示。正如我提到的,需要工作的事情是将模板文件中的值作为变量。哦,我想我现在理解了这个问题。你不能用你想做的方式去做你想做的事情,但是我想我可以想出一个解决方案,就是语法(缩进)错误。项目的工作原理如该文章所述