使用C#SDK创建Amazon AMI,但仅包括根卷

时间:2013-11-11 23:41:59

标签: c# amazon-web-services ami

我已经编写了使用C#SDK创建AMI的代码,但是无法仅使用Root Volume创建AMI。默认情况下,它会创建AMI,并将所有EBS卷附加到实例。例如。如果它有4个卷,它将创建一个AMI,其中包含4个快照,而我只需要包含C:\驱动器(根驱动器)。我知道您必须使用BlockDeviceMapping指定卷,但不确定实现任何帮助将不胜感激。

public static void CreateAMI(string InstanceID, string AMIName, string AMIDescription)
{
    try
    {

        Console.WriteLine("Creating AMI for InstanceID" + InstanceID);

        AmazonEC2Config config = new AmazonEC2Config();
        config.ProxyHost = ConfigurationManager.AppSettings["PROXYHOST"];
        config.ProxyPort = Convert.ToInt32(ConfigurationManager.AppSettings["PROXYPORT"])
        config.ServiceURL = "https://ec2." + Program.options.Region + ".amazonaws.com";

        AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(Program.options.AccessKey, Program.options.SecretKey, config);

        CreateImageRequest rq = new CreateImageRequest();

        rq.InstanceId = InstanceID;
        rq.Name = AMIName;
        rq.Description = AMIDescription;
        rq.NoReboot = true;

        /* BlockDeviceMapping BMapping = new BlockDeviceMapping();
BMapping.DeviceName = "/dev/sda1";
rq.BlockDeviceMapping.Add(BMapping); */

        CreateImageResponse rs = ec2.CreateImage(rq);
        string AMIid = rs.CreateImageResult.ImageId;
        Console.WriteLine("AMI Created with AMIid: " + AMIid);
        Console.ReadLine();
    }
    catch (Exception err)
    {
        Console.WriteLine(err.Message + "/n" + err.StackTrace);
    }

}

1 个答案:

答案 0 :(得分:2)

我认为您需要将您的其他设备EBS属性指定为Null和No Device,以使它们与AMI分开。你的代码应该是这样的。

//Create Drive Mapping List
var blockDeviceMappingList = new List<BlockDeviceMapping>();

//Create Mappings
var blockDeviceMapping = new BlockDeviceMapping();
var blockDeviceMapping2 = new BlockDeviceMapping();

//Specif a mount point of the drive you want (root)
blockDeviceMapping.DeviceName = "/dev/sda1";
var ebsBlockDevice = new EbsBlockDevice();

//Set something other than null constructor or u get an error about EBS not set. Likely has to do with how they build the request to send to the server
ebsBlockDevice.VolumeType = VolumeType.Standard; 
blockDeviceMapping.Ebs = ebsBlockDevice;

//Specif a mount point of the unwanted drive and set EBS to null and NoDevice
blockDeviceMapping2.DeviceName = "/dev/sdf";
blockDeviceMapping2.Ebs = null;
blockDeviceMapping2.NoDevice = string.Empty;

//Add the mappings to the list
blockDeviceMappingList.Add(blockDeviceMapping);
blockDeviceMappingList.Add(blockDeviceMapping2);

//Setup Request
createImageRequest.BlockDeviceMappings = blockDeviceMappingList;

=)