ansible详解

一、ansible简介

1、ansible是什么?

        ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能

2、组织结构

     ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架,如下图所示:

wKiom1Rsxz3ToUCAAAGROYAM3EI989.jpg

主要包括:

1)ansible core

2)连接插件connection plugins:负责和被监控端实现通信;

3)host inventory:管理操作的主机,是一个配置文件里面定义监控的主机;

4)各种模块核心模块、command模块、自定义模块;

5)playbook(yaml文件格式,jinjia2):剧本执行多个任务时,非必需可以让节点一次性运行多个任务。

6)借助于插件完成记录日志邮件等功能;

3、特性

        基于python语言实现,由paramiko,PyYAML和Jinjia2三个关键模块

(1)、no agents:不需要在被管控主机上安装任何客户端;   

(2)、no server:无服务器端,使用时直接运行命令即可;

(3)、modules in any languages:基于模块工作,可使用任意语言开发模块;

(4)、yaml,not code:使用yaml语言定制剧本playbook;

(5)、ssh by default:基于SSH工作;

         1) 基于密钥认证

         2)在inventory文件中指定帐号和密码

(6)、strong multi-tier solution:可实现多级指挥。

4、优点
(1)、轻量级,部署简单,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
(2)、批量任务执行可以写成脚本,而且不用分发到远程就可以执行;
(3)、使用python编写,维护更简单,ruby语法过于复杂;
(4)、支持sudo。

二、ansible安装

[root@localhost ~]# yum list|grep ansible
ansible.noarch                              1.9.4-1.el6                  epel   
ansible-inventory-grapher.noarch            1.0.1-2.el6                  epel   
ansible-lint.noarch                         2.0.1-1.el6                  epel   
[root@localhost ~]# yum list|grep ansible
ansible.noarch                              1.9.4-1.el6                  epel   
ansible-inventory-grapher.noarch            1.0.1-2.el6                  epel   
ansible-lint.noarch                         2.0.1-1.el6                  epel   
[root@localhost ~]# yum install ansible -y

[root@localhost ~]# rpm -ql ansible|less
/etc/ansible
/etc/ansible/ansible.cfg       #主配置文件
/etc/ansible/hosts             #管理的主机,inventory文件
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-doc
/usr/bin/ansible-galaxy
/usr/bin/ansible-playbook
/usr/bin/ansible-pull
/usr/bin/ansible-vault
/usr/lib/python2.6/site-packages/ansible

三、ansible配置

1、/etc/ansible/hosts文件

[root@localhost ~]# cd /etc/ansible/
[root@localhost ansible]# ls
ansible.cfg  hosts  roles
[root@localhost ansible]# cat hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.

green.example.com     
blue.example.com
192.168.100.1
192.168.100.10       #可以使用主机名和ip地址单独列在这里

# Ex 2: A collection of hosts belonging to the 'webservers' group

[webservers]         #可以将多个主机定义组
alpha.example.org
beta.example.org
192.168.1.100
192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

www[001:006].example.com  #某种风格主机名的集合(从www001.example.com -->www006.example.com 6个主机)

# Ex 3: A collection of database servers in the 'dbservers' group

[dbservers]

db01.intranet.mydomain.net
db02.intranet.mydomain.net
10.25.1.56
10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

db-[99:101]-node.example.com

[root@localhost ansible]#
[root@localhost ansible]# cat hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups
10.0.250.203

四、ansible命令使用

1、查看模块帮助

[root@localhost ansible]# ansible-doc -h
Usage: ansible-doc [options] [module...]

Show Ansible module documentation

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -M MODULE_PATH, --module-path=MODULE_PATH
                        Ansible modules/ directory
  -l, --list            List available modules
  -s, --snippet         Show playbook snippet for specified module(s)
  -v                    Show version number and exit

[root@localhost ansible]# ansible-doc -s yum
less 436
Copyright (C) 1984-2009 Mark Nudelman

less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
- name: M a n a g e s   p a c k a g e s   w i t h   t h e   I ( y u m )   p a c k a g 
  action: yum
      conf_file              # The remote yum configuration file to use for the transa
      disable_gpg_check      # Whether to disable the GPG checking of signatures of pa
      disablerepo            # `Repoid' of repositories to disable for the install/upd
      enablerepo             # `Repoid' of repositories to enable for the install/upda
      list                   # Various (non-idempotent) commands for usage with `/usr/
      name=                  # Package name, or package specifier with version, like `
      state                  # Whether to install (`present', `latest'), or remove (`a
      update_cache           # Force updating the cache. Has an effect only if state i

