DAY88 ansible自动化运维工具

306 阅读20分钟

一、简介

ansible是一种自动化运维工具,基于paramiko开发的,并且基于模块化工作,Ansible是一种集成IT系统的配置管理、应用部署、执行特定任务的开源平台,它是基于python语言,由Paramiko和YAML两个关键模块构建。集合了众多运维工具的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能.ansible是基于模块工作的,本身没有批量部署的能力.真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架.ansible不需要在远程主机上安装client/agents,因为它们是基于ssh来和远程主机通讯的。

Ansible的四个组件:

  • Inventory 主机清单(主机组)
  • Modules 模块
  • Plugins 插件
  • Playbooks 剧本(相当于脚本)

image.png

Ansible的特性

(1)特性一:

Ansible其中一个比较鲜明的特性Agentless,即无Agent的存在(无代理端,即无客户端),它就像普通命令一样, 并非c/s软件,也只需在某个作为控制节点的主机上安装一次Ansible即可,通常它基于ssh连接来控制远程主机,远程主机上不需要安装Ansible或其它额外的服务。

使用者在使用时,在服务器终端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play(一个play就是一个Linux操作),再组织成ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除。

(2)特性二:

Ansible的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是多次操作或多次执行对系统资源的影响是一致的。

比如执行 systemctl stop xxx 命令来停止服务,当发现要停止的目标服务已经处于停止状态,它什么也不会做,所以多次停止的结果仍然是停止,不会改变结果,它是幂等的,而systemctl restart xxx是非幂等的。

Ansible的很多模块在执行时都会先判断目标节点是否要执行任务,所以,可以放心大胆地让Ansible去执行任务,重复执行某个任务绝大多数时候不会产生任何副作用。

Ansible 环境安装部署实验环境:

角色IP安装工具
管理端192.168.184.101ansible
被管理端192.168.184.102无需安装
被管理端192.168.184.103无需安装
被管理端192.168.184.104无需安装

安装部署:

 #1、管理端安装ansible
 yum install -y epel-release   #先安装epel源
 yum install -y ansible        #安装ansible
 ​
 #ansible目录结构
 [root@yuji ~]# cd /etc/ansible
 [root@yuji ansible]# tree
 .
 ├── ansible.cfg
 ├── hosts
 └── roles
 ​
 1 directory, 2 files
 ​
 ​
 #2、配置主机清单,修改/etc/ansible/hosts文件
 cd /etc/ansible
 vim hosts
 [webservers]    #配置组名
 192.168.184.102   #组里包含被管理的主机IP或主机名(主机名需要先修改/etc/hosts文件)
 192.168.184.103
 ​
 [dbservers]      #第二个组
 192.168.184.104
 ​
 #3、ansible默认使用ssh连接,所以管理前要设置免密登录
 #配置密钥对验证
 ssh-keygen -t rsa    #一路回车,生成密钥文件
 ​
 vim /etc/ssh/ssh_config      #修改ssh客户端配置文件
 StrictHostKeyChecking no     #35行,取消注释,将ask修改为no,开启免交互
 ​
 systemctl restart sshd       #重启sshd
 ​
 #使用sshpass,以免交互的方式将公钥文件传给被管理端,实现免密登录
 sshpass -p '144080' ssh-copy-id root@192.168.184.102
 sshpass -p '144080' ssh-copy-id root@192.168.184.103
 sshpass -p '144080' ssh-copy-id root@192.168.184.104
 ​
 #如果被管理端主机有很多台,可以通过sshpass和for循环写一个脚本,实现多台主机免密登录。


image.png

image.png

image.png

image.png

ansible常用的命令行模块

ansible管理命令:

 ansible <组名> -m <模块> -a <参数列表>
 ​
 ansible <主机IP> -m <模块> -a <参数列表>
 ​
 ansible <主机名> -a <参数列表>      #不加-m指定模块默认使用command
 ​
 #选项解释
 -m: 指定模块
 -a: 指定命令
