在Ansible中,可以使用wait_for
模块来等待上一个主机上的服务启动完成,然后再在下一个主机上启动服务。以下是一个包含代码示例的解决方法:
- name: Start service on multiple hosts sequentially
hosts: all
gather_facts: false
tasks:
- name: Wait for service to start on previous host
wait_for:
host: "{{ inventory_hostname }}"
port: 8080
delay: 10
timeout: 600
state: started
when: inventory_hostname != groups['all'][0] # Skip for the first host
- name: Start service
command: /path/to/start_service.sh
在上面的示例中,首先使用wait_for
模块等待上一个主机上的服务在端口8080上启动。delay
参数表示每次检测的间隔时间,timeout
参数表示等待的总时间。state
参数设置为started
表示等待服务启动完成。该任务只会在除了第一个主机外的其他主机上执行,通过when
条件判断实现。
然后,无论等待是否发生,都会执行Start service
任务,使用command
模块执行启动服务的脚本。
这样,Ansible将会逐个主机地等待服务启动完成,然后再在下一个主机上启动服务。