2、使用语法

     ansible <host-pattern> [-f forks] [-m module_name] [-a args]

host-patten:对哪些主机生效

-f forks:启动的并发线程数

-m module_name:要使用的模块

-a args:模块特有的参数

3、ansible常用模块

 1)command  命令模块

默认模块,用于在远程执行命令

[root@localhost ansible]# ansible 10.0.250.203 -m command -a "date"
10.0.250.203 | success | rc=0 >>
Mon Jan 18 15:33:22 CST 2016

[root@localhost ~]# ansible all -m command  -a "hostname  -I"
10.0.250.203 | success | rc=0 >>
10.0.250.203 10.0.17.203 

[root@localhost ~]# ansible all  -a "hostname  -I"
10.0.250.203 | success | rc=0 >>
10.0.250.203 10.0.17.203

 2)cron    计划任务

[root@localhost ~]# ansible-doc -s cron
less 436
Copyright (C) 1984-2009 Mark Nudelman

less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
- name: M a n a g e   c r o n . d   a n d   c r o n t a b   e n t r i e s .
  action: cron
      backup                 # If set, create a backup of the crontab before it is mod
      cron_file              # If specified, uses this file in cron.d instead of an in
      day                    # Day of the month the job should run ( 1-31, *, */2, etc
      hour                   # Hour when the job should run ( 0-23, *, */2, etc )
      job                    # The command to execute. Required if state=present.
      minute                 # Minute when the job should run ( 0-59, *, */2, etc )
      month                  # Month of the year the job should run ( 1-12, *, */2, et
      name=                  # Description of a crontab entry.
      reboot                 # If the job should be run at reboot. This option is depr
      special_time           # Special time specification nickname.
      state                  # Whether to ensure the job is present or absent.  #安装或移除,默认安装咯
      user                   # The specific user whose crontab should be modified.
      weekday                # Day of the week that the job should run ( 0-6 for Sunda
(END)
[root@localhost ~]# ansible 10.0.250.203 -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job of xj"'
10.0.250.203 | success >> {
    "changed": true, 
    "jobs": [
        "test cron job of xj"
    ]
}

[root@localhost ~]# ansible 10.0.250.203 -a crontab -l
Usage: ansible <host-pattern> [options]

ansible: error: -l option requires an argument
[root@localhost ~]# ansible 10.0.250.203 -a 'crontab -l'
10.0.250.203 | success | rc=0 >>
#Ansible: test cron job of xj
*/10 * * * * /bin/echo hello

[root@localhost ~]# ansible 10.0.250.203 -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job of xj" stat=absent'    #移除这个计划任务
10.0.250.203 | FAILED >> {
    "failed": true, 
    "msg": "unsupported parameter for module: stat"
}

[root@localhost ~]# ansible 10.0.250.203 -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job of xj" state=absent'
10.0.250.203 | success >> {
    "changed": true, 
    "jobs": []
}

[root@localhost ~]# ansible 10.0.250.203 -a 'crontab -l'
10.0.250.203 | success | rc=0 >>

 3)user,group  用户,组管理

[root@localhost ~]# ansible 10.0.250.203 -m user -a 'name=test_user'
10.0.250.203 | success >> {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 502, 
    "home": "/home/test_user", 
    "name": "test_user", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 502
}

[root@localhost ~]# ansible 10.0.250.203 -m group -a 'name=mysql gid=306 system=yes'
10.0.250.203 | success >> {
    "changed": true, 
    "gid": 306, 
    "name": "mysql", 
    "state": "present", 
    "system": true
}

4)copy:复制或新建文件

  src=:    定义本地源文件路径可以是相对路径和绝对路径

  dest=:定义远程目标文件路径  只能是绝对路径

  content=:  表示用此处指定的信息生成为目标文件内容

[root@localhost ~]# ansible 10.0.250.203 -m copy -a 'src=/root/2.txt dest=/root/ owner=root mode=700'
10.0.250.203 | success >> {
    "changed": true, 
    "checksum": "e6557cb6b40ebfaee2ddf852ed3c7f8869b4712d", 
    "dest": "/root/2.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "5f15c5e50e91c6e2c0802190c035b6b9", 
    "mode": "0644", 
    "owner": "root", 
    "size": 35, 
    "src": "/root/.ansible/tmp/ansible-tmp-1453169880.17-103219989843490/source", 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible 10.0.250.203 -m copy -a 'content="hello Ansible\nHi\n" dest=/root/ansible'
10.0.250.203 | success >> {
    "changed": true, 
    "checksum": "08ef7f51f158685122f1c0fae57e06c6f6718176", 
    "dest": "/root/ansible", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "9d7ad9f4525d96f893802ea111d7153f", 
    "mode": "0644", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1453170642.32-25113965932022/source", 
    "state": "file", 
    "uid": 0
}

5)file  设置文件属性

