【问题标题】:Ansible displays item is undefined in loopAnsible 显示项目在循环中未定义
【发布时间】:2021-03-24 11:07:14
【问题描述】:

我正在尝试执行以下 ansible 脚本,但出现错误。

文件 test.sh 有语句“echo $1”。

---
- name: Executing Ansible Playbook
  hosts: localhost
  become: yes
  become_user: testuser
  pre_tasks:
    - include_vars: global_vars.yaml
    - name: Print some debug information 
      set_fact: 
        all_vars: |
          Content of vars
          --------------------------------
          {{ vars | to_nice_json }}

  tasks:
    - name: Iterate over an array
      command: sh test.sh -i {{ item }}
      register: sh
    - debug:
        msg: "{{ sh.stdout }}"
      with_items: "{{ array }}"

数组包含以下值 array: ["array_item1", "array_item2","array_item3","array_item4","array_item5"]

错误:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to be in '/mnt/c/ansible-test/first.yaml': line 16, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: Iterate over an array\n      ^ here\n"} 

但是,如果我删除该行

    - debug:
        msg: "{{ sh.stdout }}"

然后ansible脚本通过并给出输出

TASK [Iterate over an array] **************************************************************************************************************************************************************************************
changed: [localhost] => (item=array_item1)
changed: [localhost] => (item=array_item2)
changed: [localhost] => (item=array_item3)
changed: [localhost] => (item=array_item4)
changed: [localhost] => (item=array_item5)

如何使用调试或确保脚本以正确的项目值执行。

【问题讨论】:

  • 如您所见,您的command 任务应该有with_items,而不是debug
  • @seshadri_c 工作得非常好......但是你能回答我在你的回答中提出的疑问吗?

标签: shell ansible yaml


【解决方案1】:

你有两个任务,让我们把它们分开:

  1. 首先是 command 任务 - 这是运行 sh test.sh -i array_item1 的主要任务,依此类推。所以它需要列表arrayitems。所以我们必须将with_items: "{{ array }}" 传递给这个任务。这就是为什么当您删除 2 行 debug 任务时,with_items 用于 command 并且它可以工作。所以你的主要要求应该满足这个:

    - name: Iterate over an array
      command: "sh test.sh -i {{ item }}"
      with_items: "{{ array }}"
    
  2. debug 任务 - 这是一个可选任务。您使用它只是为了验证上一个任务。所以这个任务不需要array 变量。所以我们可以将register添加到上一个任务中,并且可以使用注册的变量(sh)来查看上一个任务的状态。

总的来说,我们需要如下所示:

    - name: Iterate over an array
      command: "sh test.sh -i {{ item }}"
      with_items: "{{ array }}"
      register: sh
    - name: Show the result of previous task
      debug:
        msg: "{{ item.stdout }}"
      with_items: "{{ sh.results }}"

【讨论】:

  • 非常感谢。像魅力一样工作。您能告诉我代码中的问题是什么:是添加名称和调试任务吗?另外,如果我从我的代码中删除调试语句,它会起作用吗?
  • 我用一些解释更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多