ansible-authorized_key 模块 批量上传公钥到服务器,


Ansible默认是通过SSH key和远程被控制主机进行通信,当然我们可以SSH password来和远程主机进行通信。 如果使用SSH KEY,则要将控制主机上的公钥放到被监控主机的/root/.ssh/authorized_keys文件中,这种方式也是官方提倡的。毕竟直接使用密码存在一定的风险。

有时候添加新项目时需要上百台机器,一台一台上传公钥或写脚本,现在有一种更简便的方法,使用ansible 的authorized_key 模块 批量上传到多台服务器。

authoried_keys模块参数介绍

如何使用
ansible all -m authorized_key -a "user=root key='{{ lookup('file', '/root/.ssh/id_rsa.pub')}}' path='/root/.ssh/authorized_keys' manage_dir=no" --ask-pass -c paramiko

SSH password: #输入服务器的密码(因为我所有测试服务器密码一致,所以只需要输入一次。

如果密码不同,则需要将密码定义到/etc/ansible/hosts中)
[xxx@xxx ~]# cat /etc/ansible/hosts
[test]
10.xxx ansible_connection=ssh ansible_ssh_user=xxx ansible_ssh_pass="xxxxxx"
10.xxx ansible_connection=ssh ansible_ssh_user=xxx ansible_ssh_pass="xxxxxx"

[xxx@xxx ~]# ansible test -m authorized_key -a "user=root key='{{ lookup('file', '/root/.ssh/id_rsa.pub')}}'"

user=root :将密钥推送到远程主机的哪个用户下
key=’{{ lookup(‘file’, ‘/root/.ssh/id_rsa.pub’)}}’ :指定要推送的密钥文件所在的路径
path=’/root/.ssh/authorized_keys’ [Default: (homedir)+/.ssh/authorized_keys] :将密钥推送到远程主机的哪个目录下并重命名
manage_dir=no :指定模块是否应该管理 authorized key 文件所在的目录。如果设置为 yes,模块会创建目录,以及设置一个已存在目录的拥有者和权限。如果通过 path 选项,重新指定了一个 authorized key 文件所在目录,那么应该将该选项设置为 no
exclusive [default: no]: 是否移除 authorized_keys 文件中其它非指定 key
state (Choices: present, absent) [Default: present]: present 添加指定 key 到 authorized_keys 文件中;absent 从 authorized_keys 文件中移除指定 key

通过次方法成功分发控制主机公钥文件后,请开启host_key_checking,并清除INVENTORY中的连接信息!!!

[xx@xxx ~]# egrep -v '^#|^$' /etc/ansible/ansible.cfg
[defaults]
host_key_checking = False
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
connect_timeout = 30
connect_retries = 30
connect_interval = 1
[accelerate]
[selinux]
[colors]
[diff]

相关内容

    暂无相关文章