

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# ストレージボリュームのスナップショットの削除
<a name="DeletingASnapshot"></a>

ストレージボリュームのスナップショットを削除できます。たとえば、長期間に渡ってストレージボリュームの多数のスナップショットを作成し、古いスナップショットが不要になった場合などは、これを実行できます。スナップショットは増分バックアップなので、スナップショットを削除すると、他のスナップショットで必要とされていないデータのみが削除されます。

**Topics**
+ [AWS SDK for Java を使用したスナップショットの削除](#DeletingSnapshotsUsingJava)
+ [AWS SDK for .NET を使用したスナップショットの削除](#DeletingSnapshotsUsingDotNet)
+ [を使用したスナップショットの削除 AWS Tools for Windows PowerShell](#DeletingSnapshotsUsingPowerShell)

Amazon EBS コンソールで、スナップショットを一度に 1 つずつ削除できます。Amazon EBS コンソールを使用してスナップショットを削除する方法については、*Amazon EC2 ユーザーガイド*の「[Amazon EBS スナップショットの削除](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html)」を参照してください。

 一度に複数のスナップショットを削除するには、Storage Gateway オペレーションをサポートするいずれかの AWS SDKs を使用できます。例については、「[AWS SDK for Java を使用したスナップショットの削除](#DeletingSnapshotsUsingJava)」、「[AWS SDK for .NET を使用したスナップショットの削除](#DeletingSnapshotsUsingDotNet)」、および「[を使用したスナップショットの削除 AWS Tools for Windows PowerShell](#DeletingSnapshotsUsingPowerShell)」を参照してください。

## AWS SDK for Java を使用したスナップショットの削除
<a name="DeletingSnapshotsUsingJava"></a>

ボリュームに関連付けられている多数のスナップショットを削除するには、プログラム的な方法を使用します。次の例で、 AWS SDK for Java を使用してスナップショットを削除する方法を示します。サンプルコードを使用するには、Java コンソールアプリケーションの実行について理解している必要があります。手順については、*AWS SDK for Java デベロッパーガイド*の「[Getting Started](https://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-setup.html)」を参照してください。いくつかのスナップショットだけを削除する必要がある場合は、[ストレージボリュームのスナップショットの削除](#DeletingASnapshot) で説明されているように、コンソールを使用します。

**Example : AWS SDK for Java を使用したスナップショットの削除**  
次の Java コード例では、ゲートウェイの各ボリュームのスナップショットと、スナップショットの開始時間が指定した日付の前か後かをリストに表示します。Storage Gateway と Amazon EC2 用の AWS SDK for Java API を使用します。Amazon EC2 API には、スナップショットを操作するためのオペレーションが含まれています。  
サービスエンドポイント、ゲートウェイの Amazon リソースネーム (ARN) およびスナップショットを保存する日数を提供するコードを更新します。スナップショットは、この期限が削除される前に取得されます。また、`viewOnly` というブール値も指定する必要があります。この値は、削除されるスナップショットを表示するかどうかや、実際に削除を行うかどうかを示します。まずは、表示オプションだけで (つまり、`viewOnly` を `true` に設定して) コードを実行して、コードによって何が削除されるかを確認します。Storage Gateway で使用できる AWS サービスエンドポイントのリストについては、の[AWS Storage Gateway 「エンドポイントとクォータ](https://docs.aws.amazon.com/general/latest/gr/sg.html)」を参照してください*AWS 全般のリファレンス*。  

```
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DeleteSnapshotRequest;
import com.amazonaws.services.ec2.model.DescribeSnapshotsRequest;
import com.amazonaws.services.ec2.model.DescribeSnapshotsResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Snapshot;
import com.amazonaws.services.storagegateway.AWSStorageGatewayClient;
import com.amazonaws.services.storagegateway.model.ListVolumesRequest;
import com.amazonaws.services.storagegateway.model.ListVolumesResult;
import com.amazonaws.services.storagegateway.model.VolumeInfo;

public class ListDeleteVolumeSnapshotsExample {

    public static AWSStorageGatewayClient sgClient;
    public static AmazonEC2Client ec2Client;    
    static String serviceURLSG = "https://storagegateway.us-east-1.amazonaws.com";
    static String serviceURLEC2 = "https://ec2.us-east-1.amazonaws.com"; 
    
    // The gatewayARN
    public static String gatewayARN = "*** provide gateway ARN ***";
    
    // The number of days back you want to save snapshots. Snapshots before this cutoff are deleted
    // if viewOnly = false.
    public static int daysBack = 10;
    
    // true = show what will be deleted; false = actually delete snapshots that meet the daysBack criteria
    public static boolean viewOnly = true;

    public static void main(String[] args) throws IOException {

        // Create a Storage Gateway and amazon ec2 client
        sgClient = new AWSStorageGatewayClient(new PropertiesCredentials(
                ListDeleteVolumeSnapshotsExample.class.getResourceAsStream("AwsCredentials.properties")));    
        sgClient.setEndpoint(serviceURLSG);
        
        ec2Client = new AmazonEC2Client(new PropertiesCredentials(
                ListDeleteVolumeSnapshotsExample.class.getResourceAsStream("AwsCredentials.properties")));
        ec2Client.setEndpoint(serviceURLEC2);        
        
        List<VolumeInfo> volumes = ListVolumesForGateway();
        DeleteSnapshotsForVolumes(volumes, daysBack);        
        
    }
    public static List<VolumeInfo> ListVolumesForGateway()
    {
        List<VolumeInfo> volumes = new ArrayList<VolumeInfo>();

        String marker = null;
        do {
            ListVolumesRequest request = new ListVolumesRequest().withGatewayARN(gatewayARN);
            ListVolumesResult result = sgClient.listVolumes(request);
            marker = result.getMarker();
            
            for (VolumeInfo vi : result.getVolumeInfos())
            {
                volumes.add(vi);
                System.out.println(OutputVolumeInfo(vi));
            }           
        } while (marker != null);

        return volumes;
    }
    private static void DeleteSnapshotsForVolumes(List<VolumeInfo> volumes,
            int daysBack2) {
        
        // Find snapshots and delete for each volume 
        for (VolumeInfo vi : volumes) {
            
            String volumeARN = vi.getVolumeARN();
            String volumeId = volumeARN.substring(volumeARN.lastIndexOf("/")+1).toLowerCase();
            Collection<Filter> filters = new ArrayList<Filter>();
            Filter filter = new Filter().withName("volume-id").withValues(volumeId);
            filters.add(filter);
            
            DescribeSnapshotsRequest describeSnapshotsRequest =
                new DescribeSnapshotsRequest().withFilters(filters);
            DescribeSnapshotsResult describeSnapshotsResult =
                ec2Client.describeSnapshots(describeSnapshotsRequest);
            
            List<Snapshot> snapshots = describeSnapshotsResult.getSnapshots();
            System.out.println("volume-id = " + volumeId);
            for (Snapshot s : snapshots){
                StringBuilder sb = new StringBuilder();
                boolean meetsCriteria = !CompareDates(daysBack, s.getStartTime());
                sb.append(s.getSnapshotId() + ", " + s.getStartTime().toString());                
                sb.append(", meets criteria for delete? " + meetsCriteria);
                sb.append(", deleted? ");
                if (!viewOnly & meetsCriteria) {
                    sb.append("yes");
                    DeleteSnapshotRequest deleteSnapshotRequest = 
                        new DeleteSnapshotRequest().withSnapshotId(s.getSnapshotId());
                    ec2Client.deleteSnapshot(deleteSnapshotRequest);
                }
                else {
                    sb.append("no");
                }
                System.out.println(sb.toString());                    
            }        
        }
    }

    private static String OutputVolumeInfo(VolumeInfo vi) {
        
        String volumeInfo = String.format(
                 "Volume Info:\n" + 
                 "  ARN: %s\n" +
                 "  Type: %s\n",
                 vi.getVolumeARN(),
                 vi.getVolumeType());
        return volumeInfo; 
     }
    
    // Returns the date in two formats as a list
    public static boolean CompareDates(int daysBack, Date snapshotDate) {
        Date today = new Date();
        Calendar cal = new GregorianCalendar();
        cal.setTime(today);
        cal.add(Calendar.DAY_OF_MONTH, -daysBack);
        Date cutoffDate = cal.getTime();        
        return (snapshotDate.compareTo(cutoffDate) > 0) ? true : false;
    }

}
```

## AWS SDK for .NET を使用したスナップショットの削除
<a name="DeletingSnapshotsUsingDotNet"></a>

ボリュームに関連付けられている多数のスナップショットを削除するには、プログラム的な方法を使用します。次に、 AWS SDK for .NET バージョン 2 および 3 を使用してスナップショットを削除する方法の例を示します。サンプルコードを使用するには、.NET コンソールアプリケーションの実行について理解している必要があります。詳細については、「AWS SDK for .NET デベロッパーガイド**」の「[Getting Started](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-config.html)」を参照してください。いくつかのスナップショットだけを削除する必要がある場合は、[ストレージボリュームのスナップショットの削除](#DeletingASnapshot) で説明されているように、コンソールを使用します。

**Example : AWS SDK for .NET を使用したスナップショットの削除**  
次の C\$1 コード例では、 AWS Identity and Access Management ユーザーはゲートウェイの各ボリュームのスナップショットを一覧表示できます。ユーザーは、スナップショットの開始時間が指定日 (保持期間) 前あるいは後であるかを決定し、保持期間を過ぎたスナップショットを削除できます。この例では、Storage Gateway と Amazon EC2 用の AWS SDK for .NET API を使用しています。Amazon EC2 API には、スナップショットを操作するためのオペレーションが含まれています。  
次のコード例では、 AWS SDK for .NET バージョン 2 および 3 を使用しています。以前のバージョンの .NET を新しいバージョンに移行できます。詳細については、[AWS 「 SDK for .NET のプロジェクトの移行](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-migrating.html)」を参照してください。  
サービスエンドポイント、ゲートウェイの Amazon リソースネーム (ARN) およびスナップショットを保存する日数を提供するコードを更新します。スナップショットは、この期限が削除される前に取得されます。また、`viewOnly` というブール値も指定する必要があります。この値は、削除されるスナップショットを表示するかどうかや、実際に削除を行うかどうかを示します。まずは、表示オプションだけで (つまり、`viewOnly` を `true` に設定して) コードを実行して、コードによって何が削除されるかを確認します。Storage Gateway で使用できる AWS サービスエンドポイントのリストについては、の[AWS Storage Gateway 「エンドポイントとクォータ](https://docs.aws.amazon.com/general/latest/gr/sg.html)」を参照してください*AWS 全般のリファレンス*。  
 まず、ユーザーを作成し、最小限の IAM ポリシーをそのユーザーにアタッチします。次に、ゲートウェイの自動スナップショットをスケジュールします。  
次のコードでは、ユーザーによるスナップショットの削除を許可する最小限のポリシーを作成します。この例では、ポリシーの名前は **sgw-delete-snapshot** です。    
****  

```
{
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "StmtEC2Snapshots",
              "Effect": "Allow",
              "Action": [
                  "ec2:DeleteSnapshot",
                  "ec2:DescribeSnapshots"
              ],
              "Resource": [
                  "*"
              ]
          },
          {
              "Sid": "StmtSgwListVolumes",
              "Effect": "Allow",
              "Action": [
                  "storagegateway:ListVolumes"
              ],
              "Resource": [
                  "*"
              ]
          }
      ]
  }
```
次の C\$1 コードでは、指定されたゲートウェイで、ボリュームと指定されたカットオフ期間が一致するすべてのスナップショットを検出し、削除します。  

```
using System;
using System.Collections.Generic;
using System.Text;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.StorageGateway.Model;
using Amazon.StorageGateway;

namespace DeleteStorageGatewaySnapshotNS
{
    class Program
    {
        /*
         * Replace the variables below to match your environment.
         */
         
         /* IAM AccessKey */
        static String AwsAccessKey = "AKIA................";
        
        /* IAM SecretKey */
        static String AwsSecretKey = "*******************************";
        
        /* Account number, 12 digits, no hyphen */
        static String OwnerID = "123456789012";
        
        /* Your Gateway ARN. Use a Storage Gateway ID, sgw-XXXXXXXX* */ 
        static String GatewayARN = "arn:aws:storagegateway:ap-southeast-2:123456789012:gateway/sgw-XXXXXXXX";
        
        /* Snapshot status: "completed", "pending", "error" */                                                                                                      
        static String SnapshotStatus = "completed";
        
        /* Region where your gateway is activated */ 
        static String AwsRegion = "ap-southeast-2";
        
        /* Minimum age of snapshots before they are deleted (retention policy) */
        static int daysBack = 30; 

        /*
         * Do not modify the four lines below.
         */
        static AmazonEC2Config ec2Config;
        static AmazonEC2Client ec2Client;
        static AmazonStorageGatewayClient sgClient;
        static AmazonStorageGatewayConfig sgConfig;

        static void Main(string[] args)
        {
            // Create an EC2 client.
            ec2Config = new AmazonEC2Config();
            ec2Config.ServiceURL = "https://ec2." + AwsRegion + ".amazonaws.com";
            ec2Client = new AmazonEC2Client(AwsAccessKey, AwsSecretKey, ec2Config);

            // Create a Storage Gateway client.
            sgConfig = new AmazonStorageGatewayConfig();
            sgConfig.ServiceURL = "https://storagegateway." + AwsRegion + ".amazonaws.com";
            sgClient = new AmazonStorageGatewayClient(AwsAccessKey, AwsSecretKey, sgConfig);

            List<VolumeInfo> StorageGatewayVolumes = ListVolumesForGateway();
            List<Snapshot> StorageGatewaySnapshots = ListSnapshotsForVolumes(StorageGatewayVolumes, 
                                                     daysBack);
            DeleteSnapshots(StorageGatewaySnapshots);
        }

        /*
         * List all volumes for your gateway
         * returns: A list of VolumeInfos, or null.
         */
        private static List<VolumeInfo> ListVolumesForGateway()
        {
            ListVolumesResponse response = new ListVolumesResponse();
            try
            {
                ListVolumesRequest request = new ListVolumesRequest();
                request.GatewayARN = GatewayARN;
                response = sgClient.ListVolumes(request);

                foreach (VolumeInfo vi in response.VolumeInfos)
                {
                    Console.WriteLine(OutputVolumeInfo(vi));
                }
            }
            catch (AmazonStorageGatewayException ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response.VolumeInfos;
        }

        /*
         * Gets the list of snapshots that match the requested volumes
         * and cutoff period.
         */
        private static List<Snapshot> ListSnapshotsForVolumes(List<VolumeInfo> volumes, int snapshotAge)
        {
            List<Snapshot> SelectedSnapshots = new List<Snapshot>();
            try
            {
                foreach (VolumeInfo vi in volumes)
                {
                    String volumeARN = vi.VolumeARN;
                    String volumeID = volumeARN.Substring(volumeARN.LastIndexOf("/") + 1).ToLower();

                    DescribeSnapshotsRequest describeSnapshotsRequest = new DescribeSnapshotsRequest();

                    Filter ownerFilter = new Filter();
                    List<String> ownerValues = new List<String>();
                    ownerValues.Add(OwnerID);
                    ownerFilter.Name = "owner-id";
                    ownerFilter.Values = ownerValues;
                    describeSnapshotsRequest.Filters.Add(ownerFilter);

                    Filter statusFilter = new Filter();
                    List<String> statusValues = new List<String>();
                    statusValues.Add(SnapshotStatus);
                    statusFilter.Name = "status";
                    statusFilter.Values = statusValues;
                    describeSnapshotsRequest.Filters.Add(statusFilter);

                    Filter volumeFilter = new Filter();
                    List<String> volumeValues = new List<String>();
                    volumeValues.Add(volumeID);
                    volumeFilter.Name = "volume-id";
                    volumeFilter.Values = volumeValues;
                    describeSnapshotsRequest.Filters.Add(volumeFilter);

                    DescribeSnapshotsResponse describeSnapshotsResponse = 
                      ec2Client.DescribeSnapshots(describeSnapshotsRequest);

                    List<Snapshot> snapshots = describeSnapshotsResponse.Snapshots;
                    Console.WriteLine("volume-id = " + volumeID);
                    foreach (Snapshot s in snapshots)
                    {
                        if (IsSnapshotPastRetentionPeriod(snapshotAge, s.StartTime))
                        {
                            Console.WriteLine(s.SnapshotId + ", " + s.VolumeId + ", 
                               " + s.StartTime + ", " + s.Description);
                            SelectedSnapshots.Add(s);
                        }
                    }
                }
            }
            catch (AmazonEC2Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return SelectedSnapshots;
        }

        /*
         * Deletes a list of snapshots.
         */
        private static void DeleteSnapshots(List<Snapshot> snapshots)
        {
            try
            {
                foreach (Snapshot s in snapshots)
                {

                    DeleteSnapshotRequest deleteSnapshotRequest = new DeleteSnapshotRequest(s.SnapshotId);
                    DeleteSnapshotResponse response = ec2Client.DeleteSnapshot(deleteSnapshotRequest);
                    Console.WriteLine("Volume: " +
                              s.VolumeId +
                              " => Snapshot: " +
                              s.SnapshotId +
                              " Response: "
                              + response.HttpStatusCode.ToString());
                }
            }
            catch (AmazonEC2Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /*
         * Checks if the snapshot creation date is past the retention period.
         */
        private static Boolean IsSnapshotPastRetentionPeriod(int daysBack, DateTime snapshotDate)
        {
            DateTime cutoffDate = DateTime.Now.Add(new TimeSpan(-daysBack, 0, 0, 0));
            return (DateTime.Compare(snapshotDate, cutoffDate) < 0) ? true : false;
        }

        /*
         * Displays information related to a volume.
         */
        private static String OutputVolumeInfo(VolumeInfo vi)
        {
            String volumeInfo = String.Format(
                "Volume Info:\n" +
                "  ARN: {0}\n" +
                "  Type: {1}\n",
                vi.VolumeARN,
                vi.VolumeType);
            return volumeInfo;
        }
    }
}
```

## を使用したスナップショットの削除 AWS Tools for Windows PowerShell
<a name="DeletingSnapshotsUsingPowerShell"></a>

ボリュームに関連付けられている多数のスナップショットを削除するには、プログラム的な方法を使用します。次に、 AWS Tools for Windows PowerShellを使用してスナップショットを削除する方法の例を示します。スクリプト例を使用するには、PowerShell スクリプトの実行を熟知している必要があります。詳細については、[https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-started.html](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-started.html)* の「AWS Tools for Windows PowerShellご利用開始にあたって*」を参照してください。いくつかのスナップショットだけを削除する必要がある場合は、[ストレージボリュームのスナップショットの削除](#DeletingASnapshot) の説明に従ってコンソールを使用します。

**Example : を使用したスナップショットの削除 AWS Tools for Windows PowerShell**  
次の PowerShell スクリプト例では、ゲートウェイの各ボリュームのスナップショットと、スナップショットの開始時間が指定した日付の前か後かをリストに表示します。Storage Gateway と Amazon EC2 AWS Tools for Windows PowerShell のコマンドレットを使用します。Amazon EC2 API には、スナップショットを操作するためのオペレーションが含まれています。  
スクリプトを更新し、ゲートウェイの Amazon リソースネーム (ARN) およびスナップショットを保存する日数を提供する必要があります。スナップショットは、この期限が削除される前に取得されます。また、`viewOnly` というブール値も指定する必要があります。この値は、削除されるスナップショットを表示するかどうかや、実際に削除を行うかどうかを示します。まずは、表示オプションだけで (つまり、`viewOnly` を `true` に設定して) コードを実行して、コードによって何が削除されるかを確認します。  

```
<#
.DESCRIPTION
    Delete snapshots of a specified volume that match given criteria.
    
.NOTES
    PREREQUISITES:
    1) AWS Tools for Windows PowerShell from https://aws.amazon.com/powershell/
    2) Credentials and AWS Region stored in session using Initialize-AWSDefault.
    For more info see, https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html 

.EXAMPLE
    powershell.exe .\SG_DeleteSnapshots.ps1  
#>

# Criteria to use to filter the results returned.
$daysBack = 18
$gatewayARN = "*** provide gateway ARN ***"
$viewOnly = $true;

#ListVolumes
$volumesResult = Get-SGVolume -GatewayARN $gatewayARN
$volumes = $volumesResult.VolumeInfos
Write-Output("`nVolume List")
foreach ($volumes in $volumesResult)
  { Write-Output("`nVolume Info:")
    Write-Output("ARN:  " + $volumes.VolumeARN)
    write-Output("Type: " + $volumes.VolumeType)
  }

Write-Output("`nWhich snapshots meet the criteria?")
foreach ($volume in $volumesResult)
  { 
    $volumeARN = $volume.VolumeARN
    
    $volumeId = ($volumeARN-split"/")[3].ToLower()
  
    $filter = New-Object Amazon.EC2.Model.Filter
    $filter.Name = "volume-id"
    $filter.Value.Add($volumeId)
    
    $snapshots = get-EC2Snapshot -Filter $filter    
    Write-Output("`nFor volume-id = " + $volumeId)
    foreach ($s in $snapshots)
    {
       $d = ([DateTime]::Now).AddDays(-$daysBack)
       $meetsCriteria = $false
       if ([DateTime]::Compare($d, $s.StartTime) -gt 0)
       {
            $meetsCriteria = $true
       }
       
       $sb = $s.SnapshotId + ", " + $s.StartTime + ", meets criteria for delete? " + $meetsCriteria
       if (!$viewOnly -AND $meetsCriteria) 
       {
           $resp = Remove-EC2Snapshot -SnapshotId $s.SnapshotId
           #Can get RequestId from response for troubleshooting.
           $sb = $sb + ", deleted? yes"
       }
       else {
           $sb = $sb + ", deleted? no"
       }
       Write-Output($sb) 
    }
  }
```