温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何优化Ansible运行速度

发布时间:2026-09-21 07:01:58 来源:亿速云 阅读:93 作者:小樊 栏目:系统运维

优化 Ansible 的运行速度可以从架构、配置、Playbook 写法、网络与系统层面多个角度入手。下面按“投入产出比”由高到低整理常见且实用的优化方法。


一、最关键的优化(效果最明显)

1. 启用 SSH 长连接(pipelining + 控制持久连接)

这是最推荐的第一步优化。

ansible.cfg 示例:

[defaults]
pipelining = True

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

效果:

  • 避免每次任务都新建 SSH 连接
  • 减少 -c ssh 的 Python 拷贝开销

✅ 注意:

  • pipelining=True 时,部分老旧 sudo 配置可能需要 requiretty=no

2. 使用 mitogen 插件(性能提升非常明显)

Mitogen 可大幅减少 Python 解释器启动和模块传输次数。

安装:

pip install mitogen

ansible.cfg:

[defaults]
strategy_plugins = /path/to/mitogen/ansible
strategy = mitogen_linear

效果:

  • 通常可提升 2–10 倍
  • 特别适合大量主机 / 大量小任务

3. 并发执行(forks)

默认 forks = 5,往往太低。

[defaults]
forks = 50

经验值:

  • 小型环境:20–50
  • 大型环境:100+

(受控制端 & 被控端 CPU、网络限制)


二、Playbook 层优化

4. 减少任务数量

  • 合并相似 task
  • 用 with_items / loop 替代多次 task
  • 能用 shell 一条命令搞定就别写 5 个模块

5. 使用 async + poll

适合长时间任务(如安装、编译)。

- name: Long running task
  command: /opt/long.sh
  async: 600
  poll: 0

或:

  async: 600
  poll: 15

6. 避免不必要的 gather_facts

如果不需要 facts:

- hosts: all
  gather_facts: false

或只收集需要的:

gather_subset:
  - 'min'

7. 合理使用 delegate_to / run_once

- name: Only once
  command: echo
  run_once: true

三、模块与执行策略优化

8. 使用高效模块

  • command / shell 比 copy + template 快(但可维护性差)
  • lineinfile 比多次 copy 好
  • 避免频繁 stat + copy

9. 使用 free 策略(大规模场景)

[defaults]
strategy = free

主机之间不互相等待,适合:

  • 批量安装
  • 无强依赖关系任务

四、网络与系统层优化

10. 控制端性能

  • 使用 SSD
  • 提高 CPU 核数
  • Python 3.x(推荐 3.9+)

11. 被控端优化

  • 关闭 SELinux(测试环境)
  • 使用本地 yum/apt 缓存
  • 使用内网镜像源

12. 使用 Jump Host / Bastion 时注意

  • 避免多层 SSH
  • 使用 ProxyCommand 而非嵌套 Ansible

五、调试与定位慢点

13. 使用 callback 插件

[defaults]
callback_whitelist = timer, profile_tasks

可看到:

  • 每个 task 耗时
  • 哪些主机最慢

14. 使用 ANSIBLE_DEBUG

ANSIBLE_DEBUG=1 ansible-playbook site.yml

六、进阶方案(大规模)

  • Ansible Tower / AWX(任务队列)
  • 拆分 Playbook(按角色/环境)
  • 使用 ansible-pull(被控端主动拉取)

总结(推荐组合)

最常见、最有效的优化组合:

pipelining = True
forks = 50
strategy = mitogen_linear
gather_facts = false(如不需要)

如果你愿意,可以:

  • 贴出你的 ansible.cfg
  • 或描述你的主机规模 / 网络环境 / 常见任务

我可以帮你做针对性优化方案。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手