Playbook 是 Ansible 进行配置管理的组件,虽然 Ansible 的日常 AD-Hoc 命令功能很强大,可以完成一些基本的配置管理工作,但是 AD-Hoc 命令无法支撑复杂环境的 配置管理工作。在我们实际使用 Ansible 的工作中,大部分时间都是在编写 Playbook 。
简单地说,playbook 是一个非常简单的配置管理和多机部署系统的基础,不像任何已经存在的系统,它非常适合部署复杂的应用程序。
Playbook 基本语法
Ansible 的 Playbook 文件格式 YAML 语法,所以需要对 YAML 语法有一定的了解。
下面通过一个安装部署 Nginx 的案例来进行讲解
---- hosts: webservers vars: http_port: 80 max_clients: 200 remote_user: root tasks: - name: ensure apache is at the latest version yum: name: httpd state: latest - name: write the apache config file template: src: /srv/httpd.j2 dest: /etc/httpd.conf notify: - restart apache - name: ensure apache is running service: name: httpd state: started handlers: - name: restart apache service: name: httpd state: restarted
复制代码
其中,notify 是触发 handlers,如果同步后,文件的 MD5 值有变化会触发 restart apache 这个 handler
handlers 是定义一个 handler 状态让 httpd 服务重启,handler 的名称是 restart apache 。
Playbook 也可以定义多个步骤,在一个 Playbook 里可以先执行一组服务器,再执行第二组服务器。
---- hosts: webservers remote_user: root
tasks: - name: ensure apache is at the latest version yum: name: httpd state: latest - name: write the apache config file template: src: /srv/httpd.j2 dest: /etc/httpd.conf
- hosts: databases remote_user: root
tasks: - name: ensure postgresql is at the latest version yum: name: postgresql state: latest - name: ensure that postgresql is started service: name: postgresql state: started
复制代码
Playbook 主机和用户
对于 Playbook 中的每个步骤,您可以选择基础设施中的哪些机器作为目标,以及哪些远程用户作为完成步骤(称为任务)的对象。
hosts 这一行是一个或多个组或主机模式的列表,用冒号分隔,如使用模式文档中所述。remote_user 只是用户帐户的名称:
---- hosts: webservers remote_user: root
复制代码
远程用户也可以写在每个任务中
---- hosts: webservers remote_user: root tasks: - name: test connection ping: remote_user: username
复制代码
也支持使用其他用户
---- hosts: webservers remote_user: username become: yes
复制代码
也可以使用关键字 become 在每个任务里来代替放在全局里。
---- hosts: webservers remote_user: yourname tasks: - service: name: nginx state: started become: yes become_method: sudo
复制代码
也可以使用其他的提权模式
---- hosts: webservers remote_user: yourname become: yes become_method: su
复制代码
评论