Combine multiple public keys with Ansible - ansible

How can I combine multiple ssh public keys to use with Ansible's authorized_key module?
I have variables file containing users and keys:
ssh_users:
- name: peter
keys:
- 'ssh-rsa AAAAB3NzaC1yc2EAAA peter#key1'
- 'ssh-rsa AAAABsgsdfgyc2EAAA peter#key2'
root: yes
- name: paul
keys:
- 'ssh-rsa AAAAB3Nzaafac2EAAA paul#key1'
root: no
I'd like to go over this list, pick out users (and their keys) which have 'root: yes' and combine them to update root user's authorized_keys file.
This doesn't work:
- name: lookup keys
set_fact:
keylist: "{{ item.keys }}"
with_items: "{{ ssh_users }}"
when: item.root == true
register: result
- name: make a list
set_fact:
splitlist: "{{ result.results |
selectattr('ansible_facts','defined') | map(attribute='ansible_facts.keylist') | list | join('\n') }}"
- name: update SSH authorized_keys
authorized_key:
user: root
key: "{{ splitlist }}"
state: present
exclusive: yes

You can get what you want using the Jinja selectattr and map filters, like this:
---
- hosts: localhost
gather_facts: false
vars:
# Here's our data: two users with 'root' access,
# one without. We expect to see three public keys in
# the resulting authorized_keys file.
#
# Note that I've renamed the "keys" key to "pubkeys", because
# otherwise it conflicts with the "keys" method of dictionary
# objects (leading to errors when you try to access something
# like item.keys).
ssh_users:
- name: alice
pubkeys:
- 'ssh-rsa alice-key-1 alice#key1'
root: true
- name: peter
pubkeys:
- 'ssh-rsa peter-key-1 peter#key1'
- 'ssh-rsa peter-key-2 peter#key2'
root: true
- name: paul
pubkeys:
- 'ssh-rsa paul-key-1 paul#key1'
root: false
tasks:
- become: true
authorized_key:
user: root
key: "{{ '\n'.join(ssh_users|selectattr('root')|map(attribute='pubkeys')|flatten) }}"
state: present
exclusive: true
In the authorized_key task, we first use the selectattr filter to extract those users with root access. We pass that to the map filter to extract just the pubkeys attribute, which would give us two lists (one with one key, the other with two keys). Finally, we pass that to the flatten filter to create a single list, and then join the resulting keys with newlines to match the input format expected by the authorized_key module. The resulting .ssh/authorized_keys file looks like:
ssh-rsa alice-key-1 alice#key1
ssh-rsa peter-key-1 peter#key1
ssh-rsa peter-key-2 peter#key2

Is this the code you're looking for?
- name: update SSH authorized_keys
authorized_key:
user: root
key: "{{ item.1 }}"
loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"
when: item.0.root
You do not need parameters exclusive and state. Defaults exclusive: no and state: present are OK, I think.
Keys, where root: False, can be removed
- name: remove SSH authorized_keys
authorized_key:
state: absent
user: root
key: "{{ item.1 }}"
loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"
when: not item.0.root
To add and remove keys in one task ternary filter might be used
- name: Preen SSH authorized_keys
authorized_key:
state: "{{ item.0.root | ternary('present','absent') }}"
user: root
key: "{{ item.1 }}"
loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"

Related

ansible Iterate over list in list

