我需要动态设置一个新的列表类型变量list var。
这是一个基本的剧本示例:
vars:
app_instances:
- host_name: host1-domain
inst_count: 3
- host_name: host2-domain
inst_count: 1
- host_name: host3-domain
inst_count: 1
tasks:
- set_fact:
instance_config: >-
{% set inst_config = [] %}
{% for inst in app_instances %}
{% for inst_num in range(inst.inst_count) %}
{% set node_number = inst.host_name.split('-') | first | replace('host', '') %}
{% set host_name = "host_name" %}
{% set host_num = "host_num" %}
{% set inst_name = "inst_name" %}
{% set node_conf = { host_name: inst.host_name, host_num: node_number, inst_name: inst_num+1 } %}
{{ inst_config.append(node_conf) }}
{% endfor %}
{% endfor %}
{{ inst_config|join(",") }}
- debug:
msg: "{{ instance_config }}"
这显然将 设置instance_config
为具有以下内容的字符串:
"instance_config": " \n \n \n \n \n {'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 1},{'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 2},{'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 3},{'host_name': 'host2-domain', 'host_num': '2', 'inst_name': 1},{'host_name': 'host3-domain', 'host_num': '3', 'inst_name': 1}"
因此,虽然我得到的列表的结构是正确的,但它是一个字符串,我似乎无法将它变成一个可以作为列表的变量。我在这里想念什么?我最终需要的是一个变量:
instance_config = [
{'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 1},
{'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 2},
{'host_name': 'host1-domain', 'host_num': '1', 'inst_name': 3},
{'host_name': 'host2-domain', 'host_num': '2', 'inst_name': 1},
{'host_name': 'host3-domain', 'host_num': '3', 'inst_name': 1}
]