ansible优化

ansible优化:

  1. 关闭 facts 收集
  2. Forks 主机连接数
  3. ssh 长连接
  4. 异步执行
  5. 开启 Pipelinling

优化变量收集facts

  1. 只需要在 playbook 文件中加上 gather_facts: no 即可

  2. play 单独添加一个 setup 模块,并通过 gather_subset 参数严格控制 facts 的收集种类,这样既拿到了我们需要的 fact 变量又提高了 ansible 的执行效率, gather_subset 参数的默认值为 all

Forks 主机连接数

根据控制节点的 CPU和 网络性能

修改默认配置 ansible.cfg

1
forks  = 15

开启ssh长链接

开启长连接后会有一个 established 的连接

openssh5.6 以后的版本支持了 multiplexing

1
2
3
4
5
root@instance-1:~# ssh -V
OpenSSH_7.9p1 Debian-10+deb10u2, OpenSSL 1.1.1d 10 Sep 2019

# 添加到默认配置文件中
root@instance-1:~# echo "ssh_args = -C -o ControlMaster=auto -o ControlPersist=5d" >> /etc/ansible/ansible.cfg

开启 Pipelinling

ansible.cfgpipelining 参数设置为 True 即可

缺点:
要么 playbook 不使用 sudo 越权功能,要么取消 sudorequiretty 特性

异步优化

1
2
3
4
5
6
7
8
9
10
11
---

- hosts: all
remote_user: root

tasks:

- name: simulate long running op (15 sec), wait for up to 45 sec, poll every 5 sec
command: /bin/sleep 15
async: 45
poll: 5 # 默认为 10 s

不适合异步

  1. 这个任务是需要运行完后才能继续另外的任务的
  2. 申请排它锁的任务