2

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"}. (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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.