天天看点

自动化运维工具ansible详细介绍以模块的使用ansible

ansible

ansible的理论部分

ansible的介绍

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

  ansible是基于 paramiko 开发的,并且基于模块化工作,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。ansible不需要在远程主机上安装client/agents,因为它们是基于ssh来和远

程主机通讯的。ansible目前已经已经被红帽官方收购,是自动化运维工具中大家认可度最高的,并且上手容易,学习简单。是每位运维工程师必须掌握的技能之一。

ansible的特点

  1. 部署简单,只需在主控端部署Ansible环境,被控端无需做任何操作;
  2. 默认使用SSH协议对设备进行管理;
  3. 有大量常规运维操作模块,可实现日常绝大部分操作;
  4. 配置简单、功能强大、扩展性强;
  5. 支持API及自定义模块,可通过Python轻松扩展;
  6. 通过Playbooks来定制强大的配置、状态管理;
  7. 轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
  8. 提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台。

    ansible的架构图

    自动化运维工具ansible详细介绍以模块的使用ansible
    上图中我们看到的主要模块如下:

Ansible:Ansible核心程序。

HostInventory:记录由Ansible管理的主机信息,包括端口、密码、ip等。

Playbooks:“剧本”YAML格式文件,多个任务定义在一个文件中,定义主机需要调用哪些模块来完成的功能。

CoreModules:核心模块,主要操作是通过调用核心模块来完成管理任务。

CustomModules:自定义模块,完成核心模块无法完成的功能,支持多种语言。

ConnectionPlugins:连接插件,Ansible和Host通信使用

ansible 任务执行

ansible 任务执行模式

Ansible 系统由控制主机对被管节点的操作方式可分为两类,即adhoc和playbook:

  • ad-hoc模式(点对点模式)

    使用单个模块,支持批量执行单条命令。ad-hoc 命令是一种可以快速输入的命令,而且不需要保存起来的命令。就相当于bash中的一句话shell。

  • playbook模式(剧本模式)

    是Ansible主要管理方式,也是Ansible功能强大的关键所在。playbook通过多个task集合完成一类功能,如Web服务的安装部署、数据库服务器的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件。

    ansible 执行流程

    自动化运维工具ansible详细介绍以模块的使用ansible
    简单理解就是Ansible在运行时, 首先读取ansible.cfg中的配置, 根据规则获取Inventory中的管理主机列表, 并行的在这些主机中执行配置的任务, 最后等待执行返回的结果。

ansible 命令执行过程

  1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg;
  2. 查找对应的主机配置文件,找到要执行的主机或者组;
  3. 加载自己对应的模块文件,如 command;
  4. 通过ansible将模块或命令生成对应的临时py文件(python脚本), 并将该文件传输至远程服务器;
  5. 对应执行用户的家目录的.ansible/tmp/XXX/XXX.PY文件;
  6. 给文件 +x 执行权限;
  7. 执行并返回结果;
  8. 删除临时py文件,sleep 0退出;

ansible安装

实验说明

服务角色 IP 系统及所需软件
主控主机 192.168.24.128 centos7  ansible
受控主机 192.168.24.130 centos7

安装yum源

[root@linfan ~]# cd /etc/yum.repos.d/ 
root@linfan yum.repos.d]# curl -o 163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@linfan yum.repos.d]# sed -i 's/\$releasever/7/g' 163.repo
[root@linfan yum.repos.d]# sed -i 's/^enabled=.*/enabled=1/g' 163.repo
[root@linfan yum.repos.d]#  yum -y install epel-release            

安装ansible

[root@linfan yum.repos.d]# yum -y install ansible ansible-doc            

查看ansible的版本

[root@linfan ~]# ansible --version
ansible 2.6.3
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]           

ansible配置

ansible配置文件:

配置文件 说明
/etc/ansible/ansible.cfg ansible主配置文件
/etc/ansible/hosts 受控主机清单

受控主机清单配置方式:

  • 分组配置
  • ip配置
  • 域名配置
  • 通配符配置

    ansible通过ssh来控制远程主机,所以要配置ssh互信,否则将会提示你输入密码

