如何使用 ansible 推送带有 SSH 密钥身份验证的剧本

Posted

技术标签:

【中文标题】如何使用 ansible 推送带有 SSH 密钥身份验证的剧本【英文标题】:how can I use ansible to push playbooks with SSH keys authentification 【发布时间】:2021-06-19 11:41:07 【问题描述】:

我是 ansible 的新手,并尝试将 playbook 推送到我的节点。我想通过 ssh-keys 推送。这是我的剧本:

- name: nginx install and start services
 hosts: <ip>
 vars:
   ansible_ssh_private_key_file: "/path/to/.ssh/id_ed25519"
 become: true

 tasks:
 - name: install nginx
   yum:
     name: nginx
     state: latest
 
 - name: start service nginx
   service:
     name: nginx
     state: started

这是我的库存:

<ip> ansible_ssh_private_key_file=/path/to/.ssh/id_ed25519

在我推送之前,我检查它是否有效:ansible-playbook -i /home/myuser/.ansible/hosts nginx.yaml --check

它给了我: fatal: [ip]: UNREACHABLE! =&gt; "changed": false, "msg": "Failed to connect to the host via ssh: user@ip: Permission denied (publickey,password).", "unreachable": true

在那台服务器上我没有 root 权限,我不能执行 sudo。这就是为什么我在我的主目录中使用我自己的库存。对于我想要推送该 nginx 剧本的目标节点,我可以进行 SSH 连接并执行登录。公钥在 /home/user/.ssh/id_ed25119.pub 中的远程服务器上

我错过了什么?

【问题讨论】:

公钥内容必须在远程服务器上连接用户的~/.ssh/authorized_keys文件中。 【参考方案1】:

将 /etc/ansible/ansible.cfg 复制到您运行 nginx.yaml 剧本的目录中,或根据文档的其他位置:https://docs.ansible.com/ansible/latest/reference_appendices/config.html#ansible-configuration-settings-locations

然后编辑该文件以更改此行:

#private_key_file = /path/to/file

阅读:

private_key_file = /path/to/.ssh/id_ed25519

同时检查远程user_user 条目。

【讨论】:

以上是关于如何使用 ansible 推送带有 SSH 密钥身份验证的剧本的主要内容,如果未能解决你的问题,请参考以下文章

ansible操作

Ansible:如何配置没有 ssh 密钥的跳转主机?

如何避免每次推送或拉取代码时都添加 ssh 密钥

使用ansible 批量分发ssh密钥

自动化运维Ansible安装部署及使用

ansible不配置ssh免密钥,使用密码登录