我希望能够编写一本剧本来更新不同环境(阶段和产品)中的所有服务器。我不想每次内核更新时都重新启动这些服务器,我只想每两个月重新启动一次。
有没有办法将重新启动变量传递给 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
答案1
您可以通过运行将额外的变量传递给 ansible playbooks
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
条件将不会得到满足。
答案2
现在有一个模块可以简单地重新启动机器:https://docs.ansible.com/ansible/latest/modules/reboot_module.html