1 ansible安装

(1)安装ansible前需要配置好yum源

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum install epel-release

然后进行yum源缓存清理与重新加载:

yum clean all
yum makecache

(2)安装ansible

yum install -y ansible

2 ansible配置与简单使用

ansible组成介绍:

[root@vm1 ~]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
└── roles

        ansible有常见的几个命令模块,本文不进行各个模块介绍,只针对实际使用场景进行总结。各个模块的介绍可以参考其他文章:

2.1 ansible.cfg配置文件

对于ansible配置文件ansible.cfg进行配置:

[defaults]
host_key_checking = False  #默认host_key_checking部分是注释的,通过取消该行的注释,可以实现跳过 ssh 首次连接提示验证部分
forks = 10 #forks参数是指执行时的并发数
log_path = /var/log/ansible.log #如果注释此选项则不输出执行日志,开启可以将command/playbook的执行过程写入日志路径,但是该日志不会归档;
command_warnings = False #Ansible can optionally warn when usage of the shell and
command module appear to be simplified by using a default Ansible module instead.

日志信息:

安装ansible 镜像 ansible安装教程_shell

 2.2 hosts文件

        hosts文件一般存放我们的被管理主机信息。主机列表清单,也叫Inventory。所有被管理的主机都需要定义在该文件中。如果不想使用默认清单的话可以用-i选项指定自定义的清单文件,防止多人混合使用一个主机清单。如果没有定义在主机列表文件中,执行命令会提示“No hosts matched”。

[root@vm1 ~]# grep -v ^# /etc/ansible/hosts
[webservers]
10.10.1.11 ansible_ssh_port=22 ansible_ssh_user=lisi ansible_ssh_pass="****"
[webserver2]
10.10.1.10 ansible_ssh_port=22 ansible_ssh_user=lisi ansible_ssh_pass="****"

         定义一台webserver,通过用户名密码进行ssh远程登录。远程执行命令查看httpd服务的状态:

[root@vm1 ~]# ansible -i /etc/ansible/hosts all -m command -a '/usr/sbin/service httpd status'
10.10.1.11 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since 六 2021-07-24 18:04:16 CST; 4min 34s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 2721 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─2721 /usr/sbin/httpd -DFOREGROUND
           ├─2722 /usr/sbin/httpd -DFOREGROUND
           ├─2723 /usr/sbin/httpd -DFOREGROUND
           ├─2724 /usr/sbin/httpd -DFOREGROUND
           ├─2725 /usr/sbin/httpd -DFOREGROUND
           └─2726 /usr/sbin/httpd -DFOREGROUNDRedirecting to /bin/systemctl status httpd.service
10.10.1.10 | FAILED | rc=4 >>
Redirecting to /bin/systemctl status httpd.service
Unit httpd.service could not be found.non-zero return code

2.3 ansible的配置参数

ansible主要参数如下:

  • -u  username——指定ssh连接的用户名,即执行后面命令的用户
  • -i  inventory_file——指定所使用的inventory文件的位置,默认为/etc/ansible/hosts
  • -m  module——指定使用的模块,默认为command,常见模块有command、shell、script、yum、copy等等。一般来说常用命令使用command模块即可满足,若是要支持管道符,需要使用shell模块;
  • -f  10——指定并发数,并发量大的时候,提高该值
  • --sudo  [-k]——当需要root权限执行的化,-k参数用来输入root密码。
  • -a——指定模块的参数,可以是命令等等。

2.4 远程登录方式

        2.2其实已经说了一种方式,是直接通过用户名密码进行登录设备制定设备集合进行批量操作。由于这种直接暴露密码的方式安全性较差,因此存在另外一种将管理端的公钥批量复制到被管理端,后续ssh登录时候就可以进行免密登录了。

        首先生成我们的公钥文件:

