在导入的任务中的不同主机上运行任务

时间:2021-01-15 14:44:16

标签: ansible

调用剧本有:

- hosts: ssh_servers
  tasks:
  - import_tasks: create_files.yml

然后,在 create_files.yml 中,我想在 ssh_servers 以外的主机上运行一些任务,例如:

- Hosts: other_servers
  tasks:
  - file:

我得到:错误!相互冲突的动作语句:主机、任务。

这是因为我试图针对从未包含在调用任务中的主机运行吗? 除了调用剧本之外,还有其他方法可以完成此操作吗:

- hosts: 
   - ssh_servers
   - other_servers
  tasks:
  - import_tasks: create_files.yml

谢谢。

1 个答案:

答案 0 :(得分:0)

<块引用>

这是因为我试图针对从未包含在调用任务中的主机运行吗?除了调用剧本之外,还有其他方法可以完成此操作

我相信答案是肯定的,尽管这会很奇怪并且可能会导致后续与您的剧本互动的人感到困惑

假设 create_files.yml 为:

- name: create /tmp/hello_world on hosts "not_known_at_launch_time"
  file:
    path: /tmp/hello_world
    state: present
  delegate_to: '{{ item }}'
  with_items: '{{ groups["not_known_at_launch_time"] }}'

那么将它们连接在一起所需的胶水是 the dynamic creation of a groupdelegate_to: keyword

- hosts: ssh_hosts
  tasks:
  - add_host:
      groups: not_known_at_launch_time
      name: secret-host-0
      ansible_host: 192.168.1.1  # or whatever
      # ... other hostvars here ...
  - include_tasks: create_files.yml

可以通过一些共享的 create_files.yml 来组合 vars: 中的那些,这些 run_once: yes 说明应该将哪个主机和 ip 添加到魔术组名称中,这也有利于保持本地化为使用它的文件的魔法组名称。

注意,我确实对此进行了测试,但并未进行广泛测试,因此可能存在一些奇怪的事情,例如需要对它们进行 groups.ssh_hosts|length 以防止任务运行 { {1}} 次或类似内容

正如 Vladimir 正确指出的那样,您实际上想要发生的是使这种关系正式化:

- hosts: ssh_hosts
  tasks:
  ... whatever tasks you had before
  - add_host: ... as before ...

- hosts: anonymous_group_name_goes_here
  tasks:
  - include_tasks: create_files.yml

- hosts: ssh_hosts
  tasks:
  - debug:
      msg: and now you are back to the ssh_hosts to pick up what they were supposed to be doing when you stopped to post on SO
相关问题