深色模式
Ansible 模块实战:yum/copy/template/service
摘要:Ansible 真正干活的是模块。本文用最常用的四个模块串起「装软件 + 下发配置 + 启动服务」的完整场景,并讲清 handler 如何实现配置变更才重启。
适用环境
- 已完成控制机到被管机的 SSH 免密,已存在 inventory.ini
- 被管机 RHEL 系或 Debian 系均可(示例用跨发行版的
package模块)
操作步骤
1. 怎么查模块
bash
ansible-doc ansible.builtin.template
ansible web -i inventory.ini -m setup -a 'filter=ansible_distribution*'1
2
2
RHEL 系可直接用 ansible.builtin.yum / dnf,Debian 系用 ansible.builtin.apt。
2. 装包与下发文件
yaml
- name: Install packages
ansible.builtin.package:
name: [nginx, curl]
state: present # present 安装 | latest 升级 | absent 卸载
- name: Copy index.html
ansible.builtin.copy:
src: files/index.html # 相对 playbook 所在目录
dest: /usr/share/nginx/html/index.html
mode: '0644'1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
3. 模板 + 服务 + handler
yaml
- name: Render nginx config
ansible.builtin.template:
src: nginx.conf.j2 # 内含 {{ nginx_port }}
dest: /etc/nginx/conf.d/site.conf
validate: 'nginx -t -c %s' # 渲染后先校验,不合法则不覆盖
notify: reload nginx # 仅当文件变化才触发
- name: Ensure nginx running
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
handler 在整个 play 结束前只执行一次,避免多个任务重复重启。
危险
copy 会整体覆盖目标文件。下发前确认目标路径没有人工维护的内容,或先备份一份 .bak。
验证
bash
ansible-playbook -i inventory.ini site.yml --check --diff
ansible web -i inventory.ini -m uri -a 'url=http://127.0.0.1:8080 status_code=200'1
2
2
- [ ] 第二次执行所有任务都是
ok而非changed(幂等) - [ ] 修改模板变量后执行,handler 被触发且服务 reload 成功
常见坑
validate 用的是远端路径
%s 替换成目标机上的临时文件,该命令必须在被管机存在,不是控制机。
notify 名字对不上静默失效
notify 的值必须与 handler 的 name 完全一致,写错不报错,只是不触发。
shell/command 永远返回 changed
这两个模块没有幂等判断。加 changed_when: false 让结果更真实。