Reputation: 1145
We need to reboot a Linux server if nobody is logged in.
ansible.builtin.reboot
doesn't seem to have an option to check for that.
Does Ansible have a way of checking if there are users logged in (kind of a who
command)?
Upvotes: 0
Views: 559
Reputation: 12080
You can just use the who
command
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- name: Gather logged in user
shell:
cmd: who | cut -d " " -f 1
register: result
changed_when: false
check_mode: false
- name: Show result
debug:
var: result.stdout_lines
when: result.stdout_lines | length > 1
and may check the return values as in the example given and perform further tasks like
- name: Reboot if required
reboot:
reboot_timeout: 150
when: reboot_allowed # or result.stdout_lines | length < 2
Upvotes: 1
Reputation: 9412
To find out who is currently logged in you have a number of options in linux itself. On https://linuxhandbook.com/linux-logged-in-users/ you can find these commands:
w
who
users
finger
Use a shell module to run the command and count the lines. This could roughly look like this (I did not run these commands to check):
- name: count logged in users
shell: "who | wc --lines"
register: usercount
- name: reboot if noone is logged on
command: /sbin/reboot
when: "usercount.stdout < 2"
Upvotes: 1