Ansible安装配置及常用模块简介

Ansible是一种集成IT系统的配置管理, 应用部署, 执行特定任务的开源平台。 它基于Python语言实现, 部署只需在主控端部署Ansible环境, 被控端无需安装代理工具, 只需打开SSH, 让主控端通过SSH秘钥认证对其进行所有的管理监控操作。相对于SaltStack, 它除了利用SSH安全传输, 无需在客户端进行任何配置, 而且它有一个很庞大的用户群体以及丰富的API, 相对适合部署到数量比较大且对系统软件安装要求比较严格的集群中。Ansible可以实现批量系统配置、批量软件部署、批量文件拷贝、批量运行命令等功能。

更多配置参考: https://github.com/ansible 

官方文档: http://docs.ansible.com/ansible

本文介绍ansible的安装和常用模块使用

安装环境:centos6.8

管理端IP:内网192.168.9.101 外网192.168.10.133

被管理端:www.lemon.com:内网192.168.9.134 外网192.168.10.137

                 www.orange.com: 内网192.168.9.135 外网192.168.10.138

一、ansible管理端配置SSH密钥免密登录被管理端

yum install epel-release -y

# yum install ssh* -y

扫描二维码关注公众号,回复: 4105894 查看本文章

ssh-keygen -t rsa

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:
24:13:34:e9:71:2b:20:0b:48:a6:86:9a:1d:1b:1d:26 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|ooE o.+.         |
|* .+..oo.        |
|oooo.ooo..       |
|oo.+  o+.        |
|o o    .S        |
|                 |
|                 |
|                 |
|                 |
+-----------------+

同步公钥文件id_rsa.pub到目标主机

# ssh-copy-id -i /root/.ssh/id_rsa.pub r[email protected]

# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

校验SSH免密码配置是否成功.

# ssh [email protected]

如直接进入则配置完成.

二、ansible软件安装

1.管理端安装软件

yum install ansible -y

2.被管理端安装软件

yum install libselinux-python -y

PS:如果关闭selinux,那么被管理端可以不安装(建议安装)

3.管理端配置管理文件

# vim /etc/ansible/hosts

文本内容修改为如下:

[webservers] #定义一个webservers组,组里有www.lemon.com和www.orange.com两台主机
www.lemon.com
www.orange.com
[host01] #同上解释
www.lemon.com
[host02] #同上解释
www.orange.com

三、ansible批量管理

ansible语法示例:

ansible命令语法格式:

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

<host-pattern>
指明管控主机,以模式形式表示或者直接给定IP,必须事先定义在文件中;all设置所有
 
 [-f forks]
指明每批管控多少主机,默认为5个主机一批次
 
[-m module_name]
使用何种模块管理操作,所有的操作都需要通过模块来指定
 
[-a args]
指明模块专用参数;args一般为key=value格式
注意:command模块的参数非为kv格式,而是直接给出要执行的命令即可;

ansible执行命令后输出信息中:

绿色——表示查询,或者没有发生任何改变

红色——表示命令操作出现异常

屎×××——对远程主机做了相应改动

粉色——对操作提出建议或忠告

四、常用模块介绍

1.command命令模块

command: 执行远程主机SHELL命令:

[root@centos6 ~]# ansible webservers -m command -a "free -m" #执行free -m查看主机内存使用情况
www.lemon.com | SUCCESS | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:           980        276        703          0         16        142
-/+ buffers/cache:        118        861
Swap:         1983          0       1983

www.orange.com | SUCCESS | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:           980        256        724          0         17        118
-/+ buffers/cache:        120        860
Swap:         1983          0       1983
 

用于在各被管理节点运行指定的命令 
shell和command的区别:shell模块可以特殊字符,而command是不支持

2.ping模块

ping:检查指定节点机器是否还能连通,用法很简单,不涉及参数,主机如果在线,则回复pong 

[root@centos6 ~]# ansible webservers -m ping #测试主机连通性
www.lemon.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
www.orange.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3.copy模块和template模块(用法基本相同)

copy:实现主控端向目标主机拷贝文件, 类似scp功能

[root@centos6 test]# ansible webservers -m copy -a "src=/root/test/test.sh dest=/root/test/ owner=root group=root mode=0755"

#复制管理端一个名为test.sh的文件到root下的test目录,所属者和所属组都为root 权限为755
www.orange.com | SUCCESS => {
    "changed": true, 
    "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
    "dest": "/root/test/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f8096daec345773cbc2b13b86109e54f", 
    "mode": "0755", 
    "owner": "root", 
    "size": 69, 
    "src": "/root/.ansible/tmp/ansible-tmp-1542236024.1-90099218503531/source", 
    "state": "file", 
    "uid": 0
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
    "dest": "/root/test/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f8096daec345773cbc2b13b86109e54f", 
    "mode": "0755", 
    "owner": "root", 
    "size": 69, 
    "src": "/root/.ansible/tmp/ansible-tmp-1542236024.09-200586221288059/source", 
    "state": "file", 
    "uid": 0
}

template基于模板方式生成一个文件复制到远程主机(template使用Jinjia2格式作为文件模版,进行文档内变量的替换的模块。它的每次使用都会被ansible标记为”changed”状态。) 
– backup: 如果原目标文件存在,则先备份目标文件 
– src:在ansible控制器上的Jinja2格式化模板的路径。 这可以是相对或绝对的路径。 
– dest:将模板渲染到远程机器上的位置。 
force:是否强制覆盖,默认为yes 
– owner:目标文件属主 
– group:目标文件属组 
– mode:目标文件的权限模式,模式可以被指定为符号模式(例如,u + rwx或u = rw,g = r,o = r)。

4.stat模块

stat:获取远程文件状态信息, 包括atime, ctime, mtime, md5, uid, gid等信息

