how to run a particular task on specific host in ansible

前端 未结 3 980
遥遥无期
遥遥无期 2021-01-07 16:40

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

相关标签:
3条回答
  • 2021-01-07 17:26

    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']
    
    0 讨论(0)
  • 2021-01-07 17:32

    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
    
    0 讨论(0)
  • 2021-01-07 17:36

    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']}}"
    
    0 讨论(0)
提交回复
热议问题