46

my inventory file's contents -

[webservers]
x.x.x.x ansible_ssh_user=ubuntu

[dbservers]
x.x.x.x ansible_ssh_user=ubuntu

in my tasks file which is in common role i.e. it will run on both hosts but I want to run a following task on host webservers not in dbservers which is defined in inventory file

- name: Install required packages
  apt: name={{ item }} state=present
  with_items:
    - '{{ programs }}'
  become: yes
  tags: programs

is when module helpful or there is any other way? How could I do this ?

3 Answers 3

83

If you want to run your role on all hosts but only a single task limited to the webservers group, then - like you already suggested - when is your friend.

You could define a condition like:

when: inventory_hostname in groups['webservers']
2
  • In case you have an application server and a database server, how your playbook, calling the role, will recognize wich tasks should be run on db server and witch ones on application server? Would you put when statements on all included tasks ? Commented Sep 17, 2019 at 14:48
  • 1
    No, you would either have two separate playbooks or two plays with different hostgroups in the playbook.
    – udondan
    Commented Sep 17, 2019 at 15:56
14

Thank you, this helps me too.

hosts file:

[production]
host1.dns.name

[internal]
host2.dns.name

requirements.yml file:

- name: install the sphinx-search rpm from a remote repo on x86_64 - internal host
  when: inventory_hostname in groups['internal']
  yum:
    name: http://sphinxsearch.com/files/sphinx-2.2.11-1.rhel7.x86_64.rpm
    state: present

- name: install the sphinx-search rpm from a remote repo on i386 - Production
  when: inventory_hostname in groups['production']
  yum:
    name: http://sphinxsearch.com/files/sphinx-2.2.11-2.rhel6.i386.rpm
    state: present
2
  • I am trying to do it in the same way but the task is skipping instead of running on another group of hosts
    – Dheeraj
    Commented Mar 21, 2018 at 23:44
  • With a condition you can only limit the scope, not extend it. It will not run on a complete different set of hosts. The hosts have to be part of the current list of hosts of the play.
    – udondan
    Commented Mar 18, 2019 at 17:59
13

An alternative to consider in some scenarios is -

delegate_to: hostname

There is also this example form the ansible docs, to loop over a group. https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html -

- hosts: app_servers

  tasks:
    - name: gather facts from db servers
      setup:
      delegate_to: "{{item}}"
      delegate_facts: True
      loop: "{{groups['dbservers']}}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.