I'm trying to adopt the task in the last answer from this post Ansible - managing multiple SSH keys for multiple users & roles
My variable looks like:
provisioning_user:
- name: ansible
state: present
ssh_public_keyfiles:
- ansible.pub
- user.pub
- name: foo
state: present
ssh_public_keyfiles:
- bar.pub
- key.pub
and my code looks like
- name: lookup ssh pubkeys from keyfiles and create ssh_pubkeys_list
set_fact:
ssh_pubkeys_list: "{{ lookup('file', item.ssh_public_keyfiles) }}"
loop: "{{ provisioning_user }}"
register: ssh_pubkeys_results_list
I want to store keys under the files directory and assign them with the variable to different users so that when a key changes, i only have to change the file and run the playbook instead of changing it in any hostvars file where the old key is used. But I get the following error and dont know how to solve it. I want to do this for every user defined in provisioning_user
fatal: [cloud.xxx.xxx]: FAILED! =>
msg: 'An unhandled exception occurred while running the lookup plugin ''file''. Error was a <class ''AttributeError''>, original message: ''list'' object has no attribute ''startswith''. ''list'' object has no attribute ''startswith'''
Can anyone please help me?
The file lookup reads the content of a single file, but you're passing it a list. That's not going to work, and is the direct cause of the error message you've reported.
You're also using both set_fact and register in the same task, which doesn't make much sense: the whole point of a set_fact task is to create a new variable; you shouldn't need to register the result.
Your life is going to be complicated by the fact that each user can have multiple key files. We need to build a data structure that maps each user name to a list of keys; we can do that like this:
- name: lookup ssh pubkeys from keyfiles
set_fact:
pubkeys: >-
{{
pubkeys |
combine({
item.0.name: pubkeys.get(item.0.name, []) + [lookup('file', item.1)]})
}}
vars:
pubkeys: {}
loop: "{{ provisioning_user|subelements('ssh_public_keyfiles') }}"
This creates the variable pubkeys, which is a dictionary that maps usernames to keys. Assuming that our provisioning_user variable looks like this:
provisioning_user:
- name: ansible
state: present
ssh_public_keyfiles:
- ansible.pub
- user.pub
- name: foo
state: present
ssh_public_keyfiles:
- bar.pub
- key.pub
- name: bar
state: present
ssh_public_keyfiles: []
After running the above task, pubkeys looks like:
"pubkeys": {
"ansible": [
"ssh-rsa ...",
"ssh-rsa ..."
],
"foo": [
"ssh-rsa ...",
"ssh-rsa ..."
]
}
We can use pubkeys in our authorized_keys task like this:
- name: test key
authorized_key:
user: "{{ item.name }}"
key: "{{ '\n'.join(pubkeys[item.name]) }}"
comment: "{{ item.key_comment | default('managed by ansible') }}"
state: "{{ item.state | default('true') }}"
exclusive: "{{ item.key_exclusive | default('true') }}"
key_options: "{{ item.key_options | default(omit) }}"
manage_dir: "{{ item.manage_dir | default('true') }}"
loop: "{{ provisioning_user }}"
when: item.name in pubkeys
I think your life would be easier if you were to rethink how you're managing keys. Instead of allowing each user to have a list of multiple key files, have a single public key file for each user -- named after the username -- that may contain multiple public keys.
That reduces your provisioning_user data to:
provisioning_user:
- name: ansible
state: present
- name: foo
state: present
- name: bar
state: present
And in our files/ directory, we have:
files
├── ansible.keys
└── foo.keys
You no longer need the set_fact task at all, and the authorized_keys task looks like:
- name: test key
authorized_key:
user: "{{ item.name }}"
key: "{{ keys }}"
comment: "{{ item.key_comment | default('managed by ansible') }}"
state: "{{ item.state | default('true') }}"
exclusive: "{{ item.key_exclusive | default('true') }}"
key_options: "{{ item.key_options | default(omit) }}"
manage_dir: "{{ item.manage_dir | default('true') }}"
when: >-
('files/%s.keys' % item.name) is exists
vars:
keys: "{{ lookup('file', '%s.keys' % item.name) }}"
loop: "{{ provisioning_user }}"
Note that in the above the when condition requires an explicit path, while the file lookup will implicitly look in the files directory.
These changes dramatically simplify your playbook.

Ansible can't loop through subelements in variables files

I have the following user lists in separated files.
The idea behind this is to create multiple users and assign them to different user groups.
To make it easier, I shortened the list. I reality they include passwords and etc.
First variables file
userlist-os:
group: os
users:
- comment: Test User
username: ostest1
user_id: 9404
user_state: present
- comment: Test User
username: ostest2
user_id: 9405
user_state: present
Second variables file
userlist-zos:
group: zos
users:
- comment: Test User1
username: zostest1
user_id: 9204
user_state: present
- comment: Test User2
username: zostest2
user_id: 9205
user_state: present
This is how my playbook looks like:
- name: test
hosts: all
user: root
vars_files:
- [userlist-zos.yml]
- [userlist-os.yml]
tasks:
- name: Create user accounts
user:
name: "{{ item.users.username }}"
update_password: on_create
uid: "{{ item.users.user_id }}"
shell: /bin/bash
create_home: yes
group: "{{ item.group }}"
state: present
comment: "{{ item.users.comment }}"
when: item.users.user_state == 'present'
with_items:
- "{{ userlist-os }}"
- "{{ userlist-zos }}"
The problem is that I'm not getting into the sub elements of users(variable username is undefined), but when I set an index like this name: "{{ item.users.0.username }}" I do get the first username from each file.
Any help is appreciated.
In your scenario, item.users are lists of users, they are not dictionaries. Therefore they don't have username field, they have list elements which have that field instead. You were able to access to first element of the list with "item.users.0.username". What I suggest you to do is to access these nested variables with an include_task variable as follows:
main.yaml
- name: Trial
hosts: localhost
vars:
# YOUR VARS
tasks:
- name: Create user accounts
include_tasks: helper.yml
with_items:
- "{{ userlistos }}"
- "{{ userlistzos }}"
loop_control:
loop_var: list
helper.yml
- name: Create user accounts
user:
name: "{{ item.username }}"
update_password: on_create
uid: "{{ item.user_id }}"
shell: /bin/bash
create_home: yes
group: "{{ list.group }}"
state: present
comment: "{{ item.comment }}"
when: item.user_state == 'present'
with_items:
- "{{list.users}}"

