This code is based on what was discussed in Rex Automation part 3, it allows you to reboot a server.


use strict;
use warnings;
use 5.010;

use Rex -feature => [qw(1.4 exec_autodie)];

use Rex::Commands::SimpleCheck;
# TODO qw(is_port_open);

sayformat "[%h]>\t%s";

task 'reboot', sub {
    Rex::Logger::info('uptime before');
    say run 'uptime';
    Rex::Logger::info('uptime after');
    say run 'uptime';

sub reboot {
    my %params = @_;
    $params{shutdown_timeout} //= 10;
    $params{boot_timeout} //= 10;

    my $server = connection->server;
    my $port   = Rex::Config->get_port( server => $server ) || 22;

    run 'reboot';

    Rex::Logger::info("Waiting for $params{shutdown_timeout} seconds for shutdown...");
    my $elapsed = 0;
    while ( is_port_open $server, $port ) {
        sleep 1;
        die "Could not shutdown in less than $params{shutdown_timeout}"
            if $params{shutdown_timeout} <= $elapsed;

    Rex::Logger::info("Waiting for $params{boot_timeout} second for the SSH service to come back...");
    $elapsed = 0;
    while ( !is_port_open $server, $port ) {
        sleep 1;
        die "Could not boot in less than $params{boot_timeout}"
            if $params{boot_timeout} <= $elapsed;


# vim: syntax=perl

Assuming you have a host with IP address where you can login as user root, this is the command you need to run:

rex -H -u root reboot

The output will look similar to this:

[2021-04-11 09:18:59] INFO - Running task reboot on
The authenticity of host ' (' can't be established.
ECDSA key fingerprint is SHA256:+z26G29adbKkq2iEuF07QEw9lrVG7U3r7oJrUnLMj7I.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
[2021-04-11 09:19:07] INFO - uptime before
[]>	 06:19:07 up 2 min,  0 users,  load average: 0.35, 0.35, 0.15
[2021-04-11 09:19:08] INFO - Waiting for shutdown...
Connection to closed by remote host.
[2021-04-11 09:19:09] INFO - Waiting for SSH to come back...
[2021-04-11 09:19:24] INFO - uptime after
[]>	 06:19:25 up 0 min,  0 users,  load average: 1.33, 0.28, 0.09
[2021-04-11 09:19:24] INFO - All tasks successful on all hosts

First I had to verify the ECDSA key fingerprint of the server because this was the first time I actually accessed this machine.

It showed the current uptime (2 min), yes I just started this server for the demo.

Then the reboot and then showing that the uptime is now 0 min.


Original gist for reboot that we used before starting the pair development session.

I personally think this, or an improved version of the reboot function should be inlcuded in the standard Rex distribution.