复制代码

查看ansible的模块:

 ansible-doc -l   #列出所有已安装的模块,按q退出
 ​
 ansible-doc -l | wc -l   #统计总共有多少模块
 3387
 ​
 ansible-doc -s 模块   #查看指定模块的描述信息和操作动作

command模块

在远程主机执行命令,不支持管道、重定向等shell的特性。

 ​
 #指定ip执行date
 ansible 192.168.41.42 -m command -a 'date'   #-a指定命令
 ​
 #指定组执行date命令
 ansible webservers -m command -a 'date'     #指定webservers组执行date命令
 ansible dbservers -m command -a' date'      #指定dbservers组执行date命令
 ansible all -m command -a ' date'           #all代表所有hosts 主机
 ansible all -a 'date'                      #如省略-m模块,则默认运行command 模块
 ​
 ​
 ##常用的参数:
 chdir:在远程主机上运行命令前提前进入目录
 creates:判断指定文件是否存在,如果存在,不执行后面的操作
 removes:判断指定文件是否存在,如果存在,执行后面的操作
 ​
 #无论管理端当前在哪个目录,执行命令都是在被管理端的家目录进行操作,可以使用chdir参数先切换目录
 ansible dbservers -m command -a "chdir=/home ls ./"   #切换到/home目录下再执行命令
 ​
 #creates判断目标主机的指定是否存在,如果存在,则不执行后面的操作
 ansible dbservers -m command -a "creates=/data/f1.txt date"
 ansible dbservers -m command -a "creates=/data/aa.txt date"
 ​
 #removes判断目标主机的指定是否存在,如果存在,执行后面的操作
 ansible dbservers -m command -a "removes=/data/f1.txt date"
 ansible dbservers -m command -a "removes=/data/aa.txt date"


image.png

image.png

常用参数示例:

(1)chdir

在远程主机上运行命令前提前进入目录。

 #无论管理端当前在哪个目录,执行命令都是在被管理端的家目录进行操作,可以使用chdir参数切换目录。
 ​
 #目标主机切换到/home/目录后,再执行命令
 [root@ ~]# ansible dbservers -m command -a "chdir=/home ls ./"
 192.168.41.44 | CHANGED | rc=0 >>
 hang
 #目标主机切换到/opt/目录后,再执行命令
 [root@ ~]# ansible dbservers -m command -a "chdir=/opt ls ./"
 192.168.41.44 | CHANGED | rc=0 >>
 abc.txt
 elasticsearch-6.7.2.rpm
 elasticsearch-head-master.zip
 node-v8.2.1
 node-v8.2.1.tar.gz
 phantomjs-2.1.1-linux-x86_64.tar.bz2
 rh


image.png

image.png

(2)creates

判断指定文件是否存在,如果存在,不执行后面的操作。

 #creates判断目标主机的指定文件是否存在,如果存在,则不执行后面的操作
 ​
 #查看目标主机的/data目录,只有f1.txt文件
 [root@ ~]# ansible dbservers -m command -a "chdir=/data ls ./"
 192.168.41.44 | CHANGED | rc=0 >>
 f1.txt
 ​
 #判断/data/f1.txt是否存在,因为存在,所以跳过后面的命令操作
 [root@ ~]# ansible dbservers -m command -a "creates=/data/f1.txt date"192.168.41.44 | SUCCESS | rc=0 >>
 skipped, since /data/f1.txt exists
 ​
 #判断/data/aa.txt是否存在,因为不存在,所以执行后面的date命令
 [root@~]# ansible dbservers -m command -a "creates=/data/aa.txt date"192.168.41.44 | CHANGED | rc=0 >>
 2022年 07月 05日 星期二 20:22:61 CST

image.png

(3)removes

