我正在尝试执行以下可解析的脚本,但出现了错误。
文件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 undefinednnThe error appears to be in '/mnt/c/ansible-test/first.yaml': line 16, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nn tasks:n - name: Iterate over an arrayn ^ heren"}
但是,如果我删除行
- debug:
msg: "{{ sh.stdout }}"
然后可翻译的脚本通过并给出输出
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
任务-这是运行sh test.sh -i array_item1
等的主任务。因此,它需要列表array
的项。所以我们必须将with_items: "{{ array }}"
传递给这个任务。这就是为什么当删除debug
任务的两行时,with_items
用于command
,并且它可以工作。所以你的主要需求应该满足这个:- name: Iterate over an array command: "sh test.sh -i {{ item }}" with_items: "{{ array }}"
-
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 }}"