ansibleansible-2.xansible-inventory

Ansible escape variable in playbook


I need to be able to load the host group in the total_hosts: "{{ groups['site'] | length }}" like i do in the first line - hosts: '{{ site }}' (the site variable is defined in my environment as shown here)

when using the site variable, I'm getting the below error:

{"msg": "The task includes an option with an undefined variable. The error was: {{ groups['{{vars[site]}}'] | length }}: 'dict object' has no attribute '{{vars[site]}}'.

---
- hosts: '{{ site }}'
  gather_facts: false
  vars:
    total_hosts: "{{ groups['{{vars[site]}}'] | length }}"
  tasks:
    - name: Test Connection
      ansible.windows.win_ping:
    - name: Total Hosts
      debug:
   enter image description here     msg: "{{ total_hosts }}"

Solution

  • jinja will not do what you want on total_hosts: "{{ groups['{{vars[site]}}'] | length }}".

    Correct would be total_hosts: "{{ groups[vars[site]] | length }}"

    Tips: when in doubts, always log the output jinja templates, even on partial expressions, so you will know what happens.