如何让Ansible中createDbsystems.yaml任务在所有主机并行执行?
实现Ansible任务在所有主机上并行执行的方法
问题背景
现有以下两个Ansible任务文件,当前createDbsystems.yaml中的任务采用串行方式执行——必须等第一个主机上的任务全部完成后,才会切换到第二个主机执行。需要调整实现所有主机上的任务并行执行。
现有文件内容
abc.yml
- name: Create DBsystem(s) include_tasks: file: createDbsystemSub.yaml apply: tags: - createDbsystem vars: nodename: "{{inventory_hostname.split('.')[0]}}" machinesvar: "{{machines[nodename]}}" loop: "{{createDbsystem}}" tags: [createDbsystem,never] ignore_errors: yes
createDbsystemSub.yaml
- name : Print the item debug: msg: "{{item.name}}" - name: Execute Dbsystem Creation include_tasks: file: createDbsystems.yaml vars: targetserver_var: "{{targetserver_dbsystems}}" dbsystem_item: "{{item}}" loop: "{{machinesvar.dbsystems}}" loop_control: loop_var: targetserver_dbsystems label: "{{ targetserver_dbsystems }}" when: item.name == targetserver_dbsystems["dbsystem"]
可行的并行实现方案
方案1:使用async与poll参数(推荐)
在createDbsystems.yaml的具体任务中添加async和poll配置,让任务在后台异步执行,无需等待单主机任务完成再切换:
# 在createDbsystems.yaml的具体任务中添加配置 - name: 具体的DB系统创建任务 # 替换为你的实际任务模块(如shell/command等) async: 300 # 设置任务超时时间,单位为秒 poll: 0 # 立即返回结果,不等待当前主机任务执行完成
之后可以通过async_status模块统一检查所有主机的任务执行状态:
- name: 批量检查DB创建任务执行状态 async_status: jid: "{{ item.ansible_job_id }}" register: job_result until: job_result.finished retries: 30 delay: 10 loop: "{{ ansible_play_batch | map('extract', hostvars, 'ansible_job_id') | list }}"
方案2:修改Playbook执行策略为free
在Playbook最顶层设置strategy: free,让Ansible无需等待所有主机完成当前任务,只要主机资源可用就分配下一个任务:
- name: 你的Play名称 hosts: all strategy: free tasks: # 后续任务列表
注意:该方式会改变整个Play的执行逻辑,所有任务都会以自由并行的方式推进,适合需要全局并行的场景。
方案3:结合throttle参数取消并发限制(Ansible 2.10+)
如果使用Ansible 2.10及以上版本,可以在调用createDbsystems.yaml的任务中添加throttle: 0取消并发数限制,同时配合异步参数实现并行:
- name: Execute Dbsystem Creation include_tasks: file: createDbsystems.yaml vars: targetserver_var: "{{targetserver_dbsystems}}" dbsystem_item: "{{item}}" loop: "{{machinesvar.dbsystems}}" loop_control: loop_var: targetserver_dbsystems label: "{{ targetserver_dbsystems }}" when: item.name == targetserver_dbsystems["dbsystem"] throttle: 0 # 取消并发数限制,允许所有主机同时执行 async: 300 poll: 0
内容的提问来源于stack exchange,提问作者Akash-BLR
相关产品推荐
相关产品推荐

