简体   繁体   中英

Ansible - How to dynamically create a list variable?

I've got a template like so:

listen {{haproxy_app_name}} 0.0.0.0:514
  mode {{haproxy_mode}}
  balance {{haproxy_algorithm}}
  option httpclose
  option forwardfor
  {% for server in haproxy_backend_servers %}
  server {{server.name}} {{server.ip}}:{{server.port}} {{server.paramstring}}
  {% endfor %}    

I'm trying to populate haproxy_backend_servers with a list of dictionaries referencing the list of hosts in inventory but am struggling with the syntax. I'm not sure if it's because of a lack of understanding of Jinja, Ansible or YAML though.

I do not have a dynamic inventory, I just have more hosts than I care to manually repeat this process for.

- hosts: balancer
  vars:
    haproxy_app_name: balancer
    haproxy_mode: tcp
    haproxy_algorithm: roundrobin
    haproxy_backend_servers:
    - name: listener
      ip: "{{ item }}"
      port: 514
      paramstring: cookie A check
    with_items: "{{ groups.listener }}"

Every time I try to run it it fails with FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'item' is undefined"} FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'item' is undefined"} . (The indentation of with_items does not seem to affect the error; how it's pasted is simply where I left off.)

Is this possible to do in this context? Is there a better way?

I noticed templates have access to all variables, not just those declared in the task, so I modified the template:

{% for server in groups.listener %}
server listener {{server}}:514 cookie A check
{% endfor %}

Still curious if this can be done through vars though.

You could create a template variable and use set_fact in a pre_tasks.

Example:
In this example, I'd like to populate the pgpool2_backends list variable with my inventory (backend_db nodes).
To do that I create a template variable (pgpool2_backend_template) and I populate pgpool2_backends using set_fact with items in pre_tasks.

---
- name: Playbook test
  hosts:
    - test
  pre_tasks:
    - name: Populate pgpool2_backends list variable
      set_fact:
        pgpool2_backends: "{{ (pgpool2_backends | default([])) + [pgpool2_backend_template] }}"
      with_items: "{{ groups['backend_db'] }}"
    - debug:
        var: pgpool2_backends
  roles:
    - databases/pgpool2
  vars:
    pgpool2_backend_template:
      host: "{{ item }}"
      port: 5432
  tags: test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM