如何在ansible中的特定主机上运行特定任务

Pre*_*ura 18 ansible ansible-playbook

我的库存文件的内容 -

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

[dbservers]
x.x.x.x ansible_ssh_user=ubuntu
Run Code Online (Sandbox Code Playgroud)

在我的任务文件中,它是共同的角色,即它将在两台主机上运行,​​但我想在主机Web服务器上运行以下任务,而不是在库存文件中定义的dbservers中运行

- name: Install required packages
  apt: name={{ item }} state=present
  with_items:
    - '{{ programs }}'
  become: yes
  tags: programs
Run Code Online (Sandbox Code Playgroud)

模块有用还是有其他方法?我怎么能这样做?

udo*_*dan 40

如果您想在所有主机上运行您的角色,但只有一个任务仅限于该webservers组,那么 - 就像您已经建议的那样 - when是您的朋友.

你可以定义一个条件,如:

when: inventory_hostname in groups['webservers']
Run Code Online (Sandbox Code Playgroud)


ope*_*ion 9

在某些情况下要考虑的替代方案是 -

delegate_to: hostname
Run Code Online (Sandbox Code Playgroud)

也有这个例子形成 ansible docs,循环一个组。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']}}"
Run Code Online (Sandbox Code Playgroud)


小智 5

谢谢,这对我也有帮助。

主机文件:

[production]
host1.dns.name

[internal]
host2.dns.name
Run Code Online (Sandbox Code Playgroud)

requirements.yml文件:

- 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
Run Code Online (Sandbox Code Playgroud)