VMware vSphere/Snapshots automatisiert löschen

From wiki.krogloth.de
Jump to: navigation, search

1 Beschreibung

Das folgende Skript löscht alle Snapshots mit einem bestimmten Namen, in diesem Fall alle Snapshots die "VEEAM BACKUP TEMPORARY SNAPSHOT" heißen und älter als ein Tag sind.

2 Usage

./remove_snapshots.pl

3 Code

  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5. use lib "/usr/lib/vmware-vcli/apps";
  6. use VMware::VIRuntime;
  7. use Date::Parse;
  8. use AppUtil::VMUtil;
  9.  
  10. my @badsnaps = ();
  11.  
  12. Opts::parse();
  13. Opts::validate();
  14. Util::connect();
  15.  
  16. my $sc = Vim::get_service_content();
  17.  
  18. my $vms = Vim::find_entity_views(
  19.     view_type => 'VirtualMachine',
  20. );
  21.  
  22. sub older_than_treshold {
  23.   my $created = shift;
  24.  
  25.   if ((time() - $created) > 86400) {
  26.      return 1;
  27.   }
  28.   return 0;
  29. }
  30.  
  31. sub check_snaplist {
  32.   my $vm_name = shift;
  33.   my $vm_snaplist = shift;
  34.  
  35.   foreach my $vm_snap (@{$vm_snaplist}) {
  36.     if ($vm_snap->{childSnapshotList}) {
  37.       check_snaplist($vm_name, $vm_snap->{childSnapshotList});
  38.     }
  39.  
  40.     my $epoch_snap = str2time($vm_snap->{createTime});
  41.     next unless (older_than_treshold($epoch_snap));
  42.     $badsnaps[scalar(@badsnaps)] = {
  43.       'vm' => $vm_name,
  44.       'snap' => $vm_snap->{name},
  45.       'date' => $epoch_snap,
  46.       };
  47.   }
  48. }
  49.  
  50. foreach my $vm_view (@{$vms}) {
  51.   my $vm_name     = $vm_view->{summary}->{config}->{name};
  52.   my $vm_snapinfo = $vm_view->{snapshot};
  53.  
  54.   next unless defined $vm_snapinfo;
  55.   check_snaplist($vm_name, $vm_snapinfo->{rootSnapshotList});
  56. }
  57.  
  58. map {
  59.    if($_->{'snap'} eq "VEEAM BACKUP TEMPORARY SNAPSHOT"){
  60.       system("/usr/lib/vmware-vcli/apps/vm/snapshotmanager.pl --operation remove --vmname $_->{'vm'} --snapshotname \"$_->{'snap'}\" --children 1");
  61.    }
  62. } @badsnaps;
  63.  
  64. END {
  65.         Util::disconnect();
  66. }