3

I am using Ansible to create ssh keys on remote hosts. Following is the playbook code

- 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)

However, it get the following error:

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"]}

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

2 Answers 2

1

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

If that's the case then it sounds like your task is working properly. ssh-keygen will only prompt to overwrite the file if it already exists, and your response to "Overwrite" in the task is "n". If you tell ssh-keygen to not overwrite the file then it will exit immediately with a non-zero return code, which Ansible interprets as an error.

If you only want this task to execute when the key doesn't exist (in order to create a new key but not overwrite an existing one) then you probably want to add the following to your task:

creates: /home/admin/.ssh/id_rsa

The creates modifier will prevent the task from executing if the specified file already exists.

0
0

I used the following, to create keys for a specific user with the right access rights:

- 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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.