判断指定文件是否存在,如果存在,执行后面的操作。

 #判断/data/f1.txt是否存在,因为存在,所以执行后面的date命令
 [root@yuji ~]# ansible dbservers -m command -a "removes=/data/f1.txt date"192.168.41.44 | CHANGED | rc=0 >>
 20220705日 星期二 20:40:17 CST
 ​
 #判断/data/aa.txt是否存在,因为不存在,所以跳过后面的操作
 [root@yuji ~]# ansible dbservers -m command -a "removes=/data/aa.txt date"192.168.41.44 | SUCCESS | rc=0 >>
 skipped, since /data/aa.txt does not exist

image.png

shell模块

在远程主机执行命令,相当于调用远程主机的shell进程,然后在该shell下打开一个子shell运行命令。支持管道符号和重动向等功能。

 ansible-doc -s shell  #查看shell模块的描述信息和操作动作
 ​
 #shell模块支持重定向功能
 ansible dbservers -m shell -a 'echo hello> /opt/abc.txt'
 ​
 #shell模块支持管道符号。
 ansible dbservers -m shell -a 'echo 123456| passwd -stdin hang'   #免交互的方式修改用户密码
 ​
 #过滤出ens33网卡的地址
 ansible dbservers -m shell -a 'ifconfig ens33 | awk "NR==2 {print $2}"'  #要在$前加\让awk使用,不然ansible会认为是变量

image.png

示例1:

shell模块支持重定向功能。

 #shell模块支持重定向功能
 ansible dbservers -m shell -a 'echo hello> /opt/abc.txt'

image.png

示例2:

shell模块支持管道符号。

 #免交互的方式修改用户密码
 ansible dbservers -m shell -a 'echo 123456| passwd --stdin hang'
 ​
 #过滤出ens33网卡的地址
 ansible dbservers -m shell -a 'ifconfig ens33 | awk "NR==2 {print $2}"'  
 #注意:外面已经有单引号了,所以awk要使用双引号。且要在$前加\让awk使用,不然ansible会认为是变量。

image.png

cron模块

在远程主机定义任务计划。其中有两种状态(state) :

  • present 表示添加(可以省略)
  • absent 表示移除。
 ansible-doc -s cron    #查看cron模块包含的操作动作
 ​
 #常用的参数: 
 minute/hour/day/month/weekday:分////周
 job:任务计划要执行的命令,尽量使用绝对路径。
 name:任务计划的名称。

image.png

示例1:

写一个计划任务,要求每分钟输出一次“helloworld”,任务名称为test1。

 ansible dbservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test1"'
 ​
 ansible dbservers -m command -a 'crontab -l'   #查看目标主机的计划任务
 ​
 #切换到目标主机,查看刚刚创建的计划任务,可以看到是Ansible创建的,且任务名称为test1
 [root@44 opt]# crontab -l
 #Ansible: test1
 */1 * * * * /bin/echo helloworld

image.png

示例2:

写出每两个月的10号的早上和晚上十点的第十分钟执行一次复制系统内核日志到/opt/的方法。

 #主机自己直接写计划性任务:
 crontab -e
 10 10,22 10 */2 * /usr/bin/cp /var/log/messages /opt/
 ​
 #使用ansible管理目标主机:
 ansible dbservers -m cron -a 'minute="10" hour="10,22" day="10" month="*/2" job="/usr/bin/cp /var/log/messages /opt/" name="test2"'
 ​
 ​
 #移除计划性任务test2。如果加入该计划时没有名字,name=None即可。
 ansible dbservers -m cron -a 'name="test2" state=absent'
 ​
 #查看目标主机的计划任务
 ansible dbservers -a 'crontab -l'

image.png

删除计划任务:

image.png

user模块

 ansible-doc -s user    #查看user模块包含的操作动作

常用参数:

参数说明
name用户名,必选参数。
state=present 或 absent创建账号或者删除账号,present表示 创建,absent 表示删除。
system=yes 或 no是否为系统账号。
uid用户uid。
group用户基本组。
groups用户附加组。
shell默认使用的登录shell
move_home=yes 或 no如果设置的家目录已经存在,是否将已经存在的家目录进行移动。
password用户的密码,建议使用加密后的字符串。
comment用户的注释信息。
remove=yes 或 no表示当state=absent时,是否删除用户的家目录。即删除用户时,是否同时删除家目录。yes表示删除用户的家目录。

