设为首页 收藏本站
查看: 4203|回复: 0

[经验分享] ansible工作原理以及使用详解

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-11-2 09:16:19 | 显示全部楼层 |阅读模式
内容:
1、ansible的作用以及工作结构
2、ansible的安装以及使用
3、ansible的playbook使用


一、ansible的作用以及工作结构
        1、ansible简介:
        ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。主要包括:
        (1)、连接插件connection plugins:负责和被监控端实现通信;
        (2)、host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;
        (3)、各种模块核心模块、command模块、自定义模块;
        (4)、借助于插件完成记录日志邮件等功能;
        (5)、playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务。

        2、ansible的架构:连接其他主机默认使用ssh协议
wKioL1gYRHGQAKgfAALF9HoQE_M831.jpg
二、ansible的安装以及常用模块使用
        1、ansible无服务器端,使用时直接运行命令即可,同时不需要在被管控主机上安装任何客户端,因此ansible是一个十分轻量级的工具,可以在epel源进行安装,ansible已经被红帽收购,相信不久会被收入base源
        配置好epel源后直接yum安装ansible
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[iyunv@php ~]# yum info ansible
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
base                                                                                              | 4.0 kB     00:00 ...
epel                                                                                              | 4.3 kB     00:00     
epel/primary_db                                                                                   | 5.7 MB     00:00     
Available Packages
Name        : ansible
Arch        : noarch
Version     : 1.9.2
Release     : 1.el6
Size        : 1.7 M
Repo        : epel
Summary     : SSH-based configuration management, deployment, and task execution system
URL         : http://ansible.com
License     : GPLv3
Description :
            : Ansible is a radically simple model-driven configuration management,
            : multi-node deployment, and remote task execution system. Ansible works
            : over SSH and does not require any software or daemons to be installed
            : on remote nodes. Extension modules can be written in any language and
            : are transferred to managed machines automatically.
[iyunv@php ~]# yum install ansible




        查看生成的主要文件:
