VMware {code} Community
Humphry
Contributor
Contributor

triggering actions on events

Hi, I'm trying to find a way to trigger actions (executing scripts, writting data in a database, etc.) when certain events occurs (like starting up a VM, shutting it down, creating a snapshot, etc.).

Do you know if it's possible to do this??? If so, how could I do it??? I'm reading the documentation and I'm not sure wether I can do it.

Thanks.

Tags (3)
0 Kudos
1 Reply
piuhapofuhpaosf
Contributor
Contributor

Here's some code that will create alarms that execute a script that is located on the VC server when a VM is either migrated or moved. It could certainly be adapted for VM startups, I would think. The code assumes $vm_view is already defined as a Virtual Machine view object. Also, "ALARM_SCRIPT" is a constant defined previously like so:

use constant ALARM_SCRIPT => 'C:\VMware\VMwareCLI\Perl\bin\Perl.exe ' .

'C:\VMware\VMwareCLI\scripts\migrate_event.pl ';

So basically what this alarm does is that anytime the VM is migrated by DRS within a cluster, it runs the script located at C:\VMware\VMwareCLI\scripts\migrate_event.pl. Obviously we installed the VMwareCLI on the VC server for this script to be able to run. This script in turn communicates with our database server to update some data there.There are quite a number of eventTypes you can specify for the EventAlarmExpression object, including events dealing with VM powerOn/Off actions.

my $alarm_script = ALARM_SCRIPT . '"' . $this->name . '"';

my $alarmMgr = $vim->get_service_content()->alarmManager;

my $alarm = $vim->get_view(mo_ref => $alarmMgr);

my $al_refs = $alarm->GetAlarm(entity=>$vm_view);

my $alarms = $vim->get_views(mo_ref_array => $al_refs);

my %alarm_hash;

foreach my $a (@$alarms) {

$alarm_hash{$this->name . ' Migrated'}++ if ($a->info->name =~ m/ Migrated$/);

$alarm_hash{$this->name . ' Moved'}++ if ($a->info->name =~ m/ Moved$/);

}

my $alarmExpr = EventAlarmExpression->new (eventType=>'VmMigratedEvent');

my $alarmExpr2 = EventAlarmExpression->new(eventType=>'VmRelocatedEvent');

my $alarmAction = RunScriptAction->new(

script => $alarm_script

);

my $alarmTrigger = AlarmTriggeringAction->new(

action => $alarmAction,

red2yellow => 1,

green2yellow => 1,

yellow2red => 1,

yellow2green => 1

);

my $alarmSpec = AlarmSpec->new(

name => $this->name . ' Migrated',

description => 'Trigger to run script when VM is migrated' ,

enabled => 1,

expression => $alarmExpr,

action => $alarmTrigger,

);

my $alarmSpec2 = AlarmSpec->new(

name => $this->name . ' Moved',

description => 'Trigger to run when VM is moved',

enabled => 1,

expression => $alarmExpr2,

action => $alarmTrigger,

);

my $newAlarm = $alarm->CreateAlarm(entity=>$vm_view,spec=>$alarmSpec) if (! $alarm_hash{$this->name . ' Migrated'});

my $newAlarm2 = $alarm->CreateAlarm(entity=>$vm_view,spec=>$alarmSpec2) if (! $alarm_hash{$this->name . ' Moved'});

Hopefully this might be of some use to you.

0 Kudos