示例1:

 ansible dbservers -m user -a 'name="test01"'   #创建用户test01
 ansible dbservers -a 'tail -1 /etc/passwd'     #查看目标主机的用户账号文件
 ​
 ansible dbservers -m user -a 'name="test01"'
 #再次执行相同命令,状态为success,而不是changed,因为user模块不具有幂等性。

image.png

示例2:

 #删除用户test01,但保留家目录。删除家目录要加remove=yes
 ansible dbservers -m user -a 'name="test01" state=absent'
 ansible dbservers -a 'id test01' 
 ansible dbservers -a 'ls /home' 

image.png

示例3:

 #创建名称为qiangge的用户,uid为9526,添加附加组wheel
 ansible dbservers -m user -a 'name="qiangge" uid=9526 groups=wheel'
 ansible dbservers -a 'grep qiangge /etc/passwd'
 ​
 #之后为qiangge用户设置密码,并且让其不可登录系统。
 ansible dbservers -m user -a 'name="qiangge" password="123456" shell="/sbin/nologin"'
 ansible dbservers -a 'grep qiangge /etc/passwd'
 ansible dbservers -a 'grep qiangge /etc/shadow'
 ​
 #删除用户qiangge,且删除家目录
 ansible dbservers -m user -a 'name="qiangge" state=absent remove=yes'
 ansible dbservers -a 'id qiange' 
 ansible dbservers -a 'ls /home' 

image.png

image.png

group模块

管理用户组的模块。

注意:字符串类型的值建议加双引号,防止有空格。数字和布尔值不要加双引号。

 ansible-doc -s group    #查看group模块包含的操作动作
 ​
 #创建mysql组,设置为系统组。
 ansible dbservers -m group -a 'name="mysql" gid=306 system=yes'
 ansible dbservers -a 'tail -3 /etc/group'
 ​
 #创建用户test02,设置为系统用户,基本组设置为mysql组。
 ansible dbservers -m user -a 'name="test02" uid=306 system=yes group="mysql"'
 ansible dbservers -a 'id test02'

image.png

image.png

 copy模块

用于将本地文件复制到远程主机。

 ansible-doc -s copy     #查看copy模块包含的操作动作

常用参数:

参数说明
src指出源文件的路径(位于控制节点,即管理端),可以使用相对路径或绝对路径,支持直接指定目录,如果源是目录则目标也要是目录。
dest指出复制文件的目标及位置,使用绝对路径,如果源是目录则目标也要是目录,如果目标文件已经存在会覆盖原有的内容。
mode指出复制时,目标文件的权限。
owner指出复制时,目标文件的属主。
group指出复制时,目标文件的属组。
content指出复制到目标主机上的内容,不能与src一起使用。

示例1:

 #将本地的/etc/hosts文件,复制到远程主机的/data/目录下,并重命名为hosts.bak,文件属主设置为root、属组设置为mysql,权限设置为640。
 ansible dbservers -m copy -a 'src=/etc/hosts dest=/data/hosts.bak owner=root group=mysql mode=640'
 ansible dbservers -a 'ls -l /data'     #查看文件权限

image.png

示例2:

 #将helloworld写入远程主机的/data/hello.txt文件中
 ansible dbservers -m copy -a 'content="helloworld" dest=/data/hello.txt'
 ansible dbservers -a 'cat /data/hello.txt'

image.png

file模块

为远程主机创建/删除文件或目录,设置文件属性。

主要参数如下:

参数说明
path指定远程服务器的路径,也可以写成"dest","name"
state状态,可以将值设定为directory表示创建目录,设定为touch表示创建文件,设定为link表示创建软链接,设定为hard表示创建硬连接,设定为absent表示删除目录文件或链接
mode文件复制到远程并设定权限,默认file=644,directory=755
owner文件复制到远程并设定属主,默认为root
group文件复制到远程并设定属组,默认为root
recurese递归修改
src指的是目标主机上的源文件。与copy模块不同。

