Skip to content

Latest commit

 

History

History
98 lines (77 loc) · 4.57 KB

File metadata and controls

98 lines (77 loc) · 4.57 KB

Ansible Role jm1.cloudy.ssh_authorized_keys

This role helps with managing SSH authorized keys from Ansible variables. It allows to add, modify and delete SSH public keys e.g. from ~/.ssh/authorized_keys with variable ssh_authorized_keys. This variable is defined as a list where each list item is a dictionary of parameters that will be passed to Ansible's authorized_key module. For example, to ensure that public SSH keys of the current user who runs Ansible on the Ansible controller is present on an Ansible host, define variable ssh_authorized_keys in group_vars or host_vars as such:

ssh_authorized_keys_default: |
  {% for type in ['dsa', 'ecdsa', 'ed25519', 'rsa'] %}
  {% set path = lookup('env','HOME') + '/.ssh/id_' + type + '.pub' %}
  {% set found = lookup('first_found', path, errors='ignore') | default('', true) | length > 0 %}
  {% if found %}
  - comment: "{{ lookup('pipe','whoami') + '@' + lookup('pipe','hostname') + ':' + path }}"
    key: "{{ lookup('file', path) }}"
    state: present
    user: '{{ ansible_user }}'
  {% endif %}
  {% endfor %}

ssh_authorized_keys: '{{ ssh_authorized_keys_default | from_yaml }}'

When this role is executed, it will pass each item of the ssh_authorized_keys list one after another as parameters to Ansible's authorized_key module.

Tested OS images

Available on Ansible Galaxy in Collection jm1.cloudy.

Requirements

None.

Variables

Name Default value Required Description
ssh_authorized_keys [] false List of parameter dictionaries for Ansible's authorized_key module

Dependencies

None.

Example Playbook

- hosts: all
  become: true
  vars:
    # Variables are listed here for convenience and illustration.
    # In a production setup, variables would be defined e.g. in
    # group_vars and/or host_vars of an Ansible inventory.
    # Ref.:
    # https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html
    # https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html
    ssh_authorized_keys:
    - # Add SSH public keys from jm1's github account
      key: https://github.com/jm1.keys
      state: present
      user: ansible
  roles:
  - name: Setup SSH authorized keys
    role: jm1.cloudy.ssh_authorized_keys
    tags: ["jm1.cloudy.ssh_authorized_keys"]

For instructions on how to run Ansible playbooks have look at Ansible's Getting Started Guide.

License

GNU General Public License v3.0 or later

See LICENSE.md to see the full text.

Author

Jakob Meng @jm1 (github, galaxy, web)