1
2
3
4
5
6
/etc/ansible
/etc/ansible/ansible.cfg   #配置文件
/etc/ansible/hosts   #主机库(host inventory)
/usr/bin/ansible   #主程序
/usr/bin/ansible-doc   #文档
/usr/bin/ansible-playbook   #剧本




        ansible命令的使用方法也比较简单:
        语法:
        ansible <host-pattern> [-f forks] [-m module_name] [-a args]
        host-pattern:host inventory文件的一个组名,可以为all
            -f forks:并行处理的个数,默认为5
            -m module_name:模块名,默认为command
            -a args:参数

        ansible-doc:
            -l:查看模块列表
            -s:查看相关模块参数

        我们可以看到ansible支持非常多的模块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[21:20 root@centos6.8/var/ftp/pub/files]# ansible-doc -l
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
a10_server                    Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                 
a10_service_group             Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                 
a10_virtual_server            Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                                 
acl                           Sets and retrieves file ACL information.                                               
add_host                      add a host (and alternatively a group) to the ansible-playbook in-memory inventory     
airbrake_deployment           Notify airbrake about app deployments                                                  
alternatives                  Manages alternative programs for common commands                                       
apache2_module                enables/disables a module of the Apache2 webserver                                    
apt                           Manages apt-packages                                                                  
apt_key                       Add or remove an apt key                                                               
apt_repository                Add and remove APT repositories                                                        
apt_rpm                       apt_rpm package manager                                                               
assemble                      Assembles a configuration file from fragments                                          
assert                        Fail with custom message                                                               
at                            Schedule the execution of a command or script file via the at command.                 
authorized_key                Adds or removes an SSH authorized key                                                  
azure                         create or terminate a virtual machine in azure                                         
bigip_facts                   Collect facts from F5 BIG-IP devices                                                   
bigip_monitor_http            Manages F5 BIG-IP LTM http monitors                                                   
bigip_monitor_tcp             Manages F5 BIG-IP LTM tcp monitors                                                     
bigip_node                    Manages F5 BIG-IP LTM nodes                                                            
bigip_pool                    Manages F5 BIG-IP LTM pools                                                            
bigip_pool_member             Manages F5 BIG-IP LTM pool members                                                     
bigpanda                      Notify BigPanda about deployments                                                      
boundary_meter                Manage boundary meters





            注意:使用ansible-doc -s查看帮助是,一般有=号的参数都是必要的参数
        Ansible默认安装好后有一个配置文件/etc/ansible/ansible.cfg,该配置文件中定义了ansible的主机的默认配置部分,如默认是否需要输入密码、是否开启sudo认证、action_plugins插件的位置、hosts主机组的位置、是否开启log功能、默认端口、key文件位置等等。
        具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[defaults]
    # some basic default values...
    hostfile       = /etc/ansible/hosts   \\指定默认hosts配置的位置
    # library_path = /usr/share/my_modules/
    remote_tmp     = $HOME/.ansible/tmp
    pattern        = *
    forks          = 5
    poll_interval  = 15
    sudo_user      = root  \\远程sudo用户
    #ask_sudo_pass = True  \\每次执行ansible命令是否询问ssh密码
    #ask_pass      = True  \\每次执行ansible命令时是否询问sudo密码
    transport      = smart
    remote_port    = 22
    module_lang    = C
    gathering = implicit
    host_key_checking = False    \\关闭第一次使用ansible连接客户端是输入命令提示
    log_path    = /var/log/ansible.log \\需要时可以自行添加。chown -R root:root ansible.log
    system_warnings = False    \\关闭运行ansible时系统的提示信息,一般为提示升级
    # set plugin path directories here, separate with colons
    action_plugins     = /usr/share/ansible_plugins/action_plugins
    callback_plugins   = /usr/share/ansible_plugins/callback_plugins
    connection_plugins = /usr/share/ansible_plugins/connection_plugins
    lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
    vars_plugins       = /usr/share/ansible_plugins/vars_plugins
    filter_plugins     = /usr/share/ansible_plugins/filter_plugins
    fact_caching = memory
    [accelerate]
    accelerate_port = 5099
    accelerate_timeout = 30
    accelerate_connect_timeout = 5.0
    # The daemon timeout is measured in minutes. This time is measured
    # from the last activity to the accelerate daemon.
    accelerate_daemon_timeout = 30




        下面对一些常用的模块来进行演示说明:
        首先现在测试环境:四台主机,一台作为ansible的控制主机,另外三台作为被管理的机器节点
        1、ansible的连接:
通过前面的介绍我们知道,ansible是基于ssh协议来进行数据传输,ssh连接一般有两种方法,一种是使用密码密钥,一种是使用公私密码免密码登录,为了顺利使用ansible,下面配置基于公私密码免密码登录
        (1)生成密钥对
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[iyunv@localhost ~]# ssh-keygen  -t rsa #-t表示使用的加密类型,其中rsa1表示version1版本,rsa、dsa、ecdsa的加密对于的是version2版本
Generating public/private rsa key pair.
#这里询问你要把生成的密钥文件保存在哪里,默认是在家目录下的.ssh文件夹中,回车保存默认目录
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
#这里是对密钥文件加密,不输入则表示不加密
Enter passphrase (empty for no passphrase):
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
04:9f:cb:9c:9d:1e:47:d7:e1:d4:c1:87:71:c3:a4:22 root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
|      .       =O+|
|       o .    ===|
|        +E .....o|
|       + +.o..   |
|        S + .    |
|         . o     |
|          .      |
|                 |
|                 |
+-----------------+



        (2)查看已经成功生成了一对密钥
1
2
[iyunv@localhost ~]# ls /root/.ssh
id_rsa  id_rsa.pub#其中id_rsa为私钥,id_rsa.pub为公钥



        (3)在生成完密钥对之后将公钥上传给服务器对应用户的家目录