示例1:修改文件的属主、属组、权限等

 ansible-doc -s file    #查看file模块包含的动作
 ​
 #修改文件的属主、属组、权限等。
 ansible dbservers -m file -a 'path=/data/hosts.bak owner=test02 group=root mode=644'
 ansible dbservers -a 'ls -l /data'

image.png

示例2:创建软链接文件

 #设置/opt/passwd.link为/etc/passwd的链接文件。state=link表示创建软链接。
 ansible dbservers -m file -a 'path=/opt/passwd.link src=/etc/passwd state=link'
 ansible dbservers -a 'ls -l /opt'
 ​
 #注意:src指的是目标主机上的源文件,与copy模块不同。

image.png

*示例3:创建和删除文件、目录

 #创建一个文件
 ansible dbservers -m file -a 'path=/data/aa.txt state=touch'
 ansible dbservers -a 'ls /data'
 ​
 #删除文件/data/aa.txt
 ansible dbservers -m file -a 'path=/data/aa.txt state=absent'
 ansible dbservers -a 'ls /data'
 ​
 #创建一个目录
 ansible dbservers -m file -a 'path=/data/hr state=directory'
 ansible dbservers -a 'ls -l /data'


image.png

image.png

hostname模块

用于管理远程主机上的主机名。

 ansible dbservers -m hostname -a 'name=myhost7-4'  #修改dbservers组的主机名

image.png

ping模块

测试远程主机的连通性。

 ansible all -m ping   #测试所有主机的连通性

image.png

 yum模块

在远程主机上安装与卸载软件包, 需要被管理端配置好yum源。

主要的参数如下:

参数说明
name指定安装软件包名或软件包URL
state指定yum对应的方法,present(默认)、installed表示安装、latest表示安装最新版本软件包;absent、removed表示卸载。支持多程序一起安装,用逗号隔开。
enablerepo允许从哪些仓库获取软件
disablerepo禁止从哪些仓库获取软件
exclude排除某些软件包,例如kernel
download_only仅下载软件包,不安装
disable_gpg_check不进行gpg检测
update_cache可以在安装包的同时更新yum缓存

示例:

 ansible-doc -s yum     #查看yum模块包含的操作动作
 ​
 ansible dbservers -m yum -a 'name=httpd'     #安装httpd服务
 ansible dbservers -m yum -a 'name=httpd state=absent'   #卸载httpd服务
 ​
 #yum一次性卸载所有主机的httpd服务
 ansible all -m yum -a "name=httpd state=absent"

image.png

image.png

image.png

service/systemd 模块

主要参数如下:

参数说明
name指定需要控制的服务名称
state指定服务状态,其值可以为stopped、started、reloaded、restarted、status
enabled指定服务是否为开机启动,yes为启动,no为不启动
daemon_reloadyes:重启systemd服务,让unit文件生效

示例:

 ansible-doc -s service     #查看service模块包含的操作动作
 ​
 #查看web服务器httpd运行状态
 ansible webservers -a 'systemctl status httpd'
 ​
 #启动httpd服务,并设置为开机自启
 ansible webservers -m service -a 'name=httpd state=started enabled=true'

image.png

script 模块

实现远程批量运行本地的shell脚本。

注意:script模块不具有幂等性。所以建议用剧本来执行。

 ansible-doc -s script
 ​
 #在本地写一个脚本
 vim test.sh
 #!/bin/bash
 echo "hello ansible from script" > /data/script.txt
 ​
 chmod +x test.sh                              #给脚本执行权限
 ansible dbservers -m script -a 'test.sh'      #远程运行本地脚本
 ansible dbservers -a 'cat /data/script.txt'   #查看生成的文件内容是否为指导内容
 
 
 #再次运行相同脚本,状态为changed,而不是successs,因为script模块不具有幂等性
 ansible dbservers -m script -a 'test.sh'

