使用 ansible 在远程主机上创建 ssh 密钥失败

Creating ssh keys on remote hosts using ansible fails

我正在使用 Ansible 在远程主机上创建 ssh 密钥。以下是剧本代码

- name: Test playbook
  hosts: all
  remote_user: admin
  tasks:
    - name: Create ssh keys
      expect:
        command: ssh-keygen -t rsa
        echo: yes
        timeout: 5
        responses:
          "file": "" ## Enter file in which to save the key (/home/admin/.ssh/id_rsa)
          "Overwrite": "n" ## Overwrite (y/n)? 
          "passphrase": "" ## Enter passphrase (empty for no passphrase)

但是,出现以下错误:

fatal: [10.1.1.1]: FAILED! => {"changed": true, "cmd": "ssh-keygen -t rsa", "delta": "0:00:00.301769", "end": "2015-12-30 09:56:29.465815", "failed": true, "invocation": {"module_args": {"chdir": null, "command": "ssh-keygen -t rsa", "creates": null, "echo": true, "removes": null, "responses": {"Overwrite": "n", "file": "", "passphrase": ""}, "timeout": 5}, "module_name": "expect"}, "rc": 1, "start": "2015-12-30 09:56:29.164046", "stdout": "Generating public/private rsa key pair.\r\nEnter file in which to save the key (/home/admin/.ssh/id_rsa): \r\n/home/admin/.ssh/id_rsa already exists.\r\nOverwrite (y/n)? n", "stdout_lines": ["Generating public/private rsa key pair.", "Enter file in which to save the key (/home/admin/.ssh/id_rsa): ", "/home/admin/.ssh/id_rsa already exists.", "Overwrite (y/n)? n"]}

当 "Overwrite" 映射到 "y" 时,这确实工作正常。

This does work fine when "Overwrite" is mapped to "y".

如果是这样,那么您的任务似乎工作正常。 ssh-keygen只有文件已经存在才会提示覆盖,你在任务中对"Overwrite"的回复是"n"。如果您告诉 ssh-keygen 不要覆盖该文件,那么它将立即退出并显示 non-zero return 代码,Ansible 会将其解释为错误。

如果您只想在密钥不存在时执行此任务(以便创建新密钥但不覆盖现有密钥),那么您可能需要将以下内容添加到您的任务中:

creates: /home/admin/.ssh/id_rsa

如果指定的文件已经存在,creates修饰符将阻止任务执行。

我使用以下方法为具有正确访问权限的特定用户创建密钥:

- name: Create ssh key
  shell: |
    ssh-keygen -t rsa -N "" -f /home/{{ ansible_user }}/.ssh/id_ed25519 -C {{ ansible_user }}@{{ inventory_hostname }}
    chown {{ ansible_user }}:{{ ansible_user }} /home/{{ ansible_user }}/.ssh/id_ed25519*
  args:
    creates: '/home/{{ ansible_user }}/.ssh/id_ed25519'