From 926a98840cfac989e701c2290e66a528ce4282ac Mon Sep 17 00:00:00 2001 From: Frank Dornheim <524257+conloos@users.noreply.github.com> Date: Fri, 10 Mar 2023 18:10:54 +0100 Subject: [PATCH] Refactored: Check for ssh-key if not present, genereate them. --- tasks/03_create_key.yml | 69 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 tasks/03_create_key.yml diff --git a/tasks/03_create_key.yml b/tasks/03_create_key.yml new file mode 100644 index 0000000..2077550 --- /dev/null +++ b/tasks/03_create_key.yml @@ -0,0 +1,69 @@ +--- +- name: Create ssh-key (if neeeded) for {{ borgbackup_user }} + when: + - install_backup is not defined or install_backup + - backup_id_rsa is not defined or backup_id_rsa | length == 0 + tags: + - install_backup + block: + - name: Ensire directory exist + ansible.builtin.file: + path: "{{ backup_user_info.home }}/.ssh/" + state: directory + mode: "0700" + owner: "{{ borgbackup_user }}" + group: "{{ borgbackup_group }}" + + - name: Generate an OpenSSH keypair with the default values (4096 bits, rsa) + community.crypto.openssh_keypair: + path: "{{ backup_user_info.home }}/.ssh/id_rsa" + mode: "0600" + owner: "{{ borgbackup_user }}" + group: "{{ borgbackup_group }}" + + - name: Set key permission + ansible.builtin.file: + path: "{{ backup_user_info.home }}/.ssh/id_rsa.pub" + mode: "0644" + owner: "{{ borgbackup_user }}" + group: "{{ borgbackup_group }}" + + - name: Read ssh key + ansible.builtin.slurp: + src: "{{ backup_user_info.home }}/.ssh/id_rsa.pub" + register: backup_local_ssh_key + + - name: Set authorized key taken from file + ansible.posix.authorized_key: + user: "{{ backup_repository | regex_search('(.*)@', '\\1') | first }}" + state: present + key: "{{ backup_local_ssh_key['content'] | b64decode }}" + # This is a bit tricky, the string backup_repository consists of three parts: + # "username"@"FQDN":"path/to/store/backup". + # With the regex we use the FQDN part to store the ssh-key on the target system. + delegate_to: "{{ backup_repository | regex_search('@(.*):', '\\1') | first }}" + +- name: Install ssh cert and key for user + when: + - install_backup is not defined or install_backup + - backup_id_rsa is defined and backup_id_rsa | length > 0 + - backup_id_rsa_pub is defined and backup_id_rsa_pub | length > 0 + tags: + - install_backup + block: + - name: Copy existing id_rsa, not genereting one + ansible.builtin.copy: + content: "{{ backup_id_rsa }}" + dest: "{{ backup_user_info.home }}/.ssh/id_rsa" + mode: "0600" + owner: "{{ borgbackup_user }}" + group: "{{ borgbackup_group }}" + + - name: Copy existing id_rsa.pub, not genereting one + ansible.builtin.copy: + content: "{{ backup_id_rsa_pub }}" + dest: "{{ backup_user_info.home }}/.ssh/id_rsa.pub" + mode: "0644" + owner: "{{ borgbackup_user }}" + group: "{{ borgbackup_group }}" +...