一、playbook 介绍
Playbook 是 ansible 用于配置,部署,和管理被控节点的剧本。用于 ansible 操作的编排。
官方文档:https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html
YMAL格式
- 以
.yaml
或.yml
结尾
- 文件的第一行以 "
---
"开始,表明 YMAL 文件的开始(可选的) - 以
#
号开头为注释 - 列表中的所有成员都开始于相同的缩进级别,并且使用一个 “
-
” 作为开头(一个横杠和一个空格) - 一个字典是由一个简单的
键: 值
的形式组成 (这个冒号后面必须是一个空格) - 注意:写这种文件不要使用 tab 键,都使用空格缩进
示例
---
# 一个 playbook 示例
- name: Update web servers
hosts: webservers
remote_user: root
tasks:
- name: Ensure apache is at the latest version
ansible.builtin.yum:
name: httpd
state: latest
- name: Write the apache config file
ansible.builtin.template:
src: /srv/httpd.j2
dest: /etc/httpd.conf
- name: Update db servers
hosts: databases
remote_user: root
tasks:
- name: Ensure postgresql is at the latest version
ansible.builtin.yum:
name: postgresql
state: latest
- name: Ensure that postgresql is started
ansible.builtin.service:
name: postgresql
state: started
二、playbook 语法
基本语法
# 运行 playbook
ansible-playbook file.yaml
playbook示例
---
# hosts: 用于指定要执行任务的主机,其可以是一个或多个由冒号分隔主机组。
- hosts: group1
# remote_user: 用于指定远程主机上的执行任务的用户
remote_user: root
# variables: 变量定义,可以被多次方便调用
vars:
- service: httpd
# tasks: 任务列表, 按顺序执行任务。如果一个 host 执行 task 失败, 整个 tasks 都会回滚, 修正 playbook 中的错误, 然后重新执行即可。
tasks:
# 第一组任务
- name: ensure apache is at the latest version
yum: name={{service}} state=latest
# 第二组任务
- name: write the apache config file
copy: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
# notify: 触发标识,含有 notify 的任务需要触发处理程序才能彻底完成。
notify:
# 调用的 handlers 任务的 name
- restart apache
# 第三组任务
- name: ensure apache is running (and enable it at boot)
service: name={{service}} state=started enabled=yes
# 待调用的任务
# handlers: 类似 task,但需要使用 notify 调用。handlers 最佳的应用场景是用来重启服务,或者触发系统重启操作。
handlers:
- name: restart apache
service: name={{service}} state=restarted
三、实战案例
httpd
---
- hosts: group1
remote_user: root
tasks:
- name: 删除 yum 源
file: path=/etc/yum.repos.d state=absent
- name: 配置 yum 源
copy: src=/etc/yum.repos.d dest=/etc/
- name: yum 安装 httpd
yum: name=httpd state=latest
- name: 配置 httpd 配置文件
copy: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify:
- restart apache
- name: 启动 httpd 并设置开机自启
service: name=httpd state=started enabled=yes
handlers:
- name: restart apache
service: name=httpd state=restarted
NFS
---
- hosts: nginx
remote_user: root
tasks:
- name: 安装 nfs 服务相关软件包
yum: name=nfs-utils,rpcbind,setup state=latest
- name: 创建共享目录
file: path=/share/ state=directory
- name: 同步 nfs 配置文件
copy: src=/etc/exports dest=/etc/exports
notify: restart nfs
- name: 启动 rpcbind 服务,并设置为开机自启动
service: name=rpcbind state=started enabled=on
- name: 启动 nfs 服务,并设置为开机自启动
service: name=nfs state=started enabled=on
handlers:
- name: restart nfs
service: name=nfs state=restarted
- hosts: php1
remote_user: root
tasks:
- name: 安装 nfs 客户端软件包
yum: name=nfs-utils state=latest
- name: 挂载 nfs 服务器的共享
shell: mount 10.1.1.12:/share /mnt