Ansible - managing multiple SSH keys for multiple users & roles

爱⌒轻易说出口 提交于 2019-12-04 06:49:33

I found this question in the list of unanswered questions and did a little research. It looks like the diff functionality was added to the authorized_keys module in ansible not long after your question. The commit was merged early in 2017 and appear to have been included in version 2.3 and later. It looks like your third option should work now, but without your key setup, I can't be sure.

https://github.com/ansible/ansible/commit/b0b7a636d8930a2c7192ea83ff890e4313aaf4d9#diff-e50c31b8374987e7c9dd4795d7f2e89f

https://github.com/ansible/ansible/pull/19277

The way I solved this was to pass an array of filenames in a variable to my user-account role. The role then gets the contents of each of these files, appends them together into a newline-separated string, then finally sets this value to be the ssh-key for the new user.

.

The playbook file:

- hosts: aws-node1
  roles:
    - { role: user-account, username: 'developer1', ssh_public_keyfiles: ['peter-sshkey.pub', 'paul-sshkey.pub'] }

.

The role definition for user-account:

- name: add user
  user:
    name: "{{username}}"


- name: lookup ssh pubkeys from keyfiles and create ssh_pubkeys_list
  set_fact:
    ssh_pubkeys_list: "{{ lookup('file', item) }}"
  with_items:
    "{{ssh_public_keyfiles}}"
  register: ssh_pubkeys_results_list


- name: iterate over ssh_pubkeys_list and join into a string
  set_fact:
    ssh_pubkeys_string: "{{ ssh_pubkeys_results_list.results | map(attribute='ansible_facts.ssh_pubkeys_list') | list | join('\n') }}"


- name: update SSH authorized_keys for user {{ username }} with contents of ssh_pubkeys_string
  authorized_key:
    user: "{{ username }}"
    key: "{{ ssh_pubkeys_string }}"
    state: present
    exclusive: yes
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!