1
2
3
[iyunv@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@10.1.249.30
[iyunv@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@10.1.252.36
[iyunv@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@10.1.253.107



        已经配置好无需密码登录了,下面进行ansible的配置
        2、配置ansible需要控制的主机列表,其配置在hosts文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[21:50 root@centos6.8/etc/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.
[test]
10.1.252.36
10.1.249.30
10.1.253.107




        [test]表示控制的组名可以根据实际进行定义,下面添加主机列表
        3、命令模块:
        这也是默认的模块,也就是不加-m指定模块时默认的模块,这个模块不能使用包含管道的命令。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[21:51 root@centos6.8/etc/ansible]# ansible-doc -s command
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: E x e c u t e s   a   c o m m a n d   o n   a   r e m o t e   n o d e
  action: command
      chdir                  # cd into this directory before running the command
      creates                # a filename, when it already exists, this step will *not* be run.
      executable             # change the shell used to execute the command. Should be an absolute path to the executable
      free_form=             # the command module takes a free form command to run.  There is no parameter actually named
      removes                # a filename, when it does not exist, this step will *not* be run.
      warn                   # if command warnings are on in ansible.cfg, do not warn about this particular line if set t
(END)





演示:
1
2
3
4
5
6
7
[21:56 root@centos6.8/etc/ansible]# ansible test -a 'date'
10.1.252.36 | success | rc=0 >>
Sat Oct 29 19:09:18 CST 2016
10.1.253.107 | success | rc=0 >>
Tue Oct 25 07:27:02 CST 2016
10.1.249.30 | success | rc=0 >>
Sun Oct 30 03:09:17 CST 2016



        4、shell模块:
        shell模块也是可以执行命令,与comman模块不同的时,command模块不能执行包含管道的命令,而shell可以
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[21:56 root@centos6.8/etc/ansible]# ansible-doc -s shell
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: E x e c u t e   c o m m a n d s   i n   n o d e s .
  action: shell
      chdir                  # cd into this directory before running the command
      creates                # a filename, when it already exists, this step will *not* be run.
      executable             # change the shell used to execute the command. Should be an absolute path to the executable
      free_form=             # The shell module takes a free form command to run, as a string.  There's not an actual opt
      removes                # a filename, when it does not exist, this step will *not* be run.
      warn                   # if command warnings are on in ansible.cfg, do not warn about this particular line if set t




        演示:
1
2
3
4
[21:58 root@centos6.8/etc/ansible]# ansible test -m shell -a 'echo 111 > /tmp/test.txt'
10.1.252.36 | success | rc=0 >>
10.1.253.107 | success | rc=0 >>
10.1.249.30 | success | rc=0 >>




        客户端查看已经生成文件
1
2
[iyunv@localhost ~]# cat /tmp/test.txt
111



        5、copy模块:可以把本机的文件拷贝至被管理的机器,通常用于分发配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[21:59 root@centos6.8/etc/ansible]# ansibl-doc -s copy
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: C o p i e s   f i l e s   t o   r e m o t e   l o c a t i o n s .
  action: copy
      backup                 # Create a backup file including the timestamp information so you can get the original file
      content                # When used instead of 'src', sets the contents of a file directly to the specified value.
      dest=                  # Remote absolute path where the file should be copied to. If src is a directory, this must
      directory_mode         # When doing a recursive copy set the mode for the directories. If this is not set we will u
      follow                 # This flag indicates that filesystem links, if they exist, should be followed.
      force                  # the default is `yes', which will replace the remote file when contents are different than
      group                  # name of the group that should own the file/directory, as would be fed to `chown'
      mode                   # mode the file or directory should be, such as 0644 as would be fed to `chmod'. As of versi
      owner                  # name of the user that should own the file/directory, as would be fed to `chown'
      selevel                # level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as
      serole                 # role part of SELinux file context, `_default' feature works as for `seuser'.
      setype                 # type part of SELinux file context, `_default' feature works as for `seuser'.
      seuser                 # user part of SELinux file context. Will default to system policy, if applicable. If set to
      src                    # Local path to a file to copy to the remote server; can be absolute or relative. If path is
      validate               # The validation command to run before copying into place.  The path to the file to validate
(END)




    演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[22:01 root@centos6.8/etc/ansible]# ansible test -m copy -a 'src=/etc/issue dest=/tmp/issu.txt mode=600'
10.1.252.36 | success >> {
    "changed": true,
    "checksum": "03801eaa2804f96b025d70a7790079068275410a",
    "dest": "/tmp/issu.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "145f4a07c5bf60603fbf3f14990b38d7",
    "mode": "0600",
    "owner": "root",
    "size": 47,
    "src": "/root/.ansible/tmp/ansible-tmp-1477576950.16-258334820967730/source",
    "state": "file",
    "uid": 0
}
10.1.253.107 | success >> {
    "changed": true,
    "checksum": "03801eaa2804f96b025d70a7790079068275410a",
    "dest": "/tmp/issu.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "145f4a07c5bf60603fbf3f14990b38d7",
    "mode": "0600",
    "owner": "root",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 47,
    "src": "/root/.ansible/tmp/ansible-tmp-1477576950.6-253946087850559/source",
    "state": "file",
    "uid": 0
}
10.1.249.30 | success >> {
    "changed": true,
    "checksum": "03801eaa2804f96b025d70a7790079068275410a",
    "dest": "/tmp/issu.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "145f4a07c5bf60603fbf3f14990b38d7",
    "mode": "0600",
    "owner": "root",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 47,
    "src": "/root/.ansible/tmp/ansible-tmp-1477576950.99-245450559825172/source",
    "state": "file",
    "uid": 0
}



    客户端查看测试成功
1
2
3
4
5
6
7
[22:04 root@centos6.8/etc/ansible]# ansible test a 'ls /tmp/issu.txt''
10.1.252.36 | success | rc=0 >>
/tmp/issu.txt
10.1.249.30 | success | rc=0 >>
/tmp/issu.txt
10.1.253.107 | success | rc=0 >>
/tmp/issu.txt




        6、cron模块:分发定期任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[22:04 root@centos6.8/etc/ansible]# 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 modified. The location of the backup i
      cron_file              # If specified, uses this file in cron.d instead of an individual user's crontab.
      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, etc )
      name=                  # Description of a crontab entry.
      reboot                 # If the job should be run at reboot. This option is deprecated. Users should use special_ti
      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 Sunday-Saturday, *, etc )
(END)



        演示:每5分钟同步ntp服务器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[22:11 root@centos6.8/etc/ansible]# ansible test -m cron -a 'name="test" minute=*/5 hour=* day=*  month=* weekday=* job="usr/sbin/ntpdate 10.1.0.1"'
10.1.249.30 | success >> {
    "changed": true,
    "jobs": [
        "test"
    ]
}
10.1.252.36 | success >> {
    "changed": true,
    "jobs": [
        "test"
    ]
}
10.1.253.107 | success >> {
    "changed": true,
    "jobs": [
        "test"
    ]
}



        查看客户端已经成功添加计划任务
1
2
3
4
5
6
7
8
9
10
[22:12 root@centos6.8/etc/ansible]# ansible test -a 'crontab -l'
10.1.253.107 | success | rc=0 >>
#Ansible: test
*/5 * * * * /usr/sbin/ntpdate 10.1.0.1
10.1.252.36 | success | rc=0 >>
#Ansible: test
*/5 * * * * /usr/sbin/ntpdate 10.1.0.1
10.1.249.30 | success | rc=0 >>
#Ansible: test
*/5 * * * * /usr/sbin/ntpdate 10.1.0.1



        7、yum模块:顾名思义,该模块可以管理软件的安装和卸载,state=present(安装) adsent(卸载)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[22:13 root@centos6.8/etc/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 e   m a n a g e r
  action: yum
      conf_file              # The remote yum configuration file to use for the transaction.
      disable_gpg_check      # Whether to disable the GPG checking of signatures of packages being installed. Has an effe
      disablerepo            # `Repoid' of repositories to disable for the install/update operation. These repos will not
      enablerepo             # `Repoid' of repositories to enable for the install/update operation. These repos will not
      list                   # Various (non-idempotent) commands for usage with `/usr/bin/ansible' and `not' playbooks. S
      name=                  # Package name, or package specifier with version, like `name-1.0'. When using state=latest,
      state                  # Whether to install (`present', `latest'), or remove (`absent') a package.
      update_cache           # Force updating the cache. Has an effect only if state is `present' or `latest'.
(END)



        演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[22:15 root@centos6.8/etc/ansible]# ansible test -m yum -a 'name=tree state=present'
10.1.253.107 | success >> {
    "changed": false,
    "msg": "",
    "rc": 0,
    "results": [
        "tree-1.6.0-10.el7.x86_64 providing tree is already installed"
    ]
}
10.1.249.30 | success >> {
    "changed": false,
    "msg": "",
    "rc": 0,
    "results": [
        "tree-1.5.3-3.el6.x86_64 providing tree is already installed"
    ]
}
10.1.252.36 | success >> {
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror, security\nSetting up Install Process\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package tree.x86_64 0:1.5.3-3.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n tree            x86_64            1.5.3-3.el6            base             36 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 36 k\nInstalled size: 65 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : tree-1.5.3-3.el6.x86_64                                      1/1 \n\r  Verifying  : tree-1.5.3-3.el6.x86_64                                      1/1 \n\nInstalled:\n  tree.x86_64 0:1.5.3-3.el6                                                     \n\nComplete!\n"
    ]
}



        测试安装成功
1
2
3
4
5
6
7
[22:16 root@centos6.8/etc/ansible]#ansible test -a 'rpm -q tree'
10.1.252.36 | success | rc=0 >>
tree-1.5.3-3.el6.x86_64
10.1.253.107 | success | rc=0 >>
tree-1.6.0-10.el7.x86_64
10.1.249.30 | success | rc=0 >>
tree-1.5.3-3.el6.x86_64




        8、service模块
        state=
            started
            stopped
            restarted
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[22:17 root@centos6.8/etc/ansible]# ansible-doc -s service
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 e r v i c e s .
  action: service
      arguments              # Additional arguments provided on the command line
      enabled                # Whether the service should start on boot. *At least one of state and enabled are required.
      name=                  # Name of the service.
      pattern                # If the service does not respond to the status command, name a substring to look for as wou
      runlevel               # For OpenRC init scripts (ex: Gentoo) only.  The runlevel that this service belongs to.
      sleep                  # If the service is being `restarted' then sleep this many seconds between the stop and star
      state                  # `started'/`stopped' are idempotent actions that will not run commands unless necessary.  `
(END)




    演示:
        现在的web服务是停止的,我们来重启
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[22:22 root@centos6.8/etc/ansible]# ansible test -m service -a 'name=httpd state=started'
10.1.249.30 | success >> {
    "changed": true,
    "name": "httpd",
    "state": "started"
}
10.1.252.36 | success >> {
    "changed": true,
    "name": "httpd",
    "state": "started"
}
10.1.253.107 | success >> {
    "changed": true,
    "name": "httpd",
    "state": "started"
}



        查看已经启动成功
1
2
3
4
5
6
7
[22:22 root@centos6.8/etc/ansible]# ansible test -m shell  -a 'ss -tnl|grep 80'
10.1.252.36 | success | rc=0 >>
LISTEN     0      128                      :::80                      :::*     
10.1.249.30 | success | rc=0 >>
LISTEN     0      128                      :::80                      :::*     
10.1.253.107 | success | rc=0 >>
LISTEN     0      128         :::80                      :::*





三、ansible的playbook使用
        有上面的演示我们体会到了ansible的强大,但是上面的演示都是一条一条指令的输入,这样未免影响了效率,有没有办法想shell脚本一样一次执行多条语句呢,答案是肯定的,只不过这里不叫shell脚本而叫playbook剧本。
        1.playbook组织格式:YAML语言格式
playbooks是ansible更强大的配置管理组件,实现基于文本文件编排执行的多个任务,且多次重复执行   
        (1)YAML简介
        YAML:YAML Ain't  Markup Language;  Yet Another Markup Language;                  
        类似于半结构化数据,声明式配置;可读性较高的用来表达资料序列的格式,易于与脚本语言交互
        官方站点:http://www.yaml.org
        (2)语法格式
        1)任何书记结构都用缩进来标识,可以嵌套
        2)每一行是一个键值数据key:value,冒号隔开。若想在一行标识需要用{ }和,分隔格式
        3)列表用 – 标识
        (3)Playbook组成结构:
        Tasks:任务,即调用模块完成的操作
        Variables:变量
        Templates:模板
        Handlers:处理器,由某个条件触发执行的操作
        Roles:角色
        基本结构:
            – host:webservices
            remote_user:
                – tasks:
                – task1
            module_name
        YAML文件扩展名通常为.yml,如test.yml。
    2、playbook的使用:
        前面的介绍我们知道了playbook的存储在*.yaml文本中,我们创建一个yaml文件验证下
