passwordless_ssh.yml 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright 2020 Dell Inc. or its subsidiaries. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. ---
  15. - name: Initialize variables
  16. set_fact:
  17. ssh_status: false
  18. current_host: "{{ item }}"
  19. - name: Verify whether passwordless ssh is set on the remote host
  20. command: ssh -o PasswordAuthentication=no root@"{{ current_host }}" 'hostname'
  21. register: ssh_output
  22. ignore_errors: yes
  23. changed_when: False
  24. - name: Update ssh connection status
  25. set_fact:
  26. ssh_status: true
  27. when: "'Permission denied' not in ssh_output.stderr"
  28. - name: Verify the public key file existence
  29. stat:
  30. path: "{{ rsa_id_file }}"
  31. register: verify_rsa_id_file
  32. when: not ssh_status
  33. - name: Generate ssh key pair
  34. command: ssh-keygen -t rsa -b 4096 -f "{{ rsa_id_file }}" -q -N "{{ passphrase }}"
  35. when:
  36. - not ssh_status
  37. - not verify_rsa_id_file.stat.exists
  38. - name: Add the key identity
  39. shell: |
  40. eval `ssh-agent -s`
  41. ssh-add "{{ rsa_id_file }}"
  42. when: not ssh_status
  43. - name: Post public key
  44. block:
  45. - name: Create .ssh directory
  46. command: >-
  47. sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
  48. ssh root@"{{ current_host }}" mkdir -p /root/.ssh
  49. when: not ssh_status
  50. no_log: True
  51. register: register_error
  52. - name: Copy the public key to remote host
  53. shell: >-
  54. set -o pipefail && cat "{{ rsa_id_file }}".pub
  55. | sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}"
  56. ssh root@"{{ current_host }}" 'cat >> "{{ auth_key_path }}"'
  57. when: not ssh_status
  58. no_log: True
  59. register: register_error
  60. - name: Change permissions on the remote host
  61. shell: sshpass -p "{{ hostvars['127.0.0.1']['cobbler_password'] }}" ssh root@"{{ current_host }}" 'chmod 700 .ssh; chmod 640 "{{ auth_key_path }}"'
  62. when: not ssh_status
  63. no_log: True
  64. register: register_error
  65. rescue:
  66. - name: Passwordless ssh failed
  67. fail:
  68. msg: "{{ register_error.stderr | regex_replace(hostvars['127.0.0.1']['cobbler_password']) | regex_replace(auth_key_path) }}"