I want to create a cluster infrastructure that each node communicates with others over shh. I want to use ansible to create a idempotent playbook/role that can be executed when cluster initialized or new nodes added to cluster. I was able to think of 2 scenarios to achieve this.
First Scenario
task 1
fetches the ssh key from a node (Probably assigns it to a variable or writes to a file).- Then
task 2
that executed locally loops over other nodes and authorizes the first node with fetched key.
This scenario supports free strategy. Tasks can be executed without waiting for all hosts. But it also requires all nodes to have related user and public key. Because if you are creating users within the same playbook (due to free strategy), when the task 2
starts running there may be users that are not created on other nodes in the cluster.
Although i am a big fan of free strategy, i din't implement this scenario due to efficiency reasons. It makes connections for
node cluster.
Second Scenario
task 1
fetches the ssh key from all nodes in order. Then writes each one to a file which name is set according toansible_hostname
.- Then
task 2
that executed locally loops over other nodes and authorizes all keys.
This scenario only supports linear strategy. You can create users within same playbook thanks to linear strategy, all users will be created before task 1
starts running.
I think it is an efficient scenario. It makes only connections for
node cluster. I did implement it and i put the snippet i wrote.
---
- name: create node user
user:
name: "{{ node_user }}"
password: "{{ node_user_pass |password_hash('sha512') }}"
shell: /bin/bash
create_home: yes
generate_ssh_key: yes
- name: fetch all public keys from managed nodes to manager
fetch:
src: "/home/{{ node_user }}/.ssh/id_rsa.pub"
dest: "tmp/{{ ansible_hostname }}-id_rsa.pub"
flat: yes
- name: authorize public key for all nodes
authorized_key:
user: "{{ node_user }}"
key: "{{ lookup('file', 'tmp/{{ item }}-id_rsa.pub')}}"
state: present
with_items:
- "{{ groups['cluster_node'] }}"
- name: remove local public key copies
become: false
local_action: file dest='tmp/' state=absent
changed_when: false
run_once: true
Maybe i can use lineinfile instead of fetch but other than that i don't know if it is the right way. It takes so long when cluster size getting larger (Because of the linear strategy). Is there a more efficient way that i can use?