How to use the lookup plugin to get the directory path and file in Ansible

I have a two playbooks where one creates SSH Keys and the other one creates a new user and deploys the public ssh key for the new user created.
My issue is I created a task that create a new directory with a timestamp to store the relevant data, I was able to get the path to a variable where I added it as a dummy host so that I can be able to call that path with all my plays but it seems like I am unable to use the same variable in lookup so that I can be able to deploy the ssh key. Kindly assist, below are the relevant tasks.
# Create the directory with timestamp
- name: Create Directory with timestamp to store data that was run multiple times that day
when: inventory_hostname in groups['local']
file:
path: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}"
state: directory
mode: "0755"
register: dir_path
# Add the directory path to dummy host called save so that I can call it from other plays
- name: Add dir path:"{{dir_path.path}}" as a 'save' host
when: inventory_hostname in groups['local']
add_host:
name: "save"
dir: "{{dir_path.path}}"
# Deploying SSH Key I tried this -->
- name: Deploy Public Key to the server
when: inventory_hostname in groups['Servers']
authorized_key:
user: "{{hostvars['new-user']['user']}}"
state: present
key: "{{dir_path.path}}/SSH-Key.pub"
# ...this -->
- name: Deploy Public Key to the server
when: inventory_hostname in groups['Servers']
authorized_key:
user: "{{hostvars['new-user']['user']}}"
state: present
key: "{{ lookup('file','{{dir_path.path}}/SSH-Key.pub') }}"
# .... and this -->
- name: Deploy Public Key to the server
when: inventory_hostname in groups['Servers']
authorized_key:
user: "{{hostvars['new-user']['user']}}"
state: present
key: "{{ lookup('file','{{hostvars['save']['dir']}}/SSH-Key.pub') }}"
None of them worked, what am I doing wrong?
If you put a Jinja expression into a string in a Jinja expression, then you indeed end up with a your variable not being interpreted.
A basic example of this is:
- hosts: all
gather_facts: no
tasks:
- debug:
msg: "{{ '{{ foo }}' }}"
vars:
foo: bar
Which gives:
ok: [localhost] => {
"msg": "{{ foo }}"
}
When
- hosts: all
gather_facts: no
tasks:
- debug:
msg: "{{ foo }}"
vars:
foo: bar
Gives thes expected:
ok: [localhost] => {
"msg": "bar"
}
So in order to achieve what you want here, you should use the concatenation operator of Jinja: ~, in order to let Jinja interpret your variable and concatenate it with the rest of your "hardcoded" string.
Effectively ending with the instruction:
key: "{{ lookup('file', hostvars['save']['dir'] ~ '/SSH-Key.pub') }}"

Assign multiple public ssh keys to user definitions with authorized_key module in Ansible

