How to upload ssh public key to as authorized_key using Ansible

Here’s how you can upload an SSH public key as an authorized_key using Ansible:

  1. Create a new playbook in Ansible:
nano upload_key.yml
  1. Add the following content to the playbook to upload an SSH public key:
- name: Upload SSH public key
hosts: <host_group>
become: yes
become_user: <username>

tasks:
- name: Create authorized_keys file
authorized_key:
user: <username>
key: "<public_key>"
state: present

  1. Replace <host_group> with the name of the host group to which you want to apply this playbook.
  2. Replace <username> with the username of the user for whom you want to upload the public key.
  3. Replace <public_key> with the contents of your SSH public key. Make sure to enclose the key in double quotes.
  4. Save the changes and exit the Nano text editor.
  5. Run the playbook using the following command:
ansible-playbook upload_key.yml

The playbook will upload the SSH public key as an authorized_key for the specified user on the specified host group. This will allow the user to log in to the remote host using the private key corresponding to the public key.

Leave a Comment