user1156544
user1156544

Reputation: 1807

Define which users belong to which host

I have an inventory:

[dbs]
server1.intranet

[webservices]
server2.intranet

[apps]
server3.intranet

And a file with variables:

users:
    - { name: user1, ssh_key: <SSH_KEY> }
    - { name: user2, ssh_key: <SSH_KEY> }  

(1) My first question is: How can I tell in the inventory which user is part of each server? (without having to copy and duplicate the user information at every host) Note that users can change and can belong to multiple servers.

(2) The final objective is to do some tasks at each host. For example, to create the users at each host, and add the corresponding user SSH key at each server, something like:

- name: SSH
  ansible.posix.authorized_key:
    user: "item.name"
    state: present
    key: "item.ssh_key"
    with_items: "{{ users[??] }}"

Of course the users variable should only have the users for the specific host iterating.

How can I do this?

Upvotes: 0

Views: 51

Answers (1)

Khaled
Khaled

Reputation: 838

I didn't understand your second point, but this solution could be helpful.
Define destination hosts as an array:

users:
    - { name: user1, ssh_key: <SSH_KEY>,hosts: ['test-001','test-002'] }
    - { name: user2, ssh_key: <SSH_KEY>,hosts: ['test-002'] }  

Use selectattr filter for your loop to search the running hostname in the hosts list defined in the vars:

- name: SSH
  ansible.posix.authorized_key:
    user: "{{ item.name }}"
    state: present
    key: "{{ item.ssh_key }}"
  loop: "{{ users | selectattr('hosts', 'search', inventory_hostname) }}"
ok: [test-001] => (item={'name': 'user1', 'ssh_key': '<SSH_KEY1>', 'hosts': ['test-001', 'test-002']}) => {
    "msg": "user1"
}
ok: [test-002] => (item={'name': 'user1', 'ssh_key': '<SSH_KEY1>', 'hosts': ['test-001', 'test-002']}) => {
    "msg": "user1"
}
ok: [test-002] => (item={'name': 'user2', 'ssh_key': '<SSH_KEY2>', 'hosts': ['test-002']}) => {
    "msg": "user2"
}

Upvotes: 2

Related Questions