1
2
3
4
5
6
7
8
[22:40 root@centos6.8/etc/ansible]# cat test.yaml
- hosts: test
  remote_user: root
  tasks:
  - name: user a group
    group: gid=1111 name=test system=no
  - name: show command
    shell: date




        正式使用时我们最好先预运行下看有没有错误
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[22:40 root@centos6.8/etc/ansible]# ansible-playbook  --check test.yaml
PLAY [test] *******************************************************************
GATHERING FACTS ***************************************************************
ok: [10.1.252.36]
ok: [10.1.253.107]
ok: [10.1.249.30]
TASK: [user a group] **********************************************************
changed: [10.1.252.36]
changed: [10.1.249.30]
changed: [10.1.253.107]
TASK: [show command] **********************************************************
skipping: [10.1.252.36]
ok: [10.1.252.36]
skipping: [10.1.249.30]
ok: [10.1.249.30]
skipping: [10.1.253.107]
ok: [10.1.253.107]
PLAY RECAP ********************************************************************
10.1.249.30                : ok=2    changed=1    unreachable=0    failed=0   
10.1.252.36                : ok=2    changed=1    unreachable=0    failed=0   
10.1.253.107               : ok=2    changed=1    unreachable=0    failed=0




        没有问题就可以正式运行命令脚本了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[22:40 root@centos6.8/etc/ansible]# ansible-playbook   test.yaml