image.png

注意:script模块不具有幂等性。

setup 模块

facts组件是用来收集被管理节点信息的,使用setup 模块可以获取这些信息。

 ansible-doc -s setup   #查看setup模块包含的操作动作
 ​
 #获取dbservers组主机的facts信息
 ansible dbservers -m setup
 ​
 #使用filter参数可以筛选指定的facts信息
 ansible dbservers -m setup -a 'filter=*ipv4'

image.png

Ansible Playbook 剧本语法

Playbook(剧本)是系统 Ansible 指令的集合,其利用 YAML 语言编写,自上而下按顺序一次执行。它可以实现一些 Ad-Hoc 指令无法实现的操作,例如从一台机器的文件中抓取内容并赋为另一台机器的变量等操作。

下面是一个 Playbook 剧本例子:

---
- 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
    service: name=httpd state=started
  handlers:
    - name: restart apache
      service: name=httpd state=restarted
复制代码

第一行中 --- 是 YAML 将文件解释为正确文档的格式要求,YAML 它允许多个文档存在与同一个文件中,每个文档由 --- 符号分割。通常一个 Playbook 对应一个文档,因此你也可以省略它。

YAML 具有强制性的格式规范,对空格非常敏感,通过空格来将不同信息分组在一起,而不能使用制表符,并且必须使用一致的间距才能正确读取文件。

- 开头的项目被视为列表项目,具有 key:value 格式的项。

YAML 文件的扩展名通常为 .yaml 或 .yml。

Playbook 的执行结果有三种颜色:

  • 红色: 表示有task执行失败或者提醒的信息
  • 黄色:表示执行了且改变了远程主机状态
  • 绿色:表示执行成功

Playbook 剧本语法

一个 Playbook 主要有以下四部分构成:

  • **target section:**定义将要执行 playbook 的远程主机组;
  • **variable section:**定义 playbook 运行时需要使用的变量;
  • **task section:**定义将要在远程主机上执行的任务列表;
  • **handler section:**定义task执行完成以后需要调用的任务;

Hosts(主机) 与 Users(用户)

每一个 Play 都要指定操作的目标主机,并且可以指定用哪个身份去完成执行的步骤(Tasks)。例如:

- hosts: webservers
  remote_user: root
  tasks:
    - name: test connection
      remote_user: yourname
      sudo: yes
复制代码
  • hosts:用于指定要执行指定任务的主机,可以是一个或多个,由逗号分隔符分隔的主机组。
  • remote_user:用于指定远程主机上执行任务的用户,它也可用于各tasks中。
  • sudo:如果设置为 yes 则获取 root 权限去执行该任务,如果需要在使用 sudo 时指定密码,可在运行 ansible-playbook 命令时加上选项 --ask-sudo-pass (-K)
  • connection:通过什么方式连接到远程主机(默认 ssh)。
  • gather_facts:默认会执行 setup 模块,设置该选项设置为 False 可以关闭自动执行 setup 模块。

vars (环境变量)

在执行 ansible-playbook 时通过添加选项 --extra-vars 看定义环境变量,可以在 Playbook 中定义,还可以在主机清单文件中配置。如果环境变量之间有冲突,则三者的优先级从高到低。

在 Playbook 中通过 {{ var_name }} 引用环境变量,如:

- hosts: all
  vars:  
    file_name: test

  tasks:
  - name:
    file: path=/tmp/{{ file_name }} state=touch
复制代码

register (注册变量)

通过 register 关键字可以存储指定命令的输出结果到一个自定义的变量中。

- hosts: all
  tasks:
    - name:
      shell: netstat -lntp
      register: System_Status

    - name: Get System Status
      debug: msg={{System_Status.stdout_lines}}
复制代码

tasks (任务)

