您是否曾经想过如何修复您的系统、重启并继续工作?
如果是这样,您会对 Ansible 感兴趣,它是一个简单的配置管理工具,可以使一些最困难的工作变得容易。 例如,系统管理任务可能很复杂,需要数小时才能完成,或者对安全性有复杂的要求。
[ 提升您的自动化专业知识。 获取 Ansible 清单: 迁移到 Red Hat Ansible 自动化平台 2 的 5 个理由 ]
以我的经验,作为系统管理员最困难的部分之一是修复系统。 每次您收到通用漏洞和暴露 (CVE) 通知或安全部门强制执行的信息保障漏洞警报 (IAVA) 时,您都必须立即采取行动以弥补安全漏洞。(而且,相信我,除非漏洞得到修复,否则您的安全官会找到您。)
Ansible 可以通过运行 软件包模块来减少修复系统所需的时间。 为了演示,让我们使用 yum 模块 来更新系统。 Ansible 可以安装、更新、删除或从另一个位置安装(例如,来自持续集成/持续开发的 rpmbuild
)。 这是更新系统的任务
- name: update the system
yum:
name: "*"
state: latest
在第一行中,我们为该任务提供了一个有意义的 name
,以便我们知道 Ansible 在做什么。 在下一行中,yum module
更新 CentOS 虚拟机 (VM),然后 name: "*"
告诉 yum 更新所有内容,最后,state: latest
更新到最新的 RPM。
更新系统后,我们需要重启并重新连接
- name: restart system to reboot to newest kernel
shell: "sleep 5 && reboot"
async: 1
poll: 0
- name: wait for 10 seconds
pause:
seconds: 10
- name: wait for the system to reboot
wait_for_connection:
connect_timeout: 20
sleep: 5
delay: 5
timeout: 60
- name: install epel-release
yum:
name: epel-release
state: latest
shell module
使系统休眠 5 秒钟,然后重新启动。 我们使用 sleep
来防止连接中断,使用 async
来避免超时,并使用 poll
来启动并忘记。 我们暂停 10 秒钟以等待 VM 返回,并使用 wait_for_connection
在可以建立连接后立即连接回 VM。 然后我们 install epel-release
来测试 RPM 安装。 您可以多次运行此 playbook 来显示 idempotent
,并且唯一会显示更改的任务是重新启动,因为我们正在使用 shell
模块。 如果您预计不会发生实际更改,则可以使用 changed_when: False
在使用 shell
模块时忽略更改。
到目前为止,我们已经学习了如何更新系统、重启 VM、重新连接和安装 RPM。 接下来,我们将使用 Ansible Lightbulb 中的角色安装 NGINX。
- name: Ensure nginx packages are present
yum:
name: nginx, python-pip, python-devel, devel
state: present
notify: restart-nginx-service
- name: Ensure uwsgi package is present
pip:
name: uwsgi
state: present
notify: restart-nginx-service
- name: Ensure latest default.conf is present
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
backup: yes
notify: restart-nginx-service
- name: Ensure latest index.html is present
template:
src: templates/index.html.j2
dest: /usr/share/nginx/html/index.html
- name: Ensure nginx service is started and enabled
service:
name: nginx
state: started
enabled: yes
- name: Ensure proper response from localhost can be received
uri:
url: "http://localhost:80/"
return_content: yes
register: response
until: 'nginx_test_message in response.content'
retries: 10
delay: 1
以及重新启动 nginx 服务的处理程序
# handlers file for nginx-example
- name: restart-nginx-service
service:
name: nginx
state: restarted
在此角色中,我们安装 RPM nginx
、python-pip
、python-devel
和 devel
,并使用 PIP 安装 uwsgi
。 接下来,我们使用 template
模块复制 nginx.conf
和 index.html
以显示页面。 之后,我们确保该服务在启动时启用并启动。 然后我们使用 uri
模块检查与页面的连接。
这是一个 playbook,显示了更新、重新启动和安装 RPM 的示例。 然后继续安装 nginx。 这可以使用您想要的任何其他角色/应用程序来完成。
- hosts: all
roles:
- centos-update
- nginx-simple
观看此演示视频以获取有关该过程的更多见解。
这只是一个更新、重新启动和继续的简单示例。 为了简单起见,我添加了没有 变量 的软件包。 一旦您开始处理大量主机,您将需要更改一些设置
这是因为在您的生产环境中,您可能希望一次更新一个系统(而不是启动并忘记),并实际等待更长的时间让您的系统重新启动并继续。
有关使用此工具自动执行工作的更多方法,请查看 Opensource.com 上的其他 Ansible 文章。
1 条评论