[root@linfan ~]#  ssh-keygen -t rsa //使用ssh-keygen 创建公钥-私钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
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:
SHA256:4gPocSR66cSXzSqpFIw+2MA8xbnpdtwWdCeDomGlTJo root@linfan
The key's randomart image is:
+---[RSA 2048]----+
|   . .           |
|  * +   .        |
| E.O.. o + .     |
|=oo==+o . +      |
|+*B+= +.S        |
|oB+=.+...        |
|.+*o.ooo         |
|..o.. ..         |
|.                |
+----[SHA256]-----+
[root@linfan ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
//使用 ssh-copy-id 将公钥复制到受控上的正确位置
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.24.130 (192.168.24.130)' can't be established.
ECDSA key fingerprint is SHA256:w+sgREnQRuhBiqS0qL9wlAImCSmvSQ6KnNqW6N3znJ0.
ECDSA key fingerprint is MD5:f0:fd:ea:c7:97:83:f0:b0:03:84:d2:a6:0a:23:12:e0.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
           

将受控主机信息加入清单配置文件中

[root@linfan ~]# vim /etc/ansible/hosts
//添加以下内容
[webservers] //组名
192.168.24.130 //受控主机IP           

ansible使用

ansible webservers组名或受控主机IP -m 模块名 -a ‘命令’           

ansible获取帮助信息

ansible通过ansible-doc命令来获取帮助信息,可以使用此命令的-s选择来获取指定模块的帮助信息

//查询service模块的帮助文档
[root@linfan ~]# ansible-doc -s service
- name: Manage services
  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:                  # (required) Name of the service.
      pattern:               # If the service does not respond to the status command, name a substring to look for as
                               would be found in the output of the `ps' command as a
                               stand-in for a status result.  If the string is found, the
                               service will be assumed to be running.
      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
                               start command. This helps to workaround badly behaving init
                               scripts that exit immediately after signaling a process to
                               stop.
      state:                 # `started'/`stopped' are idempotent actions that will not run commands unless necessary.
                               `restarted' will always bounce the service.  `reloaded'
                               will always reload. *At least one of state and enabled are
                               required.* Note that reloaded will start the service if it
                               is not already started, even if your chosen init system
                               wouldn't normally.
      use:                   # The service module actually uses system specific modules, normally through auto detection,
                               this setting can force a specific module. Normally it uses
                               the value of the 'ansible_service_mgr' fact and falls back
                               to the old 'service' module when none matching is found.           

ansible 常用模块使用详解

ansible常用模块有:

  • ping
  • yum
  • template
  • copy
  • user
  • group
  • service
  • raw
  • command
  • shell
  • script

ansible常用模块 raw、command、shell的区别

  • shell模块调用的/bin/sh指令执行
  • command模块不是调用的shell的指令,所以没有bash的环境变量
  • raw很多地方和shell类似,更多的地方建议使用command和shell模块。但是如果是使用老版本python,需要用到raw,又或是客户端是路由器,因为没有安装pyhton模块,那就需要使用raw模块了

ansible常用模块之command

ansible模块用于在远程主机上执行命令,ansible默认使用command模块

command模块有一个缺陷就是不能使用管道符号和重定向功能

查看受控主机的/tmp目录内容

[root@linfan ~]# ansible 192.168.24.130 -a 'ls /tmp'
192.168.24.130 | SUCCESS | rc=0 >>
ansible_aUrss8
systemd-private-105010548bc14e73826a57bb46c41172-chronyd.service-8duX7C
systemd-private-105010548bc14e73826a57bb46c41172-vgauthd.service-qpo65h
systemd-private-105010548bc14e73826a57bb46c41172-vmtoolsd.service-cQZm7W           

在受控主机的/tmp目录下新建一个文件test

[root@linfan ~]# ansible 192.168.24.130 -a 'touch /tmp/test'
 [WARNING]: Consider using the file module with state=touch rather than running touch.  If you need to use command
because file is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to
get rid of this message.

192.168.24.130 | SUCCESS | rc=0 >>

[root@linfan ~]# ansible 192.168.24.130 -a 'ls /tmp'
192.168.24.130 | SUCCESS | rc=0 >>
ansible_sgtAwO
systemd-private-105010548bc14e73826a57bb46c41172-chronyd.service-8duX7C
systemd-private-105010548bc14e73826a57bb46c41172-vgauthd.service-qpo65h
systemd-private-105010548bc14e73826a57bb46c41172-vmtoolsd.service-cQZm7W
test           

command模板不支持管道符,不支持重定向

[root@linfan ~]# ansible 192.168.24.130 -a "echo 'hello world' > /tmp/test"
192.168.24.130 | SUCCESS | rc=0 >>
hello world > /tmp/test

[root@linfan ~]# ansible 192.168.24.130 -a 'cat /tmp/test'
192.168.24.130 | SUCCESS | rc=0 >>

[root@linfan ~]# ansible 192.168.24.130 -a 'ps -ef | grep vsftpd'
192.168.24.130 | FAILED | rc=1 >>
error: garbage option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).non-zero return code
           

