Playbook是Ansible的配置、部署、编排语言,它可以描述一系列的任务。本篇博客将讲解ansible的playbook的用法。ansible

Playbook的定义

核心元素
hosts: 主机 tasks: 任务 variables: 变量 templates: 包含了模板语法的文本文件 handlers: 由特定条件触发的任务 roles 角色

基础组件:
   hosts:  运行指定任务的目标主机
   remoute_user:   只远程主机上执行任务的用户
       sudo_user
   tasks:  任务列表
       模块,模块参数
       格式:
           action:module arguments
           module:arguments
   shell和command模块后面直接跟命令,而非key=value类的参数列表

一个playbook可以包含一到多个play,每一个play是一个完整的部署任务。但是为了playbook的可读性和维护,一般只会在playbook中编写一个play。

---
- name: install and configure apache
  hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=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 (and enable it at boot)
    service: name=httpd state=started enabled=yes
  handlers:
    - name: restart apache
      service: name=httpd state=restarted

这里定义了一个名为"install and configure apache"的play,分三步task,安装httpd,上传配置文件,启动服务。Handler:定义任务执行完成后将调用的其他任务。定义了一个名为"restart apache"的handler,并在出入配置文件后执行。 注意:在一个 play ⾥里⾯面⽆无论对一个 handlers 通知调⽤用多少次,都只是在所有任务执⾏完后执⾏一次。 执行方式:ansible-playbook install_apache.yaml –list-hosts,查看匹配的服务器列表。 –list-tasks,显示当前的任务列表。 –step,每执行一个任务后停止,等待用户确认。

Facts 变量

Facts变量是ansible执行远程部署之前从远程服务器中获取的系统信息。我们可以在playbook中直接通过变量的名字引用变量,下面通过setup模块查看facts变量列表。

[root@ ~]# ansible dns -m setup
172.31.101.11 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.31.101.11"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::5054:ff:fe55:5bc"
        ],
        "ansible_apparmor": {
            "status": "disabled"
        },
        "ansible_architecture": "x86_64",
        "ansible_bios_date": "04/01/2014",
        "ansible_bios_version": "1.9.1-5.el6",
        ...

常用模块

Template

作用:将模板文件中的变量,动态的替换为参数值,然后将文件复制到远程主机上,而copy只复制文件。Template提供了 框架式的配置文件,可以把Anisble需要的值插入到合适的位置。采用Jinja2语法进行定义,可以包含条件、循环、宏等功 能。 参数:

  1. src:本地源文件或者目录
  2. dest:目标文件或者目录
  3. backup:覆盖之前,是否备份原文件,yes/no 4. owner:设定文件/目录的属主
  4. group:设定文件/目录的属组
  5. mode:设定文件/目录的权限
  6. validate:在执行命令前先验证命令
 # Example from Ansible Playbooks
- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode=0644
# The same example, but using symbolic modes equivalent to 0644
- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r"
# Copy a new "sudoers" file into place, after passing validation with visudo
- template: src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'

wait_for

作用:用来检测一个tcp端口是否准备好接收远程连接,当在后台运行某些程序,或者启动某些进程需要一些时间的时候特 别有用。 参数:

  1. connect_timeout:等待建立连接的时间(秒),默认值5秒 2. delay:在开始监听钱需要等待的时间(秒)
  2. exclude_hosts:需要忽略的主机列表
  3. host:需要等待的主机,默认值127.0.0.1
  4. port:需要监听的端口
  5. state:包含:started(默认)、stopped、present、absent、drained 7. timeout:等待时间(秒),默认值300秒
---
- hosts: webapps
  tasks:
     - name: Install Tomcat
       yum: name=tomcat6 state=installed
     - name: Start Tomcat
       service: name=tomcat6 state=started
    - name: Wait for Tomcat to start
      action: wait_for: port=8080 state=started

模块太多,这里只做示例,更多模块用法,请参考:https://docs.ansible.com/

role介绍

role是一个规范与抽象,将复杂的playbook分割成多个文件的机制,大大简化了复杂playbook的编写。

.
├── defaults
│   └── main.yml    # 可以被覆盖的默认变量
├── files           # 保存需要上传到远程服务器的文件
├── handlers
│   └── main.yml    # 包含了所有的handler
├── meta
│   └── main.yml    # role的依赖信息
├── README.md
├── tasks           
│   └── main.yml    # 任务列表
├── templates       # 保存了jinja2模板文件
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml    # 不应该被覆盖的变量···············································

ansible-gaiaxy

  • 初始化一个roles的目录结构 ansible-galaxy init /etc/ansible/roles/websrvs
  • 安装别人写好的roles ansible-galaxy install -p /etc/ansible/roles bennojoy.nginx Ansibel Galaxy是一个在线playbook分享平台,有各类常用功能的roles,可自行下载。

最佳实践

官方ansible在github上提供了一些最佳实践的模板,这里拿lamp_simple来学习。

├── LICENSE.md
├── README.md
├── group_vars
│   ├── all
│   └── dbservers
├── hosts
├── roles
│   ├── common
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── templates
│   │       └── ntp.conf.j2
│   ├── db
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   └── templates
│   │       └── my.cnf.j2
│   └── web
│       ├── handlers
│       │   └── main.yml
│       ├── tasks
│       │   ├── copy_code.yml
│       │   ├── install_httpd.yml
│       │   └── main.yml
│       └── templates
│           └── index.php.j2
└── site.yml

结构非常清晰,入口文件为site.yml,包含三个roles,分别为common、db、web 再看一下site.yml

⇒  cat site.yml
---
# This playbook deploys the whole application stack in this site.

- name: apply common configuration to all nodes
  hosts: all
  remote_user: root

  roles:
    - common

- name: configure and deploy the webservers and application code
  hosts: webservers
  remote_user: root

  roles:
    - web

- name: deploy MySQL and configure the databases
  hosts: dbservers
  remote_user: root

  roles:
    - db

完整代码请看:https://github.com/ansible/ansible-examples