每一个 Play 包含了一个 tasks 任务列表,任务列表中的任务会按次序逐个在指定的主机上执行,并且完成第一个后再开始第二个任务。

tasks 通过模块来完成实际操作,其格式为 "module:options",除了 Command 和 Shell 模块之外,通常大多数模块使用 key=value 格式的参数。

tasks:
 - name: make sure apache is running
   service: name=httpd state=running
   
tasks:
 - name: disable selinux
   command: /sbin/setenforce 0

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True
复制代码

when (条件语句)

Playbook 中的条件判断语句使用 when,通常这可以结合 Setup 模块针对不同系统主机执行不同的操作。

- hosts: all
  remote_user: root
  tasks:
    - name: Create File
      file: path=/tmp/this_is_{{ ansible_hostname }}_file state=touch
      when: (ansible_hostname == "nfs") or (ansible_hostname == "backup")

#系统为centos的主机才会执行
    - name: Centos Install httpd
      yum: name=httpd state=present
      when: (ansible_distribution == "CentOS")

#系统为ubuntu的主机才会执行
    - name: Ubuntu Install httpd
      yum: name=httpd2 state=present
      when: (ansible_distribution == "Ubuntu")
复制代码

with_items (循环语句)

除了条件语句之外,还可以使用循环语句 with_items,例如下面场景中通过循环语句批量安装软件:

- hosts: all
  remote_user: root
  tasks:
    - name: Installed Pkg
      yum: name={{ item }} state=present
      with_items:
        - wget
        - tree
        - lrzsz
复制代码

或者批量创建用户:

- hosts: all
  remote_user: root
  tasks:
    - name: Add Users
      user: name={{ item.name }} groups={{ item.groups }} state=present
      with_items:
        - { name: 'testuser1', groups: 'bin' }
        - { name: 'testuser2', groups: 'root' }
复制代码

ignore_errors (异常处理)

默认 Playbook 会检查命令和模块的返回状态,如遇到错误就中断执行。通过加入参数 ignore_errors: yes 来忽略错误。

- hosts: all
  remote_user: root
  tasks:
    - name: Ignore False
      command: /bin/false
      ignore_errors: yes

    - name: touch new file
      file: path=/tmp/bgx_ignore state=touch

复制代码

tags (标签)

通过对任务添加一个至多个标签,可以在执行 ansible-playbook 指令时使用 -t--skip-tags 选项来控制执行指定标签任务,或跳过指定标签的任务。

- hosts: all
  remote_user: root
  tasks:
    - name: Install Nfs Server
      yum: name=nfs-utils state=present
      tags:
        - install_nfs
        - install_nfs-server

    - name: Service Nfs Server
      service: name=nfs-server state=started enabled=yes
      tags: start_nfs-server
复制代码

使用 -t 指定 tags 执行, 多个 tags 使用逗号隔开即可:

ansible-playbook -t install_nfs-server playbook.yml
复制代码

handlers (触发回调)

我们还可以通过 handlers 在某个任务执行完成后触发某些操作,例如当一个文件内容被改动时,重启两个 services,如下面 Playbook:

- hosts: all
  remote_user: root
  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=apache state=restarted       
复制代码

notify 下列出的即是 Handlers,Handlers 其实也是一些 tasks 的列表。

Handlers 是由通知者进行 notify,如果没有被 notify,Handlers 不会执行。

include (引入外部 Tasks 模块)

include 用来动态的包含 Tasks 任务列表。

- hosts: all
  remote_user: root
  tasks:
    - include_tasks: p1.yml
    - include_tasks: p2.yml

总结

Ansible的特性:

(1)Ansible其中一个比较鲜明的特性Agentless,即无Agent的存在,只需在某个作为控制节点的主机上安装一次Ansible即可,通常它基于ssh连接来控制远程主机,远程主机上不需要安装Ansible或其它额外的服务。

(2)Ansible的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是多次操作或多次执行对系统资源的影响是一致的。

注意:script模块不具有幂等性。所以建议用剧本来执行。