ansible常用模块之raw

raw模块用于在受控主机上执行命令,其支持管道符与重定向

支持重定向

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'echo "hello world" > /tmp/test'

192.168.24.130 | SUCCESS | rc=0 >>
Shared connection to 192.168.24.130 closed.

[root@linfan ~]#
[root@linfan ~]# ansible 192.168.24.130 -a 'cat /tmp/test'
192.168.24.130 | SUCCESS | rc=0 >>
hello world           

支持管道符

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'cat /tmp/test |grep -Eo hello'
192.168.24.130 | SUCCESS | rc=0 >>
hello
Shared connection to 192.168.24.130 closed.
           

ansible常用模块之shell

shell模块用于在受控主机上执行受控主机上的脚本,也可以直接在受控主机上执行命令

shell模块也支持管道与重定向

查看受控主机上的脚本

[root@linfan ~]# ansible 192.168.24.130 -a 'ls -l /scripts/'
192.168.24.130 | SUCCESS | rc=0 >>
total 4
-rw-r--r--. 1 root root 23 Sep  9 10:37 test.sh           

使用shell模块在受控主机上执行受控主机上的脚本

[root@linfan ~]# ansible 192.168.24.130 -m shell -a '/bin/bash /scripts/test.sh'
192.168.24.130 | SUCCESS | rc=0 >>
8           

ansible常用模块之script

script模块用于在受控主机上执行主控主机上的脚本

[root@linfan ~]# ll /etc/ansible/scripts/
total 4
-rw-r--r-- 1 root root 26 Sep  9 10:55 boss.sh 
[root@linfan ~]# ansible 192.168.24.130 -m script -a '/etc/ansible/scripts/boss.sh &>/tmp/boss'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.24.130 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.24.130 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}           

查看受控机上的/tmp/boss文件内容

[root@linfan ~]# ansible 192.168.24.130 -m shell -a 'cat /tmp/boss'
192.168.24.130 | SUCCESS | rc=0 >>
999
           

ansible常用模块之template

template模块用于生成一个模块,并将其传输到受控主机上

下载一个163源文件并开启此源

[root@linfan ~]# cd /etc/yum.repos.d/ 
root@linfan yum.repos.d]# curl -o 163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@linfan yum.repos.d]# sed -i 's/\$releasever/7/g' 163.repo
[root@linfan yum.repos.d]# sed -i 's/^enabled=.*/enabled=1/g' 163.repo
           

将设置好的163源传到受控主机上

[root@linfan ~]# ansible 192.168.24.130 -m template -a 'src=/etc/yum.repos.d/163.repo dest=/etc/yum.repos.d/163.repo'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "checksum": "60b8868e0599489038710c45025fc11cbccf35f2",
    "dest": "/etc/yum.repos.d/163.repo",
    "gid": 0,
    "group": "root",
    "md5sum": "5a3e688854d9ceccf327b953dab55b21",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:system_conf_t:s0",
    "size": 1462,
    "src": "/root/.ansible/tmp/ansible-tmp-1536505977.96-30562591219464/source",
    "state": "file",
    "uid": 0
}           

查看受控主机上是否有163源

[root@linfan ~]# ansible 192.168.24.130  -a 'ls /etc/yum.repos.d/'
192.168.24.130 | SUCCESS | rc=0 >>
163.repo
CentOS-Base.repo
CentOS-CR.repo
CentOS-Debuginfo.repo
CentOS-fasttrack.repo
CentOS-Media.repo
CentOS-Sources.repo
CentOS-Vault.repo
           

ansible常用模块之yum

yum模块用于在指定节点机器上通过yum管理软件,其支持的参数主要有两个

  • name:要管理的包名
  • state:要执行的操作

    state常用的值:

  • latest:安装软件
  • installd:安装软件
  • present :安装软件
  • removed:卸载软件
  • absent:卸载软件

    如果想使用yum来管理软件,请确保受控主机上的yum源无异常

在受控主机上查询vsftpd是否安装

[root@linfan ~]# rpm -qa|grep vsftpd
[root@linfan ~]#                 
           

在ansible主机上使用yum模块在受控主机上安装vsftpd

[root@linfan ~]# ansible 192.168.24.130 -m yum -a 'name=vsftpd state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\n",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:3.0.2-22.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                 Repository      Size\n================================================================================\nInstalling:\n vsftpd           x86_64           3.0.2-22.el7            base           169 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 169 k\nInstalled size: 348 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : vsftpd-3.0.2-22.el7.x86_64                                   1/1 \n  Verifying  : vsftpd-3.0.2-22.el7.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:3.0.2-22.el7                                                  \n\nComplete!\n"
    ]
}           

