Linux
如何設置 ansible playbook 以重啟伺服器
我希望能夠編寫一本劇本來更新我在不同環境中的所有伺服器 - 階段和產品。我不想在每次核心更新時重新啟動這些伺服器,我只想每 2 個月重新啟動一次。
有沒有辦法將重啟變數傳遞給 ansible 命令以僅在我想重啟時觸發所有伺服器的重啟?
我將使用 Jenkins 來觸發更新作業。
下面的範常式式碼:
- hosts: all become: yes tasks: - name: Making changes to the yum.conf file shell: sudo sed "s/exclude=kernel/#exclude=kernel/g" /etc/yum.conf args: executable: /bin/bash - name: Performing yum update yum: update_cache: yes name: '*' state: latest update_cache: yes - name: Checking for reboot shell: LAST_KERNEL=$(rpm -q --last kernel | awk 'NR==1{sub(/kernel-/,""); print $1}'); CURRENT_KERNEL=$(uname -r); if [ $LAST_KERNEL != $CURRENT_KERNEL ]; then echo 'reboot'; else echo 'no'; fi ignore_errors: true register: reboot_hint - name: Rebooting servers now ... command: shutdown -r now "Reboot required for updated kernel" async: 0 poll: 0 sudo: true ignore_errors: true when: reboot_hint.stdout.find("reboot") != -1 register: rebooting - name: Taking a nap while servers reboot... pause: seconds=200 when: rebooting is changed - name: Confirming servers are back online wait_for: host: "{{ ansible_ssh_host | default(inventory_hostname) }}" delay: 30 state: started search_regex: OpenSSH port: 22 become: false when: reboot is changed delegate_to: localhost
您可以通過執行將額外的變數傳遞給 ansible playbook
ansible-playbook --limit whatever myplaybook.yml --extra-vars reboot=now
修改劇本的頂部:
- hosts: all become: yes vars: reboot: notnow
重啟任務變為:
- name: Rebooting servers now ... command: shutdown -r now "Reboot required for updated kernel" async: 0 poll: 0 sudo: true ignore_errors: true when: reboot == "now" register: rebooting
當您不傳遞 extra-vars 參數時,var 的值為“notnow”,然後
when
條件將不被滿足。