优化 Ansible 的运行速度可以从架构、配置、Playbook 写法、网络与系统层面多个角度入手。下面按“投入产出比”由高到低整理常见且实用的优化方法。
这是最推荐的第一步优化。
ansible.cfg 示例:
[defaults]
pipelining = True
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
效果:
-c ssh 的 Python 拷贝开销✅ 注意:
pipelining=True 时,部分老旧 sudo 配置可能需要 requiretty=nomitogen 插件(性能提升非常明显)Mitogen 可大幅减少 Python 解释器启动和模块传输次数。
安装:
pip install mitogen
ansible.cfg:
[defaults]
strategy_plugins = /path/to/mitogen/ansible
strategy = mitogen_linear
效果:
默认 forks = 5,往往太低。
[defaults]
forks = 50
经验值:
(受控制端 & 被控端 CPU、网络限制)
with_items / loop 替代多次 taskasync + poll适合长时间任务(如安装、编译)。
- name: Long running task
command: /opt/long.sh
async: 600
poll: 0
或:
async: 600
poll: 15
gather_facts如果不需要 facts:
- hosts: all
gather_facts: false
或只收集需要的:
gather_subset:
- 'min'
delegate_to / run_once- name: Only once
command: echo
run_once: true
command / shell 比 copy + template 快(但可维护性差)lineinfile 比多次 copy 好stat + copyfree 策略(大规模场景)[defaults]
strategy = free
主机之间不互相等待,适合:
ProxyCommand 而非嵌套 Ansible[defaults]
callback_whitelist = timer, profile_tasks
可看到:
ANSIBLE_DEBUGANSIBLE_DEBUG=1 ansible-playbook site.yml
ansible-pull(被控端主动拉取)最常见、最有效的优化组合:
pipelining = True
forks = 50
strategy = mitogen_linear
gather_facts = false(如不需要)
如果你愿意,可以:
ansible.cfg我可以帮你做针对性优化方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。