PLAY [test] *******************************************************************
GATHERING FACTS ***************************************************************
ok: [10.1.252.36]
ok: [10.1.253.107]
ok: [10.1.249.30]
TASK: [user a group] **********************************************************
changed: [10.1.252.36]
changed: [10.1.253.107]
changed: [10.1.249.30]
TASK: [show command] **********************************************************
changed: [10.1.252.36]
changed: [10.1.249.30]
changed: [10.1.253.107]
PLAY RECAP ********************************************************************
10.1.249.30                : ok=3    changed=2    unreachable=0    failed=0   
10.1.252.36                : ok=3    changed=2    unreachable=0    failed=0   
10.1.253.107               : ok=3    changed=2    unreachable=0    failed=0




        检查测试成功
1
2
3
4
5
6
7
[22:47 root@centos6.8/etc/ansible]# ansible test -a 'tail -1 /etc/group'
10.1.252.36 | success | rc=0 >>
test:x:1111:
10.1.253.107 | success | rc=0 >>
test:x:1111:
10.1.249.30 | success | rc=0 >>
test:x:1111:



        3.playbook-变量
        (1)变量命名:字母、数字和下划线组成,仅能以字母开头;
        (2)变量种类:
        1)facts:由远程主机发回的主机特有的属性信息,这些信息被保存在ansible变量中;无须声明,可直接调用;
        2)自定义变量:
        通过命令行传递:ansible-playbook  test.yml  –extra-vars "host=www user=test"
        通过roles传递
        3)主机变量:定义在inventory中的主机之后的变量;直接传递给单个主机的变量