在受控主机上查看是否安装了vsftpd

[root@linfan ~]# rpm -qa|grep vsftpd
vsftpd-3.0.2-22.el7.x86_64           

ansible常用模块之copy

copy模块用于复制文件到受控机上

[root@linfan ~]# ls /etc/ansible/scripts
boss.sh
[root@linfan ~]# ansible 192.168.24.130 -m copy -a 'src=/etc/ansible/scripts/boss.sh dest=/scripts/'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "checksum": "63432244439a6f90006e644666c8d9ad28f0cf11",
    "dest": "/scripts/boss.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "ed0d4fb8e02362109f20dcb380fb8029",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:default_t:s0",
    "size": 26,
    "src": "/root/.ansible/tmp/ansible-tmp-1536506836.61-157751882602101/source",
    "state": "file",
    "uid": 0
}
[root@linfan ~]# ansible 192.168.24.130 -a 'ls /scripts/'
192.168.24.130 | SUCCESS | rc=0 >>
boss.sh
test.sh           

ansible常用模块之group

group模块用于受控主机上添加或删除组

在受控主机上添加一个系统组,gid为306,组名为mysql

[root@linfan ~]# ansible 192.168.24.130 -m group -a 'name=mysql gid=306 state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "gid": 306,
    "name": "mysql",
    "state": "present",
    "system": false
}
[root@linfan ~]# ansible 192.168.24.130  -a 'grep mysql /etc/group'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:306:           

删除受控主机上的mysql组

[root@linfan ~]# ansible 192.168.24.130 -m group -a 'name=mysql gid=306 state=absent'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "name": "mysql",
    "state": "absent"
}
[root@linfan ~]# ansible 192.168.24.130  -a 'grep mysql /etc/group'
192.168.24.130 | FAILED | rc=1 >>
non-zero return code
           

ansible 常用模块之user

user模块用于管理受控主机上的用户账户

在受控主机上添加一个系统用户,用户名为mysql,uid为306,设置其shell为/sbin/nologin 无家目录

[root@linfan ~]# ansible 192.168.24.130 -m  user -a 'name=mysql uid=306 system=yes create_home=no shell=/sbin/nologin state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 306,
    "home": "/home/mysql",
    "name": "mysql",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": true,
    "uid": 306
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:306:3007::/home/mysql:/sbin/nologin           

修改mysql用户的uid为366

[root@linfan ~]# ansible 192.168.24.130 -m user -a 'name=mysql uid=366'
192.168.24.130 | SUCCESS => {
    "append": false,
    "changed": true,
    "comment": "",
    "group": 3007,
    "home": "/home/mysql",
    "move_home": false,
    "name": "mysql",
    "shell": "/sbin/nologin",
    "state": "present",
    "uid": 366
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:366:3007::/home/mysql:/sbin/nologin           

删除受控主机上的mysql用户

[root@linfan ~]# ansible 192.168.24.130 -m user -a 'name=mysql state=absent'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "force": false,
    "name": "mysql",
    "remove": false,
    "state": "absent"
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | FAILED | rc=1 >>
non-zero return code           

ansible常用模块之service

service模块用于管理受控主机上的服务

查看受控主机上的vsftpd服务是否启动

[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-active vsftpd'
192.168.24.130 | FAILED | rc=3 >>
unknownnon-zero return code           

启动受控主机上的vsftpd服务

[root@linfan ~]# ansible 192.168.24.130 -m service -a 'name=vsftpd state=started'
192.168.24.130 | SUCCESS => { 
...
...           

查看受控主机上的vsftpd服务是否开启自启动

[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-enabled vsftpd'
192.168.24.130 | FAILED | rc=1 >>
disablednon-zero return code            
[root@linfan ~]# ansible 192.168.24.130 -m service -a 'name=vsftpd enabled=yes'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "enabled": true,
    "name": "vsftpd", 
    ...
    ...           
[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-enabled vsftpd'
192.168.24.130 | SUCCESS | rc=0 >>
enabled
           
[root@linfan ~]#  ansible 192.168.24.130 -m service -a 'name=vsftpd state=stopped'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "name": "vsftpd",
    "state": "stopped",
    "status": { 
    ...
    ...
    [root@linfan ~]# ansible 192.168.24.130 -a 'systemctl is-active vsftpd'
192.168.24.130 | FAILED | rc=3 >>
inactivenon-zero return code

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'ss -natl'
192.168.24.130 | SUCCESS | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*
Shared connection to 192.168.24.130 closed.           

继续阅读