ansible是什么?
它是一个"配置管理工具",它是一个"自动化运维工具",ansible可以帮助我们完成一些批量任务,或者完成一些需要经常重复的工作,ansible通过ssh管理其他受管主机,并且具有一些特性,比如幂等性、剧本、模板,角色等。
前期准备
三台主机
192.168.1.207
192.168.1.208
192.168.1.209
安装ansible
使用yum源的方式安装ansible,因为安装ansible需要epel源,所以我配置了阿里的epel源和centos7系统镜像源,yum源配置如下
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# touch aliBase.repo && vi aliBase.repo
[aliBase]
name=aliBase
baseurl=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/RPM-GPG-KEY-CentOS-$releasever
[root@localhost yum.repos.d]# touch aliEpel.repo && vi aliEpel.repo
[aliEpel]
name=aliEpel
baseurl=https://mirrors.aliyun.com/epel/$releasever\Server/$basearch/
enabled=1
gpgcheck=0
[root@localhost yum.repos.d]# yum install ansible -y
安装完成之后,在/etc/ansible/hosts文件底部写入如下IP
[root@localhost yum.repos.d]# cd /etc/ansible/hosts && vi /etc/ansible/hosts
192.168.1.208
192.168.1.209
测试
[root@localhost ansible]# ansible 192.168.1.208 -m ping
#从命令的返回信息中可以看到,192.168.1.208不可达,也就是说,ansible无法通过ssh连接到主机208
[root@localhost ansible]# vi /etc/ansible/hosts
192.168.1.208 ansible_port=22 ansible_user=root ansible_ssh_pass=pass
#ansible_port 用于配置对应主机上的sshd服务端口号,在实际的生产环境中,各个主机的端口号通常不会使用默认的22号端口,所以用此参数指定对应端口。
#ansible_user 用于配置连接到对应主机时所使用的用户名称。
#ansible_ssh_pass 用于配置对应用户的连接密码
[root@localhost ansible]# ansible 192.168.1.208 -m ping
192.168.1.208 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
#其实,为了更加方便的使用,ansible还支持对主机添加别名,当主机存在别名时,我们可以通过主机的"别名"管理对应主机
#比如,我们想要将192.168.1.209这台主机的别名命名为node209,那么,我们在配置清单时,可以进行如下配置:
node209 ansible_host=192.168.1.209 ansible_port=22 ansible_user=root ansible_ssh_pass=pass
[root@localhost ansible]# ansible node209 -m ping
node209 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
上述参数,其实都是为了创建ssh连接所使用的,而说到ssh,我们都知道,创建ssh连接时,可以基于密码进行认证,也可以基于密钥进行认证,而在生产环境中,为了提高安全性,我们通常会基于密钥进行ssh认证,甚至会禁用密码认证
其实,在实际的使用环境中,我们通常会在"配置管理机(ansible主机)"中生成密钥,然后通过公钥认证的方式连接到对应的受管主机中。那么,我们就在ansible主机中生成密钥,并进行相应的配置。
首先,生成默认格式的密钥对,私钥与公钥。
[root@localhost ~]# ssh-keygen
然后将生成的公钥加入到192.168.1.208的认证列表
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.208
因为配置了密钥认证,所以可以实现免密码创建ssh连接,既然已经能够免密码创建ssh连接,那么在配置"主机清单"时,就没有必要再提供对应主机的用户名与密码了,所以,在完成了密钥认证的相关配置后,我们可以将清单中的配置精简为如下格式。
192.168.1.208 ansible_port=22
或者使用别名的格式
node208 ansible_host=192.168.1.208 ansible_port=22