Question:
Using Ansible, how can I set multiple public-key files (.pub) to be deployed in a user's authorized_keys file instead of using a single file containing a list of public ssh-keys?
Scenario and requirements:
I have multiple public ssh-keys stored as .pub files on a central location
I want to create new users from a vars file
each user shall have (none/one specific/multiple) public ssh-keys from the selection of .pub files deployed to their respective authorized_keys file
the list of deployed .pub files can change due to:
content of .pub file has changed due to eg. compromised private key
user in vars file shall have additional public key files assigned
I don't want to go through a "list" file for each user to replace a key
Currently deployed:
vars-file (vars/users.yml):
users:
- username: "bob"
sshkey: "{{ lookup('file', 'files/ssh_keys/bob.keys') }}"
...
- username: "alice"
sshkey: "{{ lookup('file', 'files/ssh_keys/alice.keys') }}"
...
contents of bob.keys:
ssh-rsa admin-ssh-key= admin
ssh-rsa support-a-ssh-key= support-a
ssh-rsa bobs-ssh-key= hi im bob
contents of alice.keys:
ssh-rsa admin-ssh-key= admin
ssh-rsa alice-ssh-key= hi im alice
ssh-rsa accounting-clerk-ssh-key= checking your progress
ansible role main.yml file:
- name: Add SSH keys
authorized_key:
user: "{{ item.username }}"
state: "{{ item.sshkeystate }}"
key: "{{ item.sshkey }}"
exclusive: yes
with_items: "{{ users }}"
tags: [add ssh keys]
Problem Scenario:
support-a's ssh key got compromised and all users having that public key in their authorized_keys file need to be replaced with the new public key
I need to (sed) through all keys files and replace the compromised public key with the new one
I tried:
vars-file:
users:
- username: "bob"
sshkey:
- "{{ lookup('file', 'files/ssh_keys/admin.pub') }}"
- "{{ lookup('file', 'files/ssh_keys/support_a.pub') }}"
- "{{ lookup('file', 'files/ssh_keys/bob.pub') }}"
...
- username: "alice"
sshkey:
- "{{ lookup('file', 'files/ssh_keys/admin.pub') }}"
- "{{ lookup('file', 'files/ssh_keys/alice.pub') }}"
- "{{ lookup('file', 'files/ssh_keys/accounting_clerk.pub') }}"
However, I'm getting this error when executing the ansible role:
"msg": "invalid key specified: ['ssh-rsa admin-ssh-key= admin', 'ssh-rsa support-a-ssh-key= support-a', 'ssh-rsa bobs-ssh-key= hi im bob']"
I also tried something along the lines of this ( https://stackoverflow.com/a/54079374 ) solution but I guess the scenario and requirements are a bit different and there is nothing to selectattr() in my scenario (I think).
Can anyone point me to how to solve this or am I going in a completely wrong direction?
Cheers.
As best I can tell, the only part that differs in your playbook from the one you linked to is the "\n".join() part, which folds the list into one text block. As ansible correctly points out, you are providing a list[str] to an attribute that expects str
I don't believe in your circumstance you need to use selectattr or any filtering, because you want all the keys all the time. Thus:
- name: Add SSH keys
authorized_key:
user: "{{ item.username }}"
state: "{{ item.sshkeystate }}"
key: '{{ item.sshkey | join("\n") }}'
exclusive: yes
with_items: "{{ users }}"
tags: [add ssh keys]

Ansible - failed to lookup user

How can I solve problem with run ansible role below? If a user doesn't exist on the remote server, ansible gets me the error "Failed to lookup user test1: 'getpwnam(): name not found: test1". I need manage multiple users on multiple servers. Thanks
vars:
user_list:
- user: test1
state: present
path: /usr/local/test1/.ssh/authoried_keys
keys:
- "ssh-rsa test1"
- user: test2
state: absent
path: /home/test2/.ssh/authoried_keys
keys:
- "ssh-rsa test2"
tasks:
- name: Manage SSH-keys
authorized_key:
user: "{{ item.0.user }}"
key: "{{ item.1 }}"
path: "{{ item.0.path }}"
state: "{{ item.0.state }}"
with_subelements:
- '{{ user_list }}'
- keys
CentOS Linux 7, Ansible 2.4.2.0
Perhaps you could check the existing users through ansible's wrapper for getent?
It feels a bit simpler and you don't need to use the shell module:
tasks:
- name: Get existing users
getent:
database: passwd
- name: Disable expired users
user:
name: "{{ item.name }}"
shell: /sbin/nologin
with_items:
- "{{ users_removed }}"
when: item.name in getent_passwd.keys()
Note though that as #techraf points out, at production environments you should always aim at declaring and knowing beforehand which users should and shouldn't be present :)
I think, that I solved my problem.
tasks:
- name: Check for users
shell: cat /etc/passwd | cut -f1 -d":"
register: sshkeys_users
changed_when: False
- name: Manage SSH-keys
authorized_key:
user: "{{ item.0.user }}"
key: "{{ item.1 }}"
path: "{{ item.0.path }}"
state: "{{ item.0.state }}"
with_subelements:
- '{{ user_list }}'
- keys
when: sshkeys_users is defined and item.0.user in sshkeys_users.stdout_lines

Resources