Search code examples
ansible

Run ansible tasks based on machine names in a group


I want to create symlinks for a file using ansible only when I have a certain machine hostname. I know inventory_hostname will give me the hostname, but can I do something like: when: inventory_hostname in group['machines'] so I can run this with all machines in that group? Then, I want to symlink based on name of machine. So:

file:
    src: {{ ansible_hostname }}.png
    dest: anything.png

Solution

  • You don't need the when: inventory_hostname in group['machines'] condition at all.

    You just have to run this task in a play towards hosts: machines, and you will have the symbolic link created to all hosts of the machines group.

    Update

    if you still want to go for it, and run the playbook towards a big_group but only take action when host is part of the small_group, here is a play that can do it:

    Hosts file:

    [big_group]
    greenhat
    localhost
    
    [small_group]
    localhost
    

    Playbook:

    ---
    - hosts: big_group
      # connection: local
      gather_facts: false
      vars:
        
      tasks:
      - name: print if machine is eligible for symbolic
        debug:
          msg: "machine: {{ inventory_hostname }} is eligible for symbolic link!"
        when: inventory_hostname in groups['small_group']
    

    Result:

    PLAY [big_group] ****************************************************************************************************************************************************************************************************
    
    TASK [print if machine is eligible for symbolic] ********************************************************************************************************************************************************************
    skipping: [greenhat]
    ok: [localhost] => {
        "msg": "machine: localhost is eligible for symbolic link!"
    }
    
    PLAY RECAP **********************************************************************************************************************************************************************************************************
    greenhat                   : ok=0    changed=0    unreachable=0    failed=0   
    localhost                  : ok=1    changed=0    unreachable=0    failed=0