2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EC2 EBSのsnapshotを取得する。[SDK for Java]

Last updated at Posted at 2014-11-04

はじめに

AWS SDK for Javaを使ってEBSのsnapshotを取得する手順を紹介します。

AWS Management Console

1.左メニュー ELASTIC BLOCK STORE → Volumesを選択
2.snapshotを取得したいボリュームを右クリックで選択
3.CreateSnapshotを選択
4.Name,Descriptionを適当に入力して「Create」を押下。
5.しばらくすると作成されます。

snapshotは高い信頼性のS3上にバックアップとして保管もされますし、ブート領域を含んでいる場合は、ここからAMIを作成し、EC2インスタンスを複製することが可能です。

SDK for Java

ただsnapshotを作るのではなく、EC2のインスタンスIDをキーに対象のボリュームを特定してそのsnapshotをとってみます。


import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateSnapshotRequest;
import com.amazonaws.services.ec2.model.DescribeVolumesResult;
import com.amazonaws.services.ec2.model.Volume;
import com.amazonaws.services.ec2.model.VolumeAttachment;

public class Ec2EbsSnapshot {

	/**
	 * 第一引数で指定されたEC2のインスタンスIDに紐づくEBSのsnapshotを作成します。
	 * 
	 * @param args[0] ec2 instance id
	 */
	public static void main(String[] args) {

		String ec2InstanceId = args[0];
		if (args.length != 1 || ec2InstanceId == null
				|| "".equals(ec2InstanceId)) {
			throw new IllegalArgumentException("EC2 instance id is null.");
		}

		AWSCredentialsProvider provider = new ProfileCredentialsProvider("uzr");

		AmazonEC2 ec2_tokyo = Region.getRegion(Regions.AP_NORTHEAST_1)
				.createClient(AmazonEC2Client.class, provider,
						new ClientConfiguration());

		DescribeVolumesResult volumes = ec2_tokyo.describeVolumes();
		String volumeId = null;
		for (Volume volume : volumes.getVolumes()) {
			for (VolumeAttachment volumeAttatchment : volume.getAttachments()) {
				if (ec2InstanceId.equals(volumeAttatchment.getInstanceId())) {
					volumeId = volumeAttatchment.getVolumeId();
					System.out.println(ec2InstanceId + " : " + volumeId);
					break;
				}
			}
		}

		if (volumeId == null || "".equals(volumeId)) {
			System.out.println(ec2InstanceId + "に対応するvolumeIdが見つかりません。");
		} else {
			ec2_tokyo.createSnapshot(new CreateSnapshotRequest(volumeId,
					volumeId + " snapshot."));
			System.out.println("snapshotの作成を要求しました。");
		}
	}
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?