实例:
        在hosts中直接定义在主机之后
1
2
3
4
5
[iyunv@localhost ~]# vim /etc/ansible/hosts
[web]
192.168.0.101    host=mail
192.168.0.102
192.168.0.103




        4)组变量:定义在inventory中的组上的变量(例如在默认的文件/etc/ansible/hosts上编辑)
1
2
3
[group_name:vars]
var1=value
var2=value




        注意:组名要事先存在,实例如下:
1
2
3
4
5
[websrvs]
192.168.0.101
192.168.0.102
[websrvs:vars]
host=mail




        变量使用示例:
1
2
3
4
5
6
7
8
9
10
11
      [iyunv@localhost~]# vim useradd.yml
–     hosts: websrvs
       remote_user: root
      vars:
username: testuser
password: xuding
        tasks:
-name: add user
   user: name={{ username }} state=present
-name: set password
  shell: /bin/echo {{ password }} |/usr/bin/passwd –stdin {{ username }}




注释:
    1) {{ }} 调用变量
    2) #ansible-playbook /PATH/TO/SOME_YAML_FILE  { -eVARS|–extra-vars=VARS}     
变量的重新赋值调用方法
[iyunv@localhost ~]# ansible-playbookuseradd.yml –extra-vars "username=ubuntu"

        ansible-playbook参考
        (1)基础示例
