動機

最近常用,來整理一下

一次裝很多app

如果要裝就都放在name中

- name: Install a list of packages
  yum:
    name:
      - nginx
      - postgresql
      - postgresql-server
    state: present

盡量用module

一般來說module可以在有重複時自動跳過,但有的時候module就是有bug,就沒辦法只能用command或是shell

command與shell差在?

command: 直接跑在/bin/sh shell: 看對面設定的shell是什麼

Strategy

Strategy就是在執行playbook時怎麼與其他主機協調

一般是linear,會等大家都做完才會跑下一個 free,就是自己跑自己的

加var到ansible.cfg

[defaults]
strategy = free

forks

如果主機很多就要一次多跑一點ansible,就要去調forks,預設只有5

加var到ansible.cfg

[defaults]
forks=25

Async tasks

一般來說ansible都會等對面的主機把task跑好,但有些task可以同時跑!!

- name: Execute the long running script
    shell:
    "chmod a+x /tmp/longrunningscript.sh && /tmp/my-longrunning-script.sh 60" # Run for 60 seconds 
    async: 120 # Maximum allowed time in Seconds
    poll: 05 # Polling Interval in Seconds
    
- name: Some non dependent task I want to run even if the script is still running
    yum:
    name: httpd
    state: present

ssh pipeline & Mitogen

ssh pipeline

ansible提供的減少ssh通訊的方式

  1. 加var到ansible.cfg 或是 ANSIBLE_PIPELINING=True
[ssh_connection]
pipelining = True
  1. 確保對面的/etc/sudoers中沒有requiretty (據說不用了,但文件寫要)

Mitogen

強大的IPC框架,ansible不用動,但還是有些要注意的

  1. mitogen-0.2.9.tar.gz並unzip
  2. 加var到ansible.cfg
[defaults]
strategy_plugins = /path/to/mitogen-0.2.9/ansible_mitogen/plugins/strategy
strategy = mitogen_linear

gather fact

gather_facts很慢,能不用就不用

- hosts: all
  gather_facts: no
  tasks:
    - ping:

不然就是同一台只跑一次 (cache fact)

加var到ansible.cfg,把cache放到/tmp

[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp

profile

在跑每個task時把花的時間print出來

加var到ansible.cfg

[defaults]
callback_whitelist = profile_task

Ref

How to Speed Up Your Ansible Playbooks Over 600% How to speed up Ansible playbooks drastically ?