[root@localhost ~]# ansible 10.0.250.203 -m file -a 'owner=anyfish mode=700 path=/root/2.txt'
10.0.250.203 | success >> {
    "changed": true, 
    "gid": 501, 
    "group": "user1", 
    "mode": "0700", 
    "owner": "anyfish", 
    "path": "/root/2.txt", 
    "size": 35, 
    "state": "file", 
    "uid": 500
}

[root@localhost ~]# ansible 10.0.250.203 -m file -a 'path=/root/2.txt.link src=/root/2.txt state=link'
10.0.250.203 | success >> {
    "changed": true, 
    "dest": "/root/2.txt.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 11, 
    "src": "/root/2.txt", 
    "state": "link", 
    "uid": 0
}

6)ping 测试指定主机是否能连接

[root@localhost ~]# ansible all -m ping
10.0.250.203 | success >> {
    "changed": false, 
    "ping": "pong"
}

7)service 管理服务

enabled=: 是否开机自动启动,取值为true或者false;

name=: 服务名称

state=: 状态,取值有started,stopped,restarted

[root@localhost ~]# ansible all  -a 'chkconfig --list ntpd'
10.0.250.203 | success | rc=0 >>
ntpd           	0:off	1:off	2:on	3:on	4:on	5:on	6:off

[root@localhost ~]# ansible all -m service -a 'enabled=false name=ntpd state=started'
10.0.250.203 | success >> {
    "changed": true, 
    "enabled": false, 
    "name": "ntpd", 
    "state": "started"
}

[root@localhost ~]# ansible all  -a 'chkconfig --list ntpd'
10.0.250.203 | success | rc=0 >>
ntpd           	0:off	1:off	2:off	3:off	4:off	5:off	6:off

[root@localhost ~]# ansible all  -a 'service ntpd status'
10.0.250.203 | success | rc=0 >>
ntpd (pid  2389) is running...

7)shell  在远程主机上运行命令,尤其使用管道,变量等复杂命令

[root@localhost ~]# ansible all -a 'echo 123456|passwd --stdin user1'
10.0.250.203 | success | rc=0 >>
123456|passwd --stdin user1

[root@localhost ~]# ansible all -m shell -a 'echo abc123|passwd --stdin user1'
10.0.250.203 | success | rc=0 >>
Changing password for user user1.
passwd: all authentication tokens updated successfully.

[root@localhost ~]#

8)script 将本地脚本在远程节点上运行

[root@localhost ~]# ansible all -m script -a '/tmp/test.sh'
10.0.250.203 | success >> {
    "changed": true, 
    "rc": 0, 
    "stderr": "", 
    "stdout": ""
}

9)yum 安装程序包

      name=: 指明要安装的程序包,可以带上版本号

      state=: present,latest表示安装,absent表示卸载

[root@localhost ~]# ansible all -m yum -a "name=httpd"
10.0.250.203 | success >> {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [

10)setup: 收集远程主机的facts

                  每个被管理节点在接收并运行管理命令之前,会将自己主机相关信息,如果操作系统版本,IP地址等报告给ansible

[root@localhost ansible]# ansible all -m setup

五、YAML    

1、YAML介绍

    YAML是一个可读性高的用来表达资料序列的格式。YAML参考了其他多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822等。Clark Evans在2001年在首次发表了这种语言,另外Ingy dt Net与Oren Ben-Kiki也是这语言的共同设计者。

YAML Ain't Markup Language,即YAML不是XML。不过,在开发的这种语言时,YAML的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。

其特性:

YAML的可读性好

YAML和脚本语言的交互性好

YAML使用实现语言的数据类型

YAML有一个一致的信息模型

YAML易于实现

YAML可以基于流来处理

YAML表达能力强,扩展性好


更多的内容及规范参见http://www.yaml.org。


2、YAML语法

       YAML的语法和其他高阶语言类似,并且可以简单表达清单、散列表、标量等数据结构

其结构(Structure)通过空格来展示,序列(Sequence)(同一类数据)里的项用"-"来代表,Map里的键值对用":"分隔。下面是一个示例。

name: John Smith
age: 41
gender: Male
spouse:
    name: Jane Smith
    age: 37
    gender: Female
children:
    -   name: Jimmy Smith
        age: 17
        gender: Male
    -   name: Jenny Smith
        age 13
        gender: Female

YAML文件扩展名通常为.yaml,如example.yaml。


1)list