[root@vm1 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
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:JhXX8x4784pHQ+wAQsZ+GMNdp9HhvKdnLL9S1EPWH7U root@vm1
The key's randomart image is:
+---[RSA 2048]----+
|       ++..oo.o.+|
|       .*oo o*.+o|
|       ..= ..+=E+|
|       .o . . =+o|
|      . S.   =ooo|
|       o      O= |
|             .+=+|
|             o.=.|
|            ..ooo|
+----[SHA256]-----+
[root@vm1 ~]# ls .ssh/id_rsa
.ssh/id_rsa
[root@vm1 ~]# ls .ssh/
config  id_rsa  id_rsa.pub  known_hosts
[root@vm1 ~]# cat .ssh/id_rsa.pub #这个就是我们的公钥文件了,下面是我这台管理端设备的公钥信息
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3/wJ4kA2smkrALSFZ1KiKE/dmaSGyP2E13sP+YlOHSMsyId2zHK17ZqMfn3rN6jiZHa25qxFKENtqbnQQJKQ4+by9yHhIa/zwtvQBqFRTsafpgOlayxWgMw95sE6vogxXxOuA2CcW29j+ivhmDEx596AHBWEJkiPuGQhuksPefkNhwaGyemNXoesCLVQkr97xrkEHcKxSWLGTGwjE26ZqBGbbKCL6y1ya0zG8fT5N4acwsJUj60BgDbPwobZzRAr6VOlUFRL3C+AIl0og/oo4znFJxjEP2gqcnzoDrfp54HdI7hog00zDcstGpb7gqHiwCAOidMBR38GT+ugHc9yV root@vm1
[root@vm1 ~]#

        然后将我们的公钥信息拷贝到被管理端:

ssh-copy-id -i $被管理端IP

[root@vm1 ~]# ssh-copy-id -i 10.10.1.11
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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
Warning: Permanently added '10.10.1.11' (ECDSA) to the list of known hosts.
root@10.10.1.11's password:

Number of key(s) added: 1

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

可以查看被管理端上拷贝过来的公钥信息:

[root@vm2 ~]# cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3/wJ4kA2smkrALSFZ1KiKE/dmaSGyP2E13sP+YlOHSMsyId2zHK17ZqMfn3rN6jiZHa25qxFKENtqbnQQJKQ4+by9yHhIa/zwtvQBqFRTsafpgOlayxWgMw95sE6vogxXxOuA2CcW29j+ivhmDEx596AHBWEJkiPuGQhuksPefkNhwaGyemNXoesCLVQkr97xrkEHcKxSWLGTGwjE26ZqBGbbKCL6y1ya0zG8fT5N4acwsJUj60BgDbPwobZzRAr6VOlUFRL3C+AIl0og/oo4znFJxjEP2gqcnzoDrfp54HdI7hog00zDcstGpb7gqHiwCAOidMBR38GT+ugHc9yV root@vm1

        这种方式对于单台服务器来说还是可行,但对于上100台上1000台服务器来说明显不行,这个时候通过以下脚本来进行实现:

[root@vm1 ~]# cat key_put.sh
#!/bin/bash
#
#1.为脚本添加远程主机的用户及密码
#############################################################################
read -p "请您输入主机用户:" user
read -p "请您输入主机密码:" mima
read -p "请您再次输入密码:" queren
if [ $mima == $queren ]
then
echo "您输入的密码为:$queren" && sleep 1
echo "正在为您创建密钥对儿,请您注意" && sleep 1
else
echo "您两次输入的密码不匹配,请您重新输入"
read -p "请您输入主机用户:" user
read -p "请您输入主机密码:" mima
read -p "请您再次输入密码:" queren
if [ $mima == $queren ]
then
echo "您输入的密码为:$queren"
        echo "正在为您创建密钥对儿,请您注意" && sleep 1
else
echo "您两次输入的密码不同,请您重新执行脚本"
fi
fi
#############################################################################
#2.检查秘钥、创建密钥
if [ -f /root/.ssh/id_rsa.pub ]
then
    echo "您的主机已经有密钥对儿了,不需要再次创建"
else
    ssh-keygen -t rsa -P ''
fi

rpm -q sshpass &> /dev/null
if [ $? -ne 0 ]
then
    yum -y install sshpass &> /dev/null
    echo "StrictHostKeyChecking no" > /root/.ssh/config
    echo "UserKnownHostsFile=/dev/null" >> /root/.ssh/config
else
    echo "StrictHostKeyChecking no" > /root/.ssh/config
    echo "UserKnownHostsFile=/dev/null" >> /root/.ssh/config
fi

#3.批量添加密钥对儿
ip=`cat ~/ip.txt`
for i in $ip
do
    sshpass -p $queren ssh-copy-id $user@$i &> /dev/null
    ssh $user@$i "pwd" &> /dev/null
    if [ $? -eq 0 ]
    then
        echo "$i is add successful"
    else
        echo "$i is failure"
    fi
done

       通过sshpass这种避免交互输入密码的方式来实现批量化服务器配置。运行这个脚本,即可对被管理服务器端进行批量化配置了。

        以下指定用户名进行免密ssh登录配置:

[root@vm1 ~]# ansible -u lisi -i  /etc/ansible/hosts all -m command -a '/usr/sbin/service httpd status'
10.10.1.11 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since 六 2021-07-24 18:04:16 CST; 36min ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 2721 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─2721 /usr/sbin/httpd -DFOREGROUND
           ├─2722 /usr/sbin/httpd -DFOREGROUND
           ├─2723 /usr/sbin/httpd -DFOREGROUND
           ├─2724 /usr/sbin/httpd -DFOREGROUND
           ├─2725 /usr/sbin/httpd -DFOREGROUND
           └─2726 /usr/sbin/httpd -DFOREGROUNDRedirecting to /bin/systemctl status httpd.service
10.10.1.10 | FAILED | rc=4 >>
Redirecting to /bin/systemctl status httpd.service
Unit httpd.service could not be found.non-zero return code

2.5 playbook

        我们使用如上这些命令可以快速利用Ansible的工具编写脚本、从而以非常简便的方式实现任务处理的自动化与流程化。除此之外,我们还可以创建Ansible Playbook以收集命令与任务集,这样能够大大降低管理工作的复杂程度。对于多条命令一般还是用playbook比较合适一点。

        Playbook采用YAML语法结构,因此它们一般比较易于阅读并加以配置。举例说明:

如下简单案例使用playbook实现在客户端安装screen软件。

在/etc/ansible/目录下,新建screen.yaml文件,内容如下:

- hosts: all

  remote_user: root

  tasks:

  - name: yum install screen

    shell: yum install screen -y

文件解析:-hosts:all指定对所有hosts生效,remote_user表示远程root,tasks表示需要执行的任务;name显示的名称,shell后面接:需要在远程客户端执行的命令。可以写多个命令,以;分号隔开即可,例如 shell: yum install screen -y ;mkdir /tmp/`date +%Y%m%d`