A
A
Andrey2016-07-11 14:56:48
SSH
Andrey, 2016-07-11 14:56:48

Ansible + SSH keys, how to do it?

You need to deploy keys to servers, but the trick is that there are a lot of keys and they should not all fall on all servers. Now it is implemented as follows.
in file roles/authorized_keys/vars/main.yml

ssh_users:
  - name: pupkin
    key: "{{ lookup('file', 'roles/authorized_keys/vars/pupkin.pub') }}" 
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/user.pub') }}"
    state: absent

in the task: roles/authorized_keys/tasks/main.yml
- name: Add ssh key.
    authorized_key: user={{ item.name }} key="{{ item.key }}" state={{ item.state }}
    with_items: ssh_users

in playbook: authorized_keys.yml
---
- hosts: '{{ hosts }}'
  vars_files:
    - '{{ vars }}'
  roles:
    - { role: authorized_keys }

Before starting, I edit: roles/authorized_keys/vars/main.yml , present or absent
And when starting, I specify host groups or hosts. At first everything was fine, but now there are more keys and servers, I don’t remember whose key should be on which server. It would be nice if, for example, it was possible like this, in the file roles/authorized_keys/vars/main.yml
- name: pupkin
    key: "{{ lookup('file', 'roles/authorized_keys/vars/pupkin.pub') }}" 
    servers: web,database,12.12.12.12
    state: present

So that for each key there is a list of servers where to drop them.
Or maybe there is another way to implement it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory, 2017-01-19
@gerasimov

actually nothing prevents you from doing this, you need to change the description of the keys in roles/authorized_keys/vars/main.yml like this:

ssh_users:
  - name: pupkin
    key: "{{ lookup('file', 'roles/authorized_keys/vars/pupkin.pub') }}" 
    servers: 
      - host1
      - host2
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/guru.pub') }}"
    servers: 
      - host1
      - host2
    state: present
  - name: root
    key: "{{ lookup('file', 'roles/authorized_keys/vars/user.pub') }}"
    servers: 
      - host3
      - host4
    state: absent

and add a condition to roles/authorized_keys/tasks/main.yml :
- name: Add ssh key.
    authorized_key: user="{{ item.name }}" key="{{ item.key }}" state="{{ item.state }}"
    when: "inventory_hostname in item.servers"
    with_items: "{{ ssh_users }}"

at the same time, the names listed in servers must match what is written in inventory

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question