自动化运维 ansible 安装及免密配置

2023-07-29  本文已影响0人  WeekDiffculty

管理机

1、选择yum自动化安装,阿里云epel源,提前配置好

yum install epe-release -y

yum install ansible libselinux-python -y

2、检查 assible软件安装情况,查询配置文件,和可执行命令
[root@localhost conf]# rpm -ql ansible | grep -E '/etc|/usr/bin'

rpm -ql ansible | grep -E '^/etc|^/usr/bin'

3、检查ansible版本

ansible --version

再准备ansible 被管理机器

安装ansible所需要的系统模块

yum install peel-release libselinux-python -y 

ansible 管理方式

ansible批量管理机器的方式主要有两种

配置好aisle的配置文件,添加被管理的机器ip地址,或者主机名
1、备份现有的配置文件
cp /etc/ansible/hosts{,.ori}
同上面的命令
2、添加管理的机器ip
vim /etc/ansible/hosts
[fengge]
192.168.101.67
192.168.101.68

SSH 密码认证方式管理

ansible是直接利用Linux本地ssh服务,以及一些远程的操作,一般情况客户端ssh默认开启

1、在管理机执行如下命令
-m 指定功能模块,默认command模块
-a 告诉模块需要执行的参数
-k 询问密码验证
-u 指定运行的用户
在管理机上,告诉其他别管理机器,你要执行什么命令,以及用什么用户去执行
ansible fengge -m command -a "hostname" -k -u root

2、执行完通常报错,需要手动ssh进行一次连接

3、再次执行 

配置免密登陆

ansible自带的密码认证参数

可以在/etc/ansible/hosts 文件中定义好密码即可实现快速认证,远程管理主机

参数
ansible_host   主机地址
ansible_port    端口,默认22
ansible_user    认证的用户
ansible_ssh_pass    用户认证的密码
使用修改hosts文件实现认证
[fengge]
192.168.101.66 ansible_user=root ansible_ssh_pass=123456
192.168.101.67 ansible_user=root ansible_ssh_pass=123456
192.168.101.68 ansible_user=root ansible_ssh_pass=123456
[root@localhost ansible]# ansible fengge -m command -a "hostname"
192.168.101.67 | CHANGED | rc=0 >>
localhost.localdomain
192.168.101.68 | CHANGED | rc=0 >>
localhost.localdomain
192.168.101.66 | CHANGED | rc=0 >>
localhost.localdomain

SSH密钥方式批量管理机器

1、在管理机上创建ssh密钥对

[root@localhost ~]# ssh-keygen -f ~/.ssh/id_rsa -P "" > /dev/null 2>%1

2、此时检查私钥文件

[root@localhost ~]# cd ~/.ssh/
[root@localhost .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts

编写公钥分发脚本

#!/bin/bash
rm -rf ~/.ssh/id_rsa*
ssh-keygen -f ~/.ssh/id_rsa -P "" > /dev/null 2>&1
SSH_Pass=123456
Key_Path=~/.ssh/id_rsa.pub
for ip in 66 67 68
do
        sshpass -p$SSH_Pass ssh-copy-id -i $Key_Path "-o StrictHostKeyChecking=no" 192.168.101.$ip
done
# 非交互式分发公钥需要用sshpass指定ssh密码,通过-o StrictHostKeyChecking=no 跳过SSH链接确认信息

sh ssh_key_send 执行脚本

ansible fengge -m command -a "uname -a"

此时在管理机上再链接客户机就不需要密码了,

总结

在生产环境中,ansible的链接方式,二选一即可,最好是配置ssh公私钥密码登录

上一篇 下一篇

猜你喜欢

热点阅读