group_names variable in ansible

NANIS picture NANIS · Oct 14, 2017 · Viewed 13.7k times · Source

I am running some issues when I execute this playbook:

- hosts: all
  connection: local
  tasks:
  - template: src=/etc/ansible/{{group_names}}/common.j2 dest=/etc/ansible/configs/{{inventory_hostname}}.txt
    name: create common config snippets

the error that I am getting is:

fatal: [R1]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to find '/etc/ansible/[u'ios']/common.j2' in expected paths."}
fatal: [R2]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to find '/etc/ansible/[u'ios1']/common.j2' in expected paths."}

and here are my groups:

/etc/ansible# cat hosts | grep ios           
[ios]
[ios1]

and here are my common.j2 files:

/etc/ansible# ls ios1/
common.j2


/etc/ansible# ls ios/ 
common.j2

Could someone elaborate why the group_names returns [u'group_names] please?

Answer

techraf picture techraf · Oct 14, 2017

Because group_names a list (that's why it is surrounded by [ ]) -- a host can belong to multiple groups.

You need to decide, what is your objective:

  • If you wanted to include files for all groups, you have to add a loop:

    - hosts: all
      connection: local
      tasks:
        - name: create common config snippets
          template:
            src: /etc/ansible/{{item}}/common.j2
            dest: /etc/ansible/configs/{{inventory_hostname}}.txt
          with_items: "{{group_names}}"
    
  • If you wanted to add a single group, you could refer to a single element (group_names[0]), but that doesn't seem practical...