[root@centos6 test]# ansible webservers -m stat -a "path=/root/test/test.sh"    #查看脚本文件信息                                                
www.orange.com | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1542338028.7207732, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
        "ctime": 1542338028.7247732, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 786081, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/x-shellscript", 
        "mode": "0755", 
        "mtime": 1542338028.3807731, 
        "nlink": 1, 
        "path": "/root/test/test.sh", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 69, 
        "uid": 0, 
        "version": "1922158357", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}
www.lemon.com | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1542338028.7619922, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
        "ctime": 1542338028.7659922, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 785266, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/x-shellscript", 
        "mode": "0755", 
        "mtime": 1542338028.4139922, 
        "nlink": 1, 
        "path": "/root/test/test.sh", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 69, 
        "uid": 0, 
        "version": "934519185", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}

 5.script模块

script:远程执行MASTER本地SHELL脚本.(类似scp+shell)

[root@centos6 test]# ansible webservers -m script -a "/root/test/test.sh"   #执行test.sh脚本,脚本内容为echo ""this iiiiis a test"                                                       
www.orange.com | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to www.orange.com closed.\r\n", 
    "stderr_lines": [
        "Shared connection to www.orange.com closed."
    ], 
    "stdout": "this iiiiis a test\r\n", 
    "stdout_lines": [
        "this iiiiis a test"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to www.lemon.com closed.\r\n", 
    "stderr_lines": [
        "Shared connection to www.lemon.com closed."
    ], 
    "stdout": "this iiiiis a test\r\n", 
    "stdout_lines": [
        "this iiiiis a test"
    ]
}

6.yum模块

yum:Linux包管理平台操作,  常见都会有yum和apt, 此处会调用yum管理模式

[root@centos6 test]# ansible webservers -m yum -a 'name=wget state=latest' #安装wget
www.orange.com | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: centos.ustc.edu.cn\n * extras: ftp.sjtu.edu.cn\n * updates: centos.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.12-10.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n wget            x86_64            1.12-10.el6            base            484 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 484 k\nInstalled size: 1.8 M\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : wget-1.12-10.el6.x86_64                                      1/1 \n\r  Verifying  : wget-1.12-10.el6.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.12-10.el6                                                     \n\nComplete!\n"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: centos.ustc.edu.cn\n * extras: ftp.sjtu.edu.cn\n * updates: centos.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.12-10.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n wget            x86_64            1.12-10.el6            base            484 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 484 k\nInstalled size: 1.8 M\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : wget-1.12-10.el6.x86_64                                      1/1 \n\r  Verifying  : wget-1.12-10.el6.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.12-10.el6                                                     \n\nComplete!\n"
    ]
}

使用`yum’软件包管理器管理软件包,其选项有: 
– config_file:yum的配置文件 (optional) 
– disable_gpg_check:关闭gpg_check (optional) 
– disablerepo:不启用某个源 (optional) 
– enablerepo:启用某个源(optional) 
– name:要进行操作的软件包的名字,默认最新的程序包,指明要安装的程序包,可以带上版本号,也可以传递一个url或者一个本地的rpm包的路径 
– state:状态(present,absent,latest),表示是安装还卸载 
   present:默认的,表示为安装 
   lastest: 安装为最新的版本 
   absent:表示删除 
7.cron模块

cron:远程主机crontab配置

[root@centos6 test]# ansible webservers -m cron -a 'name=sync_time minute=*/5 job="/usr/sbin/ntpdate cn.pool.ntp.org >/dev/null 2>&1"' #每五分钟同步一次网络时间
www.orange.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "check dir", 
        "sync_time"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "check dir", 
        "sync_time"
    ]
}

job                    # 定义定时任务与要做什么事

name       # 给定时任务加一个备注,避免创建出多个重复的定时任务(根据定时任务备份判断        是否生成一个新的定时任务)

stat       #若设置为present,表示创建定时任务,若设置为absent,表示删除指定定时任务

disabled      #disable=yes注释掉定时任务(不生效),disable=no解除注释定时任务(生效)

8.service模块

service:远程主机系统服务管理

[root@centos6 test]# ansible webservers -m service -a 'name=mysqld state=restarted' #重启mysql服务
www.orange.com | SUCCESS => {
    "changed": true, 
    "name": "mysqld", 
    "state": "started"
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "name": "mysqld", 
    "state": "started"
}

9.file模块

file模块主要用于远程主机上的文件操作,file模块包含如下选项: 
– force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no 
– group:定义文件/目录的属组 
– mode:定义文件/目录的权限 
– owner:定义文件/目录的属主 
– path:必选项,定义文件/目录的路径 
– recurse:递归的设置文件的属性,只对目录有效 
– src:要被链接的源文件的路径,只应用于state=link的情况 
– dest:被链接到的路径,只应用于state=link的情况 
– state: 
   directory:如果目录不存在,创建目录 
   file:即使文件不存在,也不会被创建 
   link:创建软链接 
   hard:创建硬链接 
   touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间 
   absent:删除目录、文件或者取消链接文件

[root@centos6 ~]# ansible webservers -m file -a "dest=/root/test/test.sh state=absent"  #删除test.sh文件
www.orange.com | SUCCESS => {
    "changed": true, 
    "path": "/root/test/test.sh", 
    "state": "absent"
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "path": "/root/test/test.sh", 
    "state": "absent"
}

10.setup模块

ansible webservers -m setup 

#显示远程主机的所有信息(后面加-v显示详细信息)

#提取IP、或架构信息等,X86来判断主机架构,安装合适软件

ansible webservers -m setup -v  

#主要用于解决一些错误:如远程主机hang住了,ansible会输出少量信息(最多-vvvv)

猜你喜欢

转载自blog.csdn.net/qq_39626154/article/details/84134229