How can I deploy multiple ssh_key for multiple users on multiple servers with Ansible?

2.9k views Asked by At

My environment is composed of 2 web servers and 2 db servers.

I have a new developer coming in my team. I need to deploy his ssh key on every server.

He must be able to connect with both user ubuntu and www-data on the web servers and with user ubuntu on the db servers.

My servers are provisioned with Ansible.

How can I do it ?

2

There are 2 answers

1
Raphaël On BEST ANSWER

I solved it by creating a ssh-keys task like so.

In roles/ssh-keys/tasks/main.yml:

---
- name: add authorized key
  authorized_key: user={{ item }} key="{{ lookup('file', 'authorized_keys') }}"
  with_items: authorized_ssh_users
  when: authorized_ssh_users is defined

In roles/ssh-keys/files/authorized_keys:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[ssh_pub_key_of_dev1] dev1
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[ssh_pub_key_of_dev2] dev2
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[ssh_pub_key_of_dev3] dev3

In hosts/production:

[webservers]
webserv1-hostname
webserv2-hostname

[webservers:vars]
authorized_ssh_users=['ubuntu','www-data']

[dbservers]
dbserv1-hostname
dbserv2-hostname

[dbservers:vars]
authorized_ssh_users=['ubuntu']

Then in playbook.yml:

- name: Provision ssh keys
  hosts: all
  sudo: true
  roles:
  - ssh-keys

With this solution, I can manage every combination of server / user to deploy key on.

0
MillerGeek On

This role will work quite nicely for you. Working on getting this into Galaxy, but it's not importing for some reason.

https://github.com/smiller171/ansible-user-management

This role is set up so you just pass in variables for users and groups that you want, as well as any users you want to delete, like so:

---
- hosts: all
  sudo: yes
  roles:
  - scott.miller171.manage_users
  vars:
  - manage_users_allowed:
    - name: foo
      authorized:
      - "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAlPYybp3CWDzRPo0uF/woyqkfhpZK2T7zn16z+fGYlRQl6gXATIUB4JYfr9pfD+SOW2T4X78P+/h1o4QPCwoesLacaFEFGwUb+SzhVVm6B6q4WMAiJWD6OVXh+SVVvD9rdcz5RMVLqQngrRqBlj4kBIMQ3S8h1cCESbR2P6jszgFj0I6p3tQCpo9yjcVwLqvWFKJgzEm2E2wV/gmrc0PhVRP2guIRN4p6M2ZyIPprdZ6PA8m7Rs4yN3jQ/0alrQ23ECCU4lHoVG9fwvLIq1vh4ikPcUrdA8sSHTE1pkpzvrTv7FtkuUcBrDMedFE7E8dB9pPS+vXIBWVUYJhp9WzVkQ== [email protected]"

  - manage_users_unauthorized:
    - foobar

  - manage_users_groups: "sudo,adm,dialout,cdrom,floppy,audio,video,plugdev"