列表的所有元素均使用“-”打头,例如:

# A list of tasty fruits

- Apple

- Orange

- Strawberry

- Mango


2)dictionary

字典通过key与valuef进行标识,例如:

---

# An employee record

name: Example Developer

job: Developer

skill: Elite


也可以将key:value放置于{}中进行表示,例如:

---

# An employee record

{name: Example Developer, job: Developer, skill: Elite}

六、Ansible中使用的YAMY基础元素

1、变量

 1)变量命名

变量名仅能由字母、数字和下划线组成,且只能以字母开头。

 2)facts

     facts是由正在通信的远程目标主机发回的信息,这些信息被保存在ansible变量中。要获取指定的远程主机所支持的所有facts,可使用如下命令进行:

# ansible hostname -m setup

3)register   #注册器

   把任务的输出定义为变量,然后用于其他任务,示例如下:

 tasks:

     - shell: /usr/bin/foo

       register: foo_result

       ignore_errors: True


4)通过命令行传递变量

在运行playbook的时候也可以传递一些变量供playbook使用,示例如下:


ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"


5)通过roles传递变量

当给一个主机应用角色的时候可以传递变量,然后在角色内使用这些变量,示例如下:


- hosts: webservers

 roles:

   - common

   - { role: foo_app_instance, dir: '/web/htdocs/a.com',  port: 8080 }


2、Inventory

      ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名。默认的inventory file为/etc/ansible/hosts。

inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成。


1)inventory文件格式

      inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中;此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明。


ntp.magedu.com


[webservers]

www1.magedu.com:2222

www2.magedu.com


[dbservers]

db1.magedu.com

db2.magedu.com

     db3.magedu.com


如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机,例如:


[webservers]

www[01:50].example.com


[databases]

db-[a:f].example.com


2)主机变量

可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用。例如:


[webservers]

www1.magedu.com http_port=80 maxRequestsPerChild=808

www2.magedu.com http_port=8080 maxRequestsPerChild=909


3)组变量

组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。例如:


[webservers]

www1.magedu.com

www2.magedu.com


[webservers:vars]

ntp_server=ntp.magedu.com

nfs_server=nfs.magedu.com


4)组嵌套


inventory中,组还可以包含其它的组,并且也可以向组中的主机指定变量。不过,这些变量只能在ansible-playbook中使用,而ansible不支持。例如:


[apache]

httpd1.magedu.com

httpd2.magedu.com


[nginx]

ngx1.magedu.com

ngx2.magedu.com


[webservers:children]      #表示webservers调用了其它组,

apache

nginx


[webservers:vars]

ntp_server=ntp.magedu.com


5)inventory参数

    ansible基于ssh连接inventory中指定的远程主机时,还可以通过参数指定其交互方式;这些参数如下所示:


ansible_ssh_host

  The name of the host to connect to, if different from the alias you wish to give to it.

ansible_ssh_port

  The ssh port number, if not 22

ansible_ssh_user

  The default ssh user name to use.

ansible_ssh_pass

  The ssh password to use (this is insecure, we strongly recommend using --ask-pass or SSH keys)

ansible_sudo_pass

  The sudo password to use (this is insecure, we strongly recommend using --ask-sudo-pass)

ansible_connection

  Connection type of the host. Candidates are local, ssh or paramiko.  The default is paramiko before Ansible 1.2, and 'smart' afterwards which detects whether usage of 'ssh' would be feasible based on whether ControlPersist is supported.

ansible_ssh_private_key_file

  Private key file used by ssh.  Useful if using multiple keys and you don't want to use SSH agent.

ansible_shell_type

  The shell type of the target system. By default commands are formatted using 'sh'-style syntax by default. Setting this to 'csh' or 'fish' will cause commands executed on target systems to follow those shell's syntax instead.

ansible_python_interpreter

  The target host python path. This is useful for systems with more

  than one Python or not located at "/usr/bin/python" such as \*BSD, or where /usr/bin/python

  is not a 2.X series Python.  We do not use the "/usr/bin/env" mechanism as that requires the remote user's

  path to be set right and also assumes the "python" executable is named python, where the executable might

  be named something like "python26".

ansible\_\*\_interpreter

  Works for anything such as ruby or perl and works just like ansible_python_interpreter.

  This replaces shebang of modules which will run on that host.


5.3 条件测试


如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试。


5.3.1 when语句


在task后添加when子句即可使用条件测试;when语句支持Jinja2表达式语法。例如:


tasks:

  - name: "shutdown Debian flavored systems"

    command: /sbin/shutdown -h now

    when: ansible_os_family == "Debian"


