Ansible自动化部署工具-playbook编写

发布时间:2026/8/4 5:21:57
Ansible自动化部署工具-playbook编写 接着上篇Ansible自动化部署工具-安装与模块使用的文章之后下面介绍一下playbook剧本的编写就不用一行一行的去敲命令了直接集中执行命令。目录YAML 序列化配置文件playbook案例1 - 基础使用playbook案例2 - notifyhandlersplaybook案例2 - vartemplateYAML 序列化配置文件1. 核心规则- 后缀 .yml / .yaml- 靠缩进区分层级只能用空格禁止 Tab统一 2 空格缩进- 键值对key: value冒号后必须加空格- 注释# 开头- 字符串一般不用引号有空格 / 特殊字符再加双引号2. 三种基础语法普通键值name: sanchuangport: 8000列表横线 - 后面需要加空格packages:- hosts- python3- ansible-core嵌套字典多层缩进server:name: webport: 8000path: /app3. 多行字符串 |script: |set -euxyum install -y nginxsystemctl start nginxplaybook案例1 - 基础使用1. vim yum_test.yml#剧本1 - hosts: web1 # - 表示列表一个文件可多个剧本 remote_user: wf #登录用户 become: yes #可以切换用户 become_user: root #切换root用户 become_method: sudo #自动切换 tasks: - name: install nginx,docker yum: namenginx,pstree statepresent - name: start nginx service: namenginx statestarted - name: start docker service: namedocker statestarted2. 使用ansible-playbook 来运行该文件ansible-playbook yum_test.ymlplaybook案例2 - notifyhandlersnotify写在普通 task 里当前任务发生文件 / 配置变更时触发指定 handlerhandlers特殊任务只能被 notify 触发只能有一个handler等所有 tasks 执行完后再执行多用于重启 / 重载服务1. vim web.yml- hosts: web tasks: - name: 安装nginx yum: namenginx statepresent tags: install - name: 下发nginx配置 copy: src./nginx.conf dest/etc/nginx/ # 文件发生修改触发名为 nginx_reload 的handler notify: nginx_reload tags: conf handlers: - name: nginx_reload systemd: namenginx statereloaded enabledyes tags: reload2. tag 给任务打上标记运行 playbook 时可指定只执行带对应 tag 的任务跳过其余任务。ansible-playbook web.yml --tags install_nginx只执行install_nginx 标签任务ansible-playbook web.yml --skip-tags install_nginx跳过install_nginx任务ansible-playbook web.yml --tags all执行所有带标签任务playbook案例2 - vartemplate1.在web.yml所在目录下vim nginx.conf.j2listen {{ nginx_port }};2.一般会使用本机的template模板去部署被控制主机上的软件配置文件vim web.yml- hosts: web #变量 vars: nginx_port: 9000 tasks: - name: 推送渲染nginx配置模板 #在nginx.conf.j2模板里nginx_port变量会替换成上面的变量 template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf mode: 644