如何循环访问可能具有单个值的变量?



我正在编写一个剧本,并希望在从用户那里获取其值的变量上循环一个角色。 但是,该值可能并不总是项目列表,它可能是单个值,每当发生这种情况时,它都会引发错误。

我的任务:

- name: task name
include role:
name: role name
vars:
cluster_name: '{{ item }}'
loop: "{{ list_or_not }}"
loop_control:
loop_var: item

错误:

。传递给"循环"的无效数据,它需要一个列表...

你有没有试过:"|列表"过滤器? 抱歉,目前无法测试。

您可以测试变量是否为字符串,如果是,则将其转换为单项列表。 像这样:

---
- hosts: localhost
gather_facts: false
tasks:
- set_fact:
list_or_not: ["{{ list_or_not }}"]
when: list_or_not is string
- debug:
msg: "{{ item }}"
loop: "{{ list_or_not }}"