Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Run commands when docker containers are started/terminated.
#!/usr/bin/perl -w
#
# This script watches for docker containers to be launched/stopped
# and lets you invoke scripts.
#
use strict;
use warnings;
#
# Ensure we have a start + stop directory
#
foreach my $dir (qw! /etc/docker.start.d/ /etc/docker.stop.d/ !)
{
print "WARNING: $dir missing\n" unless ( -d $dir );
}
#
# Read events
#
open( my $cmds, "-|", "docker events --since 0" );
while ( my $line = <$cmds> )
{
my ( $date, $id, $event ) = undef;
#
# Parse the line into tokens
#
if ( $line =~ /^\[([^]]+)\] ([^:]+):.*(create|die)/i )
{
$date = $1;
$id = $2;
$event = $3;
}
next unless ( $date && $id && $event );
#
# Setup the environment
#
$ENV{ 'DATE' } = $date;
$ENV{ 'ID' } = $id;
#
# Creation
#
if ( $event =~ /create/i )
{
system( "run-parts", "/etc/docker.start.d/" )
if ( -d "/etc/docker.start.d/" );
}
#
# Termination.
#
if ( $event =~ /die/i )
{
system( "run-parts", "/etc/docker.stop.d/" )
if ( -d "/etc/docker.stop.d/" );
}
}
close $cmds;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment