任务中 ansible 未定义变量

aoe*_*ger 2 ansible

我使用 molecular 来测试 ansible 的作用。任务是使用变量复制模板。
ansible/任务/main.yml

---
- name: copy manifest billing
  template:
    src: templates/service.j2
    dest: "{{ item }}"
    with_items:
      "{{ services }}"
Run Code Online (Sandbox Code Playgroud)

ansible/vars/main.yml

services:
  - billing
  - cart
  - checkout
Run Code Online (Sandbox Code Playgroud)

当我运行“分子收敛”时出现错误

TASK [ansible : copy manifest billing] *****************************************
fatal: [instance]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to be in '/home/user/ansible/tasks/main.yml': line 2, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n---\n- name: copy manifest billing\n  ^ here\n"}
Run Code Online (Sandbox Code Playgroud)

Vla*_*tka 5

问:错误是:‘项目’未定义

答:缩进是错误的。with_items不是模块的参数。这是循环模块的指令。正确的语法是

    ---
    - name: copy manifest billing
      template:
        src: templates/service.j2
        dest: "{{ item }}"
      with_items:
        "{{ services }}"
Run Code Online (Sandbox Code Playgroud)

笔记

    with_items: "{{ services }}"
Run Code Online (Sandbox Code Playgroud)
  • 随着 Ansible 2.5 的发布,执行循环的推荐方法是使用新的循环关键字而不是 with_X 样式循环
    loop: "{{ services }}"
Run Code Online (Sandbox Code Playgroud)
  • 命令结果不一致ansible-playbook playbook.yml --check。该命令不会抱怨"Invalid options for template: with_items"!但是,例如,使用该模块,debug检查按预期进行
    - debug:
        var: item
        with_items: "{{ services }}"
Run Code Online (Sandbox Code Playgroud)
fatal: [localhost]: FAILED! => {"msg": "Invalid options for debug: with_items"}
Run Code Online (Sandbox Code Playgroud)