1)Playbook由一个或多个"play"组成的列表,play的主要功能Ansible中的Task定义好的角色,指定剧本对应的服务器组。nginx
于Ansible Playbook还能够收集命令、能够建立任务集,这样可以大大下降管理工做的复杂程度,Playbook采用YAML语法结构,易于阅读、方便配置。web
2)Playbooks组件包括以下:shell
Target 定义playbook的远程主机组
Variable 定义playbook使用的变量
Task 定义远程主机上执行的任务列表
Handler 定义task执行完成之后须要调用的任务
3)Target 经常使用参数以下:服务器
hosts 定义远程主机组;
user 执行该任务的用户;
sudo 设置为yes的时候,执行任务的时候使用root权限;
sudo_user 指定sudo普通用户;
connection 默认基于SSH链接客户端;
gather_facks 获取远程主机facts基础信息。
4)Variable 经常使用参数以下:spa
vars 定义格式,变量名:变量值;
vars_files 指定变量文件;
vars_prompt 用户交互模式自定义变量;
setup 模块去远程主机的值;
5)Task经常使用参数以下:code
name 任务显示名称即屏幕显示信息
action 定义执行动做
copy 复制本地文件到远程主机
template 复制本地文件到远程主机,能够引用本地变量
service 定义服务的状态
二、远程主机安装Nginx WEB服务,playbook代码以下server
-host:all remote_user: root tasks: -name:pcre pcre-devel and zlib lib install yum: name=pcre,pcre-devel,zlib,zlib-devel state=install -name: Nginx WEB Server Install Process shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2.tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install
1)检测远程主机Nginx目录是否存在,不存在则安装Nginx WEB服务,安装完并启动Nginx,playbook代码以下blog
- hosts: all remote_user: root tasks: - name: Nginx server Install file: path=/usr/local/nginx/ state=directory notify: - nginx install - nginx start handlers: - name: nginx install shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2 .tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install - name: nginx start shell: /usr/local/nginx/sbin/nginx
2)检测远程主机内核参数配置文件是否更新,若是更新则执行命令sysctl –p使内核参数生效,playbook代码以下rem
- hosts: all remote_user: root tasks: - name: Linux kernel config 2019 copy: src=/data/sh/sysctl.conf dest=/etc/ notify: - source sysctl handlers: - name: source sysctl shell: sysctl -p
3)基于列表items多个值建立用户,经过{{}}定义列表变量,with_items选项传入变量的值get
- hosts: all remote_user: root tasks: - name: Linux system Add User list. user: name={{ item }} state=present with_items: - jfedu1 - jfedu2 - jfedu3 - jfedu4
4)Ansible Playbook能够自定义template模板文件,模板文件主要用于服务器需求不一致的状况,须要独立定义的,例如两台服务器安装了Nginx,安装完毕以后将服务器A的HTTP端口改为80,服务器B的HTTP端口改为81,基于tempalte模块轻松实现
Ansible hosts文件指定不一样服务器不一样httpd_port端口
[web] 192.168.0.112 httpd_port=80 192.168.0.113 httpd_port=81
Ansible 建立nginx.conf jinja2模板文件,cp nginx.conf nginx.conf.j2,并修改listen 80为listen {{httpd_port}},Nginx其余配置项不变
cp nginx.conf nginx.conf.j2
listen {{httpd_port}};
Ansible playbook剧本yaml文件建立
- hosts: all remote_user: root tasks: - name: Nginx server Install 2019 file: path=/usr/local/nginx/ state=directory notify: - nginx install - nginx config handlers: - name: nginx install shell: cd /tmp;rm -rf nginx-1.12.2.tar.gz;wget http://nginx.org/download/nginx-1.12.2.tar.gz;tar xzf nginx-1.12.2 .tar.gz;cd nginx-1.12.2;./configure --prefix=/usr/local/nginx;make;make install - name: nginx config template: src=/root/nginx.conf.j2 dest=/usr/local/nginx/conf/nginx.conf
Ansible playbook执行剧本文件