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,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