使用 ansible 分发 ssh 密钥

hea*_*nce 1 ansible ansible-2.x

我已将用户帐户部署到我们的测试机器上,并创建了他们的主目录并生成了 ssh 密钥。用户已按预期创建。

在此输入图像描述

我如何将他们的密钥复制到每个服务器的授权密钥,以便他们可以在不输入密码或至少使用密码的情况下执行 ssh?

---
- hosts: all
  remote_user: root
  vars:
    users:
      - username: test9
      - username: test8
      - username: test7

  tasks:
  - name: Adding users
    user:
      name: "{{ item.username }}"
      state: present
      createhome: yes
      generate_ssh_key: yes
      ssh_key_bits: 2048
    with_items: "{{ users }}"
Run Code Online (Sandbox Code Playgroud)

我试过这个:

---
- hosts: all
  remote_user: root
  vars:
    users:
      #- username: test9
      - username: test8
      - username: test7

  tasks:
  - name: Adding users
    authorized_key: user='{{item.username}}' state=present key="{{ lookup('file', '/home/{{ item.username}}/.ssh/id_rsa.pub')}}" manage_dir=no
    with_items: "{{ users }}"
Run Code Online (Sandbox Code Playgroud)

并收到错误消息,指出 message: could not locate file in lookup: /home/test8/.ssh/id_rsa.pub"}它是否试图在 ansible 服务器而不是那些主机中查找文件?我该如何解决这个问题?抱歉,我是 ansible 新手。

kfr*_*ezy 5

根据Ansible 的 Lookups 文档

查找发生在本地计算机上,而不是远程计算机上。

因此 Ansible 正在尝试在“Ansible 服务器”上查找用户的密钥。

就我个人而言,我不会generate_ssh_key在您的用户任务中使用该参数。

  1. 每个用户对于每个服务器都有不同的密钥。
  2. 您必须将密钥分发给每个用户,因为他们首先无法访问服务器。
  3. 如果您确实想确保用户私钥的安全,最好的方法是根本不分发它们

相反,我会向用户指示如何生成密钥,并要求他们在生成后向我提供他们的公钥。然后,您可以通过查找或作为变量将 pub 密钥传递给 Ansible。

但是,如果您确定了自己的方法,我就不会使用该authorized_keys模块。相反,我只是复制该文件。

- name: copy pub key to authorized_keys
  copy:
    src: "/home/{{ item.username }}/.ssh/id_rsa.pub"
    dest: "/home/{{ item.username }}/.ssh/authorized_keys"
    user: "{{ item.username }}"
    group: "{{ item.username }}"
    mode: "0644"
    remote_src: True
  with_items: "{{ users }}"
Run Code Online (Sandbox Code Playgroud)