【问题标题】:how to run a particular task on specific host in ansible如何在ansible中的特定主机上运行特定任务
【发布时间】:2020-06-29 15:47:50
【问题描述】:

我的库存文件的内容 -

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

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

在我的任务文件中,它具有共同作用,即它将在两个主机上运行,​​但我想在主机网络服务器上运行以下任务,而不是在清单文件中定义的 dbservers 中

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

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

【问题讨论】:

    标签: ansible ansible-playbook


    【解决方案1】:

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

    您可以定义如下条件:

    when: inventory_hostname in groups['webservers']
    

    【讨论】:

    • 如果你有一个应用服务器和一个数据库服务器,你的剧本,调用角色,将如何识别哪些任务应该在数据库服务器上运行,哪些任务应该在应用服务器上运行?你会在所有包含的任务上加上 when 语句吗?
    • 不,你要么有两个单独的剧本,要么在剧本中有两个不同主机组的剧本。
    【解决方案2】:

    谢谢,这对我也有帮助。

    主机文件:

    [production]
    host1.dns.name
    
    [internal]
    host2.dns.name
    

    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
    

    【讨论】:

    • 我正在尝试以相同的方式执行此操作,但任务正在跳过而不是在另一组主机上运行
    • 使用条件只能限制范围,不能扩展范围。它不会在一组完全不同的主机上运行。主持人必须是该剧当前主持人名单的一部分。
    【解决方案3】:

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

    delegate_to: hostname
    

    还有这个例子来自 ansible 文档,循环一个组。 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']}}"
    

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多