I’m not good with Ansible and have been working with this playbook mess for a while now.
My goal is to pull a list of Sudo users in Ubuntu servers and put them all in a single dictionary object which would get emailed to me. It would look something like this for example:
server1: bob, joe, admin
server2: josh, service2
etc…
This is the playbook I have so far:
- name: root users
hosts: ubuntu
become: true
become_user: root
gather_facts: no
#I created root_users dictionary to hold all the root users of
#each server
vars:
root_users: {}
- name: Get root users
ansible.builtin.shell:
cmd: getent group sudo | cut -d{{':'}} -f4
register: usersStdOut
#I did this to store only the list of users. Otherwise usersStdOut
returns a dictionary.
- set_fact:
users: "{{ usersStdOut.stdout }}"
- name: test type
debug:
msg:
- "value: '{{ users }}' is of type: {{ users | type_debug }}"
- debug:
var: users
- name: Add root users to dictionary
set_fact:
root_users: "{{ root_users | combine({item: 'users'}) }}"
with_items: "{{ users }}"
- name: List of Ubuntu root users per host
ansible.builtin.debug:
var: sudo_users
- name: Send email containing root users
delegate_to: localhost
run_once: true
community.general.mail:
[redacted]
This is my output
TASK [Get root users]
**********************************************************
changed: [server1]
changed: [server2]
TASK [set_fact]
**********************************************************
ok: [server1]
ok: [server2]
# Maybe this task is causing me problems given the type of
# the variable?
TASK [test type]
**********************************************************
ok: [server1] => {
"msg": [
"value: 'bob,joe,admin' is of type: AnsibleUnsafeText"
]
}
ok: [server2] => {
"msg": [
"value: 'josh,service2' is of type: AnsibleUnsafeText"
]
}
TASK [debug]
**********************************************************
ok: [server1] => {
"users": "bob,joe,admin"
}
ok: [server2] => {
"users": "'josh,service2"
}
TASK [Add root users to dictionary]
**********************************************************
ok: [server1] => (item=bob,joe,admin)
ok: [server2] => (item=josh,service2)
# How can I stop "users" from being added at the end?
TASK [List of Ubuntu root users per host]
**********************************************************
ok: [server1] => {
"sudo_users": {
"bob,joe,admin": "users"
}
}
ok: [server2] => {
"sudo_users": {
"'josh,service2": "users"
}
}
TASK [Send email containing root users]
**********************************************************
ok: [server1 -> localhost]
ok: [server2-> localhost]
I get a separate email from each server but I only want one email sent for all servers. The email lists the users like this:
"{'bob,joe,admin': 'users'}"
How can I get them to show up like this with the name of the server before the user list?
"{'bob,joe,admin'}"