Important material first:
Don’t be me and do the manual method of ssh-key delivery, then learn the module exists after a day and a half of trouble-shooting.
Use this module, unless you are wanting to learn Ansible…. Then use the module after you learned it.
Authorized_keys modules

The playbook:

- hosts: whateverHosts
  gather_facts: False
  tasks:

    - name: set permissions for .ssh directory
      file:
            path: /home/user/.ssh 
            mode: 0700
            state: directory

    - name: insert public ssh key for user
      blockinfile:
            dest: /home/user/.ssh/authorized_keys
            create: yes
            mode: 0644
            block: |
                *Your SSH-key(s), here*

Command to run it:

ansible-playbook ssh_key.yml -k

This requires you to have the package “sshpass”. -k for asking ssh password (preventing password-less configuration).

Analysis:

  • hosts: Who will be receiving the keys.
    • This is set in /etc/ansible/hosts
    • looks like this
      [whateverHosts]
      192.168.1.67
      
  • gather_facts
    • By default, Ansible gathers facts about the computer for possible later use
    • False because it takes time, and is necessary.
    • Documentation for gather_facts
  • tasks
    • Section defining what gets done to hosts
  • file
    • Module for basic file management
    • Path for where the file is going to be located on remote machine
    • Mode for the permissions applied to the file
    • State for determining the state of the “file” (normally present or absent)
    • If you have a file with the same name as a directory you are trying to make, this will error
    • Documentation for file
  • blockinfile
    • Dest (interchangeable with path) is location of the file on remote device
    • Block checks if the “block” of text is in the file
    • Create makes the file if it doesn’t already exist
    • Documentation for blockinfile
  • Ideas for practice
    • Change /etc/ssh/sshd_config to deny password access and only your user
    • Learn lineinfile to check/add 1 key (can be different method for same thing)
    • Run a playbook on more than one host
    • Run this playbook on more than one hosts with different hostnames
    • Use ansible-vault to protect the playbook from clear-text