在Ansible中,可以使用with_items
关键字将循环项引用到循环任务外的变量中。下面是一个包含代码示例的解决方法:
- name: Define a list of items
set_fact:
my_items:
- item1
- item2
- item3
- name: Loop through the items and register the result
command: echo "{{ item }}"
with_items: "{{ my_items }}"
register: result
- name: Print the registered result
debug:
msg: "{{ result.results | map(attribute='stdout') | list }}"
在上面的示例中,首先使用set_fact
模块定义一个名为my_items
的变量,其中包含一个列表。然后使用command
模块循环遍历my_items
列表,并将每个循环项通过item
变量引用。循环过程中,使用register
关键字将每次循环的结果注册到result
变量中。
最后,使用debug
模块打印出result
变量中所有循环结果的标准输出(stdout)。输出结果将是一个包含每个循环项输出的列表。
这样,循环项就可以在循环任务外的其他任务中通过注册的变量进行引用。