group_names variable in ansible

17,937

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...

Share:
17,937

Related videos on Youtube

NANIS
Author by

NANIS

Updated on June 04, 2022

Comments

  • NANIS
    NANIS almost 2 years

    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?

    • larsks
      larsks over 6 years
      group_names is a list. It doesn't make sense to substitute it in a filename like that.
    • NANIS
      NANIS over 6 years
      I am new to ansible , i did not know that and thanks so much for prompt answer.
  • NANIS
    NANIS over 6 years
    you guys are amazing.