任务中的未定义变量

时间:2019-12-13 08:00:35

标签: ansible

我用分子来测试角色。任务是使用变量的复制模板。
ansible / task / main.yml

---
- name: copy manifest billing
  template:
    src: templates/service.j2
    dest: "{{ item }}"
    with_items:
      "{{ services }}"

ansible / vars / main.yml

services:
  - billing
  - cart
  - checkout

当我运行“分子收敛”时,我会得到错误

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"}

4 个答案:

答案 0 :(得分:1)

  

Q:“错误是:'item'未定义”

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

---
- name: copy manifest billing
  template:
    src: templates/service.j2
    dest: "{{ item }}"
  with_items:
    "{{ services }}"

注释

    with_items: "{{ services }}"
  • 随着Ansible 2.5的发布,建议执行循环的方法是使用新的loop keyword而不是with_X样式循环
    loop: "{{ services }}"
  • 命令ansible-playbook playbook.yml --check的结果不一致。该命令不会抱怨"Invalid options for template: with_items"!但是使用模块debug,检查可以按预期进行
    - debug:
        var: item
        with_items:
          "{{ services }}"
fatal: [localhost]: FAILED! => {"msg": "Invalid options for debug: with_items"}

答案 1 :(得分:1)

如之前的答案中所述,这是一个缩进问题。

尝试Ansible Template tester。在将您的Ansible模板添加到您的剧本之前,对它进行检查非常有用。

答案 2 :(得分:0)

您应该从文件中include个变量:

AutoCompleteStringCollection allowedTypes = new AutoCompleteStringCollection();
allowedTypes.AddRange(yourArrayOfSuggestions);
txtType.AutoCompleteCustomSource = allowedTypes;
txtType.AutoCompleteMode = AutoCompleteMode.Suggest;
txtType.AutoCompleteSource = AutoCompleteSource.CustomSource;

explicitly add vars_files

---
- hosts: localhost
  tasks:
  - include_vars: 
     file: ansible/vars/main.yml
  - name: copy manifest billing
    template:
      src: templates/service.j2
      dest: "{{ item }}"
    with_items:
      "{{ services }}"

答案 3 :(得分:0)

谢谢。
我将一个j2模板用于多个配置。
我需要将服务项目中的每个项目都放在相同的配置文件名称中。
我的template / service.j2的一部分

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: "{{ common.fullname }}-{% for item in services %}{{ item }}{% endfor %}"

但这对我来说不合适。
我应该在同名文件中获取列表值之一,并在相应文件名中从列表中获取下一个值。
现在需要

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: "hf-billingcartcheckout"