1、authorized_key 模块的简单介绍
需要使用到的模块:authorized_key,为特定的用户账号添加或删除 SSH authorized keys
帮助文件查看
ansible-doc authorized_key
常用选项:
Options: (= is mandatory)(= 后面的参数是强制要有的)
- exclusive [default: no]: 是否移除 authorized_keys 文件中其它非指定 key
= key: SSH public key(s) 可以是字符串或 url,如:https://github.com/username.keys
- key_options [Default: None]: 附加到 key 中的字符串,该字符串会加到 key 的开头
- path [Default: (homedir)+/.ssh/authorized_keys]: 指定 authorized_keys 文件存放的位置
- state (Choices: present, absent) [Default: present]: present 添加指定 key 到 authorized_keys 文件中;absent 从 authorized_keys 文件中移除指定 key
= user: 指定修改远端服务器上哪个用户的 authorized_keys
- manage_dir (Choices: yes, no) [Default: yes]: 指定模块是否应该管理 authorized key 文件所在的目录。如果设置为 yes,模块会创建目录,以及设置一个已存在目录的拥有者和权限。如果通过 path 选项,重新指定了一个 authorized key 文件所在目录,那么应该将该选项设置为 no
2、批量推送
一个简单的批量推送的 playbook 文件
]$ vim PushKey.yml
---
- hosts: webs
remote_user: osmgr
become: yes
become_user: root
become_method: sudo
tasks:
- name: deliver authorized_keys
authorized_key:
user: osmgr
key: "{{ lookup('file', '/home/osmgr/.ssh/id_rsa.pub') }}"
state: present
exclusive: yes
以 osmgr 用户身份,执行以下命令,并提供远端主机上 osmgr 用户的口令
]$ ansible-playbook PushKey.yml -k
SSH password:
注:
远端主机上 osmgr 用户已经配置免密 sudo 权限
3、批量更改
出于安全的考虑,可能有定期更换密钥的需求。其实批量推送与批量更改实现原理是一致的:
1.生成新的密钥时,使用 -f 选项,避免新生成的密钥覆盖老的密钥
]$ ssh-keygen -t rsa -f ~/.ssh/id_rsa_new
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/osmgr/.ssh/id_rsa_new.
Your public key has been saved in /home/osmgr/.ssh/id_rsa_new.pub.
The key fingerprint is:
00:0e:dc:42:0b:cf:28:d3:41:0b:3f:ee:b7:f8:48:5d osmgr@test-135-46
The key's randomart image is:
+--[ RSA 2048]----+
|o+=.. |
| Oo*.. |
|+ O.. . |
|.o . . |
| . E S |
| . . . |
| o o |
| . + . |
| o.o |
+-----------------+
-f:设置 key 文件的文件名
查看生成的新密钥对:
]$ ls ~/.ssh | grep new
id_rsa_new
id_rsa_new.pub
2.将新生成的密钥推送到远程主机上,还是使用上面的 playbook。只是把读取的密钥文件更改成新生成的 “id_rsa_2016-09-13.pub” 即可。
key: "{{ lookup('file', '/home/osmgr/.ssh/id_rsa_new.pub') }}"
3.更新完成后,备份老的密钥,将新生成的密钥名更改为默认密钥名
备份老密钥:
]$ mv ~/.ssh/id_rsa ~/keybak/id_rsa.$(date +%F).bak
]$ mv ~/.ssh/id_rsa.pub ~/keybak/id_rsa.pub.$(date +%F).bak
更改新密钥:
]$ mv ~/.ssh/id_rsa_new id_rsa
]$ mv ~/.ssh/id_rsa_new.pub id_rsa.pub
网友评论