Playbook脚本——使用Ansible-authorized_key模块实现主机批量拷贝密钥
环境搭建
- 由于是自建环境,使用时需要安装环境
ansible-galaxy collection install ansible.posix
通过此命令便可以只用 authorized_key
模块了
-
在未执行上述命令时是没有 authorized_key 的手册的
-
执行
ansible-doc -l | grep -i authrized
命令
实现目标
- 为远程受管理主机创建新用户,并能够使用 ssh 实现免密登录
命令
- 要求使用管理主机的 root 用户执行代码
---
- name: set public key on remote hosts
hosts: servera
# 受管理主机或主机组
become: no
remote_user: root
tasks:
- name: set secondary group for rhce
user:
name: rhce
groups: wheel
append: yes
- name: Set authorized key taken from file
ansible.posix.authorized_key:
user: rhce
state: present
key: "{{ lookup('file', '/home/rhce/.ssh/id_rsa.pub') }}"
# 控制主机的普通用户密钥地址
- name: Change file ownership, group and permissions
ansible.builtin.file:
path: /etc/sudoers
mode: '0644'
- name: Ensure /etc/suders no passwd
ansible.builtin.lineinfile:
path: /etc/sudoers
insertafter: '^%sudo '
line: '%wheel ALL=(ALL:ALL) NOPASSWD: ALL'
- name: Change file ownership, group and permissions
ansible.builtin.file:
path: /etc/sudoers
owner: root
group: root
mode: '0440'
问题及解决方案
受控主机连接问题
fatal: [serverf]: FAILED! => {"msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this .
解决方法
- 方案1
- 在 ansible.cfg 中添加
host_key_checking = False
- 在 ansible.cfg 中添加
- 方案2
- 先使用 root 用户 ssh连接,使 root 用户中 know_host 保存来自受控主机的 host_key
执行脚本时的问题
- root 用户下没有执行
ansible-galaxy collection install ansible.posix
解决方法
- 切换至 root 用户执行一下命令
ansible-galaxy collection install ansible.posix
分类:
Ansible
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)