使用jinja,动态创建一个列表

分享于 

4分钟阅读

互联网

  繁體

问题:

需要动态设置一个新的列表类型变量列表var。

以下是基本的playbook例子:


 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}


]




答案1:

  • do中启用ansible.cfg jinja扩展:jinja2_extensions =jinja2.ext.do
  • 代替{{ inst_config.append(node_conf) }}{% do inst_config.append(node_conf) %}
  • 使用{%--%}修剪空白

set_fact任务的最终结果如下所示:


 - set_fact:


 instance_config: >-


 {%- set instance_config = [] -%}


 {%- for inst in app_instances -%}


 {%- for inst_num in range(inst.inst_count) -%}


 {%- set node_number = inst.host_name.split('-') | first | replace('host', '') | int -%}


 {%- 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 } -%}


 {%- do instance_config.append(node_conf) -%}


 {%- endfor -%}


 {%- endfor -%}


 {{ instance_config }}





lis  列表  动态  ANSI  Ansible  Jinja  
相关文章