Search code examples
ansibleenvironment-variablesssh-keys

How can I install multiple ssh public keys from environment variable?


I'm writing a little playbook I want to share with some people. This playbook needs one or more ssh public keys to install on ansible nodes.

To make it easier to customize, I thought setting SSH public keys in an environment variable would be the best solution, but I can study any better proposal.

So, users just have to set this:

export ANSIBLE_SSH_PUBKEY=${HOME}/.ssh/my_ssh_key.pub

And in the playbook, this is handled like this:

- name: Install ssh public key
  ansible.posix.authorized_key:
    user: ansible
    state: present
    key: '{{ item }}'
  with_file: '{{ lookup("env", "ANSIBLE_SSH_PUBKEY") }}'

Currently, I only manage one ssh public key installation.
So, my question is: how can I do to handle any number of public keys?


Solution

  • Either allow them to import all their public key, with a with_fileglob loop instead:

    export ANSIBLE_SSH_FOLDER=~/.ssh
    
    - name: Install ssh public key
      ansible.posix.authorized_key:
        user: ansible
        state: present
        key: '{{ item }}'
      with_fileglob: '{{ lookup("env", "ANSIBLE_SSH_FOLDER") }}/*'
    

    Or allow them for a colon separated value, then split the environment variable on that separator:

    export ANSIBLE_SSH_PUBKEY=~/.ssh/my_ssh_key.pub:~/.ssh/my_other_ssh_key.pub
    
    - name: Install ssh public key
      ansible.posix.authorized_key:
        user: ansible
        state: present
        key: '{{ item }}'
      with_file: '{{ (lookup("env", "ANSIBLE_SSH_PUBKEY")).split(":") }}'