when语句中还可以使用Jinja2的大多“filter”,例如要忽略此前某语句的错误并基于其结果(failed或者sucess)运行后面指定的语句,可使用类似如下形式:


tasks:

  - command: /bin/false

    register: result

    ignore_errors: True

  - command: /bin/something

    when: result|failed

  - command: /bin/something_else

    when: result|success

  - command: /bin/still/something_else

    when: result|skipped


此外,when语句中还可以使用facts或playbook中定义的变量。


5.4 迭代


当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可。例如:


- name: add several users

  user: name={{ item }} state=present groups=wheel

  with_items:

     - testuser1

     - testuser2


上面语句的功能等同于下面的语句:


- name: add user testuser1

  user: name=testuser1 state=present groups=wheel

- name: add user testuser2

  user: name=testuser2 state=present groups=wheel


事实上,with_items中可以使用元素还可为hashes,例如:


- name: add several users

  user: name={{ item.name }} state=present groups={{ item.groups }}

  with_items:

    - { name: 'testuser1', groups: 'wheel' }

    - { name: 'testuser2', groups: 'root' }


ansible的循环机制还有更多的高级功能,具体请参见官方文档(http://docs.ansible.com/playbooks_loops.html)。

七、ansible playbooks

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

- hosts: webnodes
  vars:                 #定义变量
    http_port: 80
    max_clients: 256
  remote_user: root
  tasks:
- name: ensure apache is at the latest version
    yum: name=httpd state=latest
- name: ensure apache is running
    service: name=httpd state=started
  handlers:
- name: restart apache
      service: name=httpd state=restarted


7.1 playbook基础组件


7.1.1 Hosts和Users

playbook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。hosts用于指定要执行指定任务的主机,其可以是一个或多个由冒号分隔主机组;remote_user则用于指定远程主机上的执行任务的用户。如上面示例中的

-hosts: webnodes

remote_user: root


不过,remote_user也可用于各task中。也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户。


- hosts: webnodes

 remote_user: mageedu

 tasks:

   - name: test connection

     ping:

     remote_user: mageedu

     sudo: yes


7.1.2 任务列表和action


play的主体部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。在运行自上而下某playbook时,如果中途发生错误,所有已执行任务都可能回滚,因此,在更正playbook后重新执行一次即可。


task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的,这意味着多次执行是安全的,因为其结果均一致。


每个task都应该有其name,用于playbook的执行结果输出,建议其内容尽可能清晰地描述任务执行步骤。如果未提供name,则action的结果将用于输出。


定义task的可以使用“action: module options”或“module: options”的格式,推荐使用后者以实现向后兼容。如果action一行的内容过多,也中使用在行首使用几个空白字符进行换行。

tasks:

 - name: make sure apache is running

   service: name=httpd state=running


在众多模块中,只有command和shell模块仅需要给定一个列表而无需使用“key=value”格式,例如:

tasks:

 - name: disable selinux

   command: /sbin/setenforce 0


如果命令或脚本的退出码不为零,可以使用如下方式替代:

tasks:

 - name: run this command and ignore the result

   shell: /usr/bin/somecommand || /bin/true


或者使用ignore_errors来忽略错误信息:

tasks:

 - name: run this command and ignore the result

   shell: /usr/bin/somecommand

   ignore_errors: True


7.1.3 handlers

用于当关注的资源发生变化时采取一定的操作。


“notify”这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行指定的操作,取而代之,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作。

- name: template configuration file

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

 notify:

    - restart memcached

    - restart apache


handler是task列表,这些task与前述的task并没有本质上的不同。

handlers:

   - name: restart memcached

     service:  name=memcached state=restarted

   - name: restart apache

     service: name=apache state=restarted


案例:

heartbeat.yaml

- hosts: hbhosts

 remote_user: root

 tasks:

   - name: ensure heartbeat latest version

     yum: name=heartbeat state=present

   - name: authkeys configure file

     copy: src=/root/hb_conf/authkeys dest=/etc/ha.d/authkeys

   - name: authkeys mode 600

     file: path=/etc/ha.d/authkeys mode=600

     notify:

       - restart heartbeat

   - name: ha.cf configure file

     copy: src=/root/hb_conf/ha.cf dest=/etc/ha.d/ha.cf

     notify: 

      - restart heartbeat

 handlers:

  - name: restart heartbeat

   service: name=heartbeat state=restarted









5、任务执行流程

wKiom1Rsx2uQYJZ5AAJplY08vOQ976.jpg



你可能感兴趣的:(ansible)