Dorilds
Dorilds

Reputation: 448

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

Upvotes: 9

Views: 25872

Answers (2)

ilias-sp
ilias-sp

Reputation: 6705

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 

Upvotes: 20

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93481

Sometimes you have to use other groups to gather their facts. However, your tasks will run only against one group. That time, you can use simply "mygroup" in group_names

group_names is a magic variable will be filled in automatically by groups of the current host.

e.g:

- hosts: mygroup,othergroup
  tasks:
  - name: x
    when: 'mygroup' in group_names
  

Upvotes: 2

Related Questions