ansible之playbook

playbook是由一个或多个“play”组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲,所谓task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让它们联合起来按事先编排的机制完成某一任务

Playbook:

- host: websrvs                #定义执行的主机
  remote_user: root            #定义执行的用户
  tasks:                       #定义任务
    - task1                    #定义第一个任务名称
    module_name: module_args   #定义使用的模块,和模块参数
   -  task 2                   #定义第二个任务名称

Target section

定义将要执行playbook的远程主机组

Variable section

定义playbook运行时需要使用的变量

Task section

定义将要在远程主机上执行的任务列表

Handler section

定义task执行完成以后需要调用的任务

Target section

hosts:定义远程的主机组

user:执行该任务组的用户

remote_user:与user相同

sudo:如果设置为yes,执行该任务组的用户在执行任务的时候,获取root权限

sudo_user:如果你设置user为tom,sudo为yes,sudo_user为jerry,则tom用户则会获取jerry用户的权限

connection:通过什么方式连接到远程主机,默认为ssh

gather_facts:除非你明确说明不需要在远程主机上执行setup模块,否则默认会自动执行。如果你确实不需要setup模块所传递过来的变量,你可以启用该选项 

Variable section

Vars 直接定义变量

vars:

http_port: 80

server_name: localhost

cert_file: /etc/nginx/ssl/nginx.crt

key_file: /etc/nginx/ssh/nginx.key

conf_file: /etc/nginx/conf/default.conf

vars_files通过文件定义变量

paybook文件指定vars_files文件名

vars_files:

- /vars/nginx_vars.yml

/vars/nginx_vars.yml内容示例:

http_port: 80

server_name: localhost

cert_file: /etc/nginx/ssl/nginx.crt

key_file: /etc/nginx/ssh/nginx.key

conf_file: /etc/nginx/conf/default.conf

vars_prompt实现人机交互

vars_prompt:

- name: 'http_passphrase'          #存储数据的变量名

prompt: 'Key Passphrase'          #手工输入数据

private: yes                      #当该值为yes,则用户的输入不会被打印

Task section

tasks:

- name: install apache安装

action: yum name=httpd state=installed

- name: configure apache配置

copy: src=files/httpd.conf dest=/etc/httpd/conf/httpd.conf

- name: restart apache启动

service:

name: httpd

state: restarted

Handler section

Notify定义当前task执行完要执行的操作

tasks:

- name: template configuration file

template: src=template.j2 dest=/etc/foo.conf

notify:

- restart memcached

- restart apache

handlers:

- name: restart memcached

service: name= memcached state=restarted

- name: restart apache

service: name=httpd state=restarted

条件测试

when 当条件满足才执行

tasks:
  - name: "shutdown Debian flavored systems"
    command: /sbin/shutdown -h now
    when: ansible_os_family == "Debian"

迭代 重复执行,例如yum多个包,创建多个用户

- name: add several users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }

一个安装memcached的事例

- hosts: all

user: root

tasks:

- name: install memcached

yum: name=memcached state=installed

- name: set memcached size

set_fact: memcached_size="{{ ansible_memtotal_mb /4 }}"

- name: copy configurations

template: src=templates/memcached.j2 dest=/etc/sysconfig/memcached

notify:

- restart memcached

handlers:

- name: restart memcached

service: name=memcached state=restarted enabled=yes

ansible之playbook
http://www.jcwit.com/article/212/
作者
Carlos
发布于
2018年7月24日
许可协议