如何根据远程主机在localhost上执行命令

时间:2016-11-25 11:53:36

标签: ansible

在我的剧本中我有这个:

- name: compile 
  hosts: localhost
  gather_facts: false
  tasks:
  - name: compile binary
    local_action: command make build FOO=foo1

如果主机是make build FOO=bar1bar-1,我想在localhost上执行bar-2 (他们都在{{1}组中因此,按群组区分也很好)。我尝试使用bars

when

- name: compile binary local_action: command make build FOO=foo1 when: (inventory_hostname != "bar-1") and (inventory_hostname != "bar-2") - name: compile binary local_action: command make build FOO=bar1 when: (inventory_hostname == "bar-1") or (inventory_hostname == "bar-2") 总是inventory_hostname

在我的主持人中我有

localhost

我将其作为

运行
[foos]
foo-1 ...
foo-2 ...

[bars]
bar-1 ...
bar-2 ...

3 个答案:

答案 0 :(得分:2)

这对我来说很好用:

---
- hosts: localhost,test-server
  gather_facts: no
  tasks:
    - shell: echo {{ inventory_hostname }}
      delegate_to: localhost

命令在localhost上执行,但打印localhosttest-server

答案 1 :(得分:2)

如果正在操作的当前主机是bars组的一部分,此任务将在localhost 上运行命令

   shell: echo {{ inventory_hostname }}
   run_once: true
   delegate_to: localhost
   when: "'bars' in group_names"

注意:如果您打算使用serial模式,则会影响run_once行为。

http://docs.ansible.com/ansible/playbooks_delegation.html#run-once

答案 2 :(得分:0)

在库存中以主机名为基础在本地主机上运行操作的方法

命令:

ansible-playbook -i ~/inventory_file provision/deploy.yml -e 'host_group=bars'

在库存文件中添加主机

〜/ inventory_file

[foos]
foo-1 ...
foo-2 ...

[bars]
bar-1 ...
bar-2 ...

deploy.yml

 - name: compile 
   hosts: localhost
   gather_facts: false

   tasks:
     - name: compile binary
       local_action: command make build FOO=foo1
       when: {{item}} not in "'bar-1','bar-2'"
       with_items:
         - groups['host_group']

     - name: compile binary
       local_action: command make build FOO=bar1
       when: {{item}} in "'bar-1','bar-2'"
       with_items:
         - groups[host_group]