- Run the play as your safe user.
Run the play as your safe user.
- Be sure to set
gather_facts: noor or play will fail at this step withhost unreachableerror.
- Be sure to set
- With the first task, in order to check if the user already exists, you ping the server and ignore the host unreachable error:
With the first task, in order to check if the user already exists, you ping the server and ignore the host unreachable error:
- name: Check if safe user exists ansible.builtin.ping: register: result ignore_unreachable: true If the ping fails, using the default user you create the safe user, give it sudo rights and add SSH keys:
- name: Handle the error (missing user) when: result.failed == true vars: ansible_ssh_user: "{{ default_user }}" block: - ansible.builtin.meta: clear_host_errors - name: Create safe user ansible.builtin.user: name: "{{ safe_user }}" password: "{{ password | password_hash('sha512') }}" groups: - sudo - users append: true shell: "{{ shell }}" - name: Add Authorized key ansible.posix.authorized_key: user: "{{ safe_user }}" key: "{{ ssh_pub_key }}" exclusive: trueNow, the safe user should have SSH access and can delete the default user.
- name: Remove default user ansible.builtin.user: name: "{{ default_user }}" state: absentThe rest of the playbook can be run as the safe user. The playbook can also be re-run later. The ping will succeed and user creation will be skipped.
- name: Check if safe user exists
ansible.builtin.ping:
register: result
ignore_unreachable: true
- If the ping fails, using the default user you create the safe user, give it sudo rights and add SSH keys:
- name: Handle the error (missing user)
when: result.failed == true
vars:
ansible_ssh_user: "{{ default_user }}"
block:
- ansible.builtin.meta: clear_host_errors
- name: Create safe user
ansible.builtin.user:
name: "{{ safe_user }}"
password: "{{ password | password_hash('sha512') }}"
groups:
- sudo
- users
append: true
shell: "{{ shell }}"
- name: Add Authorized key
ansible.posix.authorized_key:
user: "{{ safe_user }}"
key: "{{ ssh_pub_key }}"
exclusive: true
- Now, the safe user should have SSH access and can delete the default user.
- name: Remove default user
ansible.builtin.user:
name: "{{ default_user }}"
state: absent
- Rest of the playbook can be run as the safe user. Playbook can also be re-run later, the ping will succeed and user creation will be skipped