1
2
3
4
5
6
7
8
~]# vim base.yaml
- hosts: 192.168.1.114
remote_user: root
tasks:
- name: install httpd server
    yum: name=httpd state=present
  - name: start httpd server
    service: name=httpd state=started



        (2)handlers示例
1
2
3
4
5
6
7
8
9
10
11
12
13
~]# vim handlers.yaml
- hosts: 192.168.1.114
remote_user: root
tasks:
- name: install httpd
  yum: name=httpd state=present
- name: install configure file
  copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  notify: restart httpd server
handlers:
- name: restart httpd server  
  service: name=httpd state=restarted
~]# vim file/httpd.conf



        修改Listen 80为Linsten 8080:
1
~]# ansible-playbook --check handlers.yaml



        (3)tags示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
~]# vim tags.yaml
- hosts: 192.168.1.114
remote_user: root
tasks:
- name: install httpd
  yum: name=httpd state=present
- name: install configure file
  copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  tags: instconf
  notify: restart httpd server
handlers:
- name: restart httpd server
  service: name=httpd state=restarted
~]# ansible-playbook tags.yaml -t instconf



        (4)variables示例
1
2
3
4
5
6
7
8
9
10
11
12
13
~]# vim variables.yaml
- hosts: 192.168.1.114
remote_user: root
tasks:
- name: install {{ package }}
  yum: name={{ package }} state=present

~]# ansible-playbook variables.yaml -e package=httpd
c.
~]# vim /etc/ansible/hosts
[websrvs]
192.168.1.114 package=httpd
~]# ansible-playbook variables.yaml






运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-294582-1-1.html 上篇帖子: Ansible安装(ubuntu14.04环境) 下篇帖子: Ansible 一键配置安装Keepalived+Nginx作为前端,httpd+php作为后端 工作原理
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表