public override void Execute() { AmazonEC2Client client = new AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY); DescribeSnapshotsRequest request = new DescribeSnapshotsRequest(); DescribeSnapshotsResponse response = client.DescribeSnapshots(request); Dictionary<string, List<Amazon.EC2.Model.Snapshot>> snapshots = new Dictionary<string, List<Amazon.EC2.Model.Snapshot>>(); foreach (Amazon.EC2.Model.Snapshot r in response.DescribeSnapshotsResult.Snapshot) { if (!snapshots.ContainsKey(r.VolumeId)) snapshots[r.VolumeId] = new List<Amazon.EC2.Model.Snapshot>(); snapshots[r.VolumeId].Add(r); } foreach (string volumeId in snapshots.Keys) { Console.WriteLine("--- Volume: {0}", volumeId); snapshots[volumeId].Sort(delegate(Amazon.EC2.Model.Snapshot x,Amazon.EC2.Model.Snapshot y) { return DateTime.Parse(x.StartTime).CompareTo(DateTime.Parse(y.StartTime)); }); foreach (Amazon.EC2.Model.Snapshot s in snapshots[volumeId]) { DateTime startTime = DateTime.Parse(s.StartTime); Console.Write("{0}\t{1}\t{2}\t{3}", s.SnapshotId, startTime, s.Progress, s.Status); Console.WriteLine(); } Console.WriteLine(); } }
public override void Execute() { Amazon.EC2.AmazonEC2Client client = new Amazon.EC2.AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY); List<string> snapshotsToDelete = new List<string>(); if (isVolumeId) { // delete snapshots belonging to this volume DescribeSnapshotsRequest request = new DescribeSnapshotsRequest(); DescribeSnapshotsResponse response = client.DescribeSnapshots(request); foreach (Amazon.EC2.Model.Snapshot s in response.DescribeSnapshotsResult.Snapshot) { if (string.Equals(s.VolumeId, id, StringComparison.InvariantCultureIgnoreCase)) { DateTime snapshotDate = DateTime.Parse(s.StartTime); if (snapshotDate.AddDays(days) < DateTime.Now) snapshotsToDelete.Add(s.SnapshotId); } } } else { snapshotsToDelete.Add(id); } foreach (string snapshotId in snapshotsToDelete) { Console.WriteLine("Deleting snapshot ID {0}", snapshotId); Amazon.EC2.Model.DeleteSnapshotRequest request = new Amazon.EC2.Model.DeleteSnapshotRequest(); request.SnapshotId = snapshotId; Amazon.EC2.Model.DeleteSnapshotResponse response = client.DeleteSnapshot(request); } }
// delete older snapshots to keep the list clean void PruneSnapShots(string volume_id) { try { DescribeSnapshotsRequest dsr = new DescribeSnapshotsRequest(); Filter f = new Filter(); f.Name = "volume-id"; f.Value.Add(volume_id); dsr.Filter.Add(f); dsr.Owner = "self"; var resp = aec.DescribeSnapshots(dsr); var list = resp.DescribeSnapshotsResult.Snapshot; list.Sort((Snapshot s1, Snapshot s2) => { return s2.StartTime.CompareTo(s1.StartTime); }); if (list.Count > snaps2keep) { for (int i = snaps2keep; i < list.Count; i++) { DeleteSnapshotRequest del_req = new DeleteSnapshotRequest(); del_req.SnapshotId = list[i].SnapshotId; aec.DeleteSnapshot(del_req); } } } catch (Exception e) { Console.WriteLine("Caught exception while pruning snapshots: " + e.Message); Console.WriteLine("Stacktrace: " + e.StackTrace); } }
public void TerminateSnapshots(IEnumerable<string> volumeIds) { Logger.WithLogSection("Terminating snapshots", () => { foreach (var volumeId in volumeIds) { var describe = new DescribeSnapshotsRequest { Filters = new List<Filter> { new Filter { Name = "volume-id", Values = new[]{volumeId}.ToList() } } }; var snapshots = _client.DescribeSnapshots(describe); foreach (var snapshot in snapshots.Snapshots) { var request = new DeleteSnapshotRequest { SnapshotId = snapshot.SnapshotId }; _client.DeleteSnapshot(request); Logger.Info("Snapshot {0} deleted.", snapshot.SnapshotId); } } }); }
protected override void ProcessRecord() { AmazonEC2 client = base.GetClient(); Amazon.EC2.Model.DescribeSnapshotsRequest request = new Amazon.EC2.Model.DescribeSnapshotsRequest(); if (string.IsNullOrEmpty(this._SnapshotId)) { request.SnapshotId.Add(this._SnapshotId); } request.Owner = this._Owner; request.RestorableBy = this._RestorableBy; Amazon.EC2.Model.DescribeSnapshotsResponse response = client.DescribeSnapshots(request); base.WriteObject(response.DescribeSnapshotsResult.Snapshot, true); }
public static void DeleteOldSnapshots(List<string> volumeIds, int maxDays) { var describeSnapshotsRequest = new DescribeSnapshotsRequest { Filters = new List<Filter> { new Filter { Name = "volume-id", Values = volumeIds } } }; var describeSnapshotsResponse = Ec2Client.DescribeSnapshots(describeSnapshotsRequest); foreach (var snapshot in describeSnapshotsResponse.Snapshots) { var age = (DateTime.UtcNow - snapshot.StartTime.ToUniversalTime()).TotalDays; Console.WriteLine("Description: {0} Age:{1}", snapshot.Description, age); if (age > maxDays) { if (snapshot.Description.Contains("Created by CreateImage")) continue; Console.WriteLine("Deleting "); Ec2Client.DeleteSnapshot(new DeleteSnapshotRequest {SnapshotId = snapshot.SnapshotId}); } } }
private Amazon.EC2.Model.DescribeSnapshotsResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DescribeSnapshotsRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DescribeSnapshots"); try { #if DESKTOP return(client.DescribeSnapshots(request)); #elif CORECLR return(client.DescribeSnapshotsAsync(request).GetAwaiter().GetResult()); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } }
/// <summary> /// <para>Describes one or more of the Amazon EBS snapshots available to you. Available snapshots include public snapshots available for any AWS /// account to launch, private snapshots that you own, and private snapshots owned by another AWS account but for which you've been given /// explicit create volume permissions.</para> <para>The create volume permissions fall into the following categories:</para> /// <ul> /// <li> <i>public</i> : The owner of the snapshot granted create volume permissions for the snapshot to the <c>all</c> group. All AWS accounts /// have create volume permissions for these snapshots.</li> /// <li> <i>explicit</i> : The owner of the snapshot granted create volume permissions to a specific AWS account.</li> /// <li> <i>implicit</i> : An AWS account has implicit create volume permissions for all snapshots it owns.</li> /// /// </ul> /// <para>The list of snapshots returned can be modified by specifying snapshot IDs, snapshot owners, or AWS accounts with create volume /// permissions. If no options are specified, Amazon EC2 returns all snapshots for which you have create volume permissions.</para> <para>If you /// specify one or more snapshot IDs, only snapshots that have the specified IDs are returned. If you specify an invalid snapshot ID, an error /// is returned. If you specify a snapshot ID for which you do not have access, it is not included in the returned results.</para> <para>If you /// specify one or more snapshot owners, only snapshots from the specified owners and for which you have access are returned. The results can /// include the AWS account IDs of the specified owners, <c>amazon</c> for snapshots owned by Amazon, or <c>self</c> for snapshots that you /// own.</para> <para>If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are returned. /// You can specify AWS account IDs (if you own the snapshots), <c>self</c> for snapshots for which you own or have explicit permissions, or /// <c>all</c> for public snapshots.</para> <para>For more information about Amazon EBS snapshots, see <a /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html" >Amazon EBS Snapshots</a> in the <i>Amazon Elastic Compute Cloud /// User Guide</i> .</para> /// </summary> /// /// <param name="describeSnapshotsRequest">Container for the necessary parameters to execute the DescribeSnapshots service method on /// AmazonEC2.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by AmazonEC2.</returns> /// public DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest describeSnapshotsRequest) { IAsyncResult asyncResult = invokeDescribeSnapshots(describeSnapshotsRequest, null, null, true); return EndDescribeSnapshots(asyncResult); }
public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.EC2.Model.DescribeSnapshotsRequest(); if (cmdletContext.Filter != null) { request.Filters = cmdletContext.Filter; } if (cmdletContext.MaxResult != null) { request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value); } if (cmdletContext.OwnerId != null) { request.OwnerIds = cmdletContext.OwnerId; } if (cmdletContext.RestorableByUserId != null) { request.RestorableByUserIds = cmdletContext.RestorableByUserId; } if (cmdletContext.SnapshotId != null) { request.SnapshotIds = cmdletContext.SnapshotId; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return(null); }
public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; // create request and set iteration invariants var request = new Amazon.EC2.Model.DescribeSnapshotsRequest(); if (cmdletContext.Filter != null) { request.Filters = cmdletContext.Filter; } if (cmdletContext.OwnerId != null) { request.OwnerIds = cmdletContext.OwnerId; } if (cmdletContext.RestorableByUserId != null) { request.RestorableByUserIds = cmdletContext.RestorableByUserId; } if (cmdletContext.SnapshotId != null) { request.SnapshotIds = cmdletContext.SnapshotId; } // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.NextToken)) { _nextToken = cmdletContext.NextToken; } if (cmdletContext.MaxResult.HasValue) { // The service has a maximum page size of 1000. If the user has // asked for more items than page max, and there is no page size // configured, we rely on the service ignoring the set maximum // and giving us 1000 items back. If a page size is set, that will // be used to configure the pagination. // We'll make further calls to satisfy the user's request. _emitLimit = cmdletContext.MaxResult; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; if (_emitLimit.HasValue) { int correctPageSize = Math.Min(1000, _emitLimit.Value); request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.Snapshots.Count; _nextToken = response.NextToken; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return(null); }
public List<Snapshot> GetSnapshots(Ec2Key ec2Key) { AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key); var ec2Request = new DescribeSnapshotsRequest(); DescribeSnapshotsResponse result = ec2.DescribeSnapshots(ec2Request); return result.DescribeSnapshotsResult.Snapshot; }
public DataTable GetSnapshotDetails(string aprofile, string Region2Scan) { DataTable ToReturn = AWSTables.GetSnapshotDetailsTable(); string accountid = GetAccountID(aprofile); RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1; //Convert the Region2Scan to an AWS Endpoint. foreach (var aregion in RegionEndpoint.EnumerableAllRegions) { if (aregion.DisplayName.Equals(Region2Scan)) { Endpoint2scan = aregion; continue; } } Amazon.Runtime.AWSCredentials credential; try { credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile); var ec2 = new Amazon.EC2.AmazonEC2Client(credential, Endpoint2scan); // Describe snapshots has a max limit, so we have to make sure we collect all the data we need. DescribeSnapshotsRequest requesty = new DescribeSnapshotsRequest(); requesty.MaxResults = 1000; //Ouch! It lists all snaps we have access to. We only want ones we own and pay for.. //And it doesnt seem to return the ones we own. WTF???? requesty.OwnerIds.Add("self"); var snapres = ec2.DescribeSnapshots(requesty); var snappies = snapres.Snapshots; int nummie = snappies.Count; Dictionary<string, Snapshot> snaplist = new Dictionary<string, Snapshot>(); while (snapres.NextToken != null) { foreach (var av in snappies) { try { if (!snaplist.Keys.Contains(av.SnapshotId)) snaplist.Add(av.SnapshotId, av); else { var goob = snaplist[av.SnapshotId]; if (goob.Equals(av)) { string itsadupe = "Yar"; } }//Eliminate dupes } catch (Exception ex) { WriteToEventLog("Snapshots on " + aprofile + "/" + Region2Scan + " failed:\n" + ex.Message, EventLogEntryType.Error); } } requesty.NextToken = snapres.NextToken; snapres = ec2.DescribeSnapshots(requesty); } foreach (var av in snappies) { if (!snaplist.Keys.Contains(av.SnapshotId)) snaplist.Add(av.SnapshotId, av); else { var goob = snaplist[av.SnapshotId]; if (goob.Equals(av)) { string itsadupe = "Yar"; } }//Eliminate dupes. } foreach (var onesnap in snaplist.Values) { var arow = ToReturn.NewRow(); if (!accountid.Equals(onesnap.OwnerId)) continue; arow["AccountID"] = accountid; var rr = onesnap.GetType(); arow["Profile"] = aprofile; arow["Region"] = Region2Scan; arow["SnapshotID"] = onesnap.SnapshotId; arow["Description"] = onesnap.Description; arow["VolumeID"] = onesnap.VolumeId; arow["VolumeSize-GB"] = onesnap.VolumeSize; arow["Encrypted"] = onesnap.Encrypted.ToString(); arow["KMSKeyID"] = onesnap.KmsKeyId; arow["OwnerAlias"] = onesnap.OwnerAlias; arow["OwnerID"] = onesnap.OwnerId; arow["Progress"] = onesnap.Progress; arow["StartTime"] = onesnap.StartTime.ToString(); arow["State"] = onesnap.State.Value; arow["StateMessage"] = onesnap.StateMessage; var DKI = onesnap.DataEncryptionKeyId; if (String.IsNullOrEmpty(DKI)) { } else { arow["DataEncryptionKeyID"] = onesnap.DataEncryptionKeyId.ToString(); } //********** Some extra handling required**************/// List<string> taglist = new List<string>(); foreach (var atag in onesnap.Tags) { taglist.Add(atag.Key + ": " + atag.Value); } arow["Tags"] = List2String(taglist); ToReturn.Rows.Add(arow); } } catch (Exception ex) { WriteToEventLog("Snapshots on " + aprofile + " failed:\n" + ex.Message, EventLogEntryType.Error); } return ToReturn; }
/// <summary> /// Describes one or more of the EBS snapshots available to you. Available snapshots include /// public snapshots available for any AWS account to launch, private snapshots that you /// own, and private snapshots owned by another AWS account but for which you've been /// given explicit create volume permissions. /// /// /// <para> /// The create volume permissions fall into the following categories: /// </para> /// <ul> <li> <i>public</i>: The owner of the snapshot granted create volume permissions /// for the snapshot to the <code>all</code> group. All AWS accounts have create volume /// permissions for these snapshots.</li> <li> <i>explicit</i>: The owner of the snapshot /// granted create volume permissions to a specific AWS account.</li> <li> <i>implicit</i>: /// An AWS account has implicit create volume permissions for all snapshots it owns.</li> /// </ul> /// <para> /// The list of snapshots returned can be modified by specifying snapshot IDs, snapshot /// owners, or AWS accounts with create volume permissions. If no options are specified, /// Amazon EC2 returns all snapshots for which you have create volume permissions. /// </para> /// /// <para> /// If you specify one or more snapshot IDs, only snapshots that have the specified IDs /// are returned. If you specify an invalid snapshot ID, an error is returned. If you /// specify a snapshot ID for which you do not have access, it is not included in the /// returned results. /// </para> /// /// <para> /// If you specify one or more snapshot owners, only snapshots from the specified owners /// and for which you have access are returned. The results can include the AWS account /// IDs of the specified owners, <code>amazon</code> for snapshots owned by Amazon, or /// <code>self</code> for snapshots that you own. /// </para> /// /// <para> /// If you specify a list of restorable users, only snapshots with create snapshot permissions /// for those users are returned. You can specify AWS account IDs (if you own the snapshots), /// <code>self</code> for snapshots for which you own or have explicit permissions, or /// <code>all</code> for public snapshots. /// </para> /// /// <para> /// If you are describing a long list of snapshots, you can paginate the output to make /// the list more manageable. The <code>MaxResults</code> parameter sets the maximum number /// of results returned in a single page. If the list of results exceeds your <code>MaxResults</code> /// value, then that number of results is returned along with a <code>NextToken</code> /// value that can be passed to a subsequent <code>DescribeSnapshots</code> request to /// retrieve the remaining results. /// </para> /// /// <para> /// For more information about EBS snapshots, see <a href='http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html'>Amazon /// EBS Snapshots</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by EC2.</returns> public DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance; return Invoke<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller, unmarshaller); }
/// <summary> /// Paginator for DescribeSnapshots operation ///</summary> public IDescribeSnapshotsPaginator DescribeSnapshots(DescribeSnapshotsRequest request) { return(new DescribeSnapshotsPaginator(this.client, request)); }
/// <summary> /// Describes the indicated snapshots, or in lieu of that, all snapshots owned by the caller. /// /// </summary> /// <param name="service">Instance of AmazonEC2 service</param> /// <param name="request">DescribeSnapshotsRequest request</param> public static void InvokeDescribeSnapshots(AmazonEC2 service, DescribeSnapshotsRequest request) { try { DescribeSnapshotsResponse response = service.DescribeSnapshots(request); Console.WriteLine ("Service Response"); Console.WriteLine ("============================================================================="); Console.WriteLine (); Console.WriteLine(" DescribeSnapshotsResponse"); if (response.IsSetDescribeSnapshotsResult()) { Console.WriteLine(" DescribeSnapshotsResult"); DescribeSnapshotsResult describeSnapshotsResult = response.DescribeSnapshotsResult; List<Snapshot> snapshotList = describeSnapshotsResult.Snapshot; foreach (Snapshot snapshot in snapshotList) { Console.WriteLine(" Snapshot"); if (snapshot.IsSetSnapshotId()) { Console.WriteLine(" SnapshotId"); Console.WriteLine(" {0}", snapshot.SnapshotId); } if (snapshot.IsSetVolumeId()) { Console.WriteLine(" VolumeId"); Console.WriteLine(" {0}", snapshot.VolumeId); } if (snapshot.IsSetStatus()) { Console.WriteLine(" Status"); Console.WriteLine(" {0}", snapshot.Status); } if (snapshot.IsSetStartTime()) { Console.WriteLine(" StartTime"); Console.WriteLine(" {0}", snapshot.StartTime); } if (snapshot.IsSetProgress()) { Console.WriteLine(" Progress"); Console.WriteLine(" {0}", snapshot.Progress); } } } if (response.IsSetResponseMetadata()) { Console.WriteLine(" ResponseMetadata"); ResponseMetadata responseMetadata = response.ResponseMetadata; if (responseMetadata.IsSetRequestId()) { Console.WriteLine(" RequestId"); Console.WriteLine(" {0}", responseMetadata.RequestId); } } } catch (AmazonEC2Exception ex) { Console.WriteLine("Caught Exception: " + ex.Message); Console.WriteLine("Response Status Code: " + ex.StatusCode); Console.WriteLine("Error Code: " + ex.ErrorCode); Console.WriteLine("Error Type: " + ex.ErrorType); Console.WriteLine("Request ID: " + ex.RequestId); Console.WriteLine("XML: " + ex.XML); } }
internal DescribeSnapshotsPaginator(IAmazonEC2 client, DescribeSnapshotsRequest request) { this._client = client; this._request = request; }
static IEnumerable<Snapshot> GetSnapshotsWithBackupDate() { AmazonEC2 ec2 = GetEC2Client(); Filter filter = new Filter().WithName("tag:BackupDate").WithValue("*"); var request = new DescribeSnapshotsRequest().WithFilter(filter); var response = ec2.DescribeSnapshots(request); return response.DescribeSnapshotsResult.Snapshot; }
static bool CheckSnapshotCompletion(string snapshotID) { bool status = false; AmazonEC2 ec2 = GetEC2Client(); Filter filter = new Filter(); var request = new DescribeSnapshotsRequest().WithSnapshotId(snapshotID); var response = ec2.DescribeSnapshots(request); foreach (Snapshot s in response.DescribeSnapshotsResult.Snapshot) { if (s.SnapshotId == snapshotID) { if (s.Status == "completed") { status = true; } } } return status; }
/// <summary> /// Check for any snapshots set to expire -- that have a tag key of "expires" with a value that is in the past. /// </summary> public static void CheckForExpiredSnapshots() { Console.WriteLine("Checking for expired snapshots..."); var ec2 = Ec2Helper.CreateClient(); DescribeSnapshotsRequest rq = new DescribeSnapshotsRequest(); rq.OwnerIds.Add("self"); rq.Filters.Add(new Filter() { Name = "tag-key", Values = new List<string>() { "expires" } }); DescribeSnapshotsResponse rs = ec2.DescribeSnapshots(rq); foreach(Snapshot s in rs.Snapshots) { string expireText = Ec2Helper.GetTagValue(s.Tags, "expires"); DateTime expires; if (DateTime.TryParse(expireText, out expires)) { if(expires<DateTime.UtcNow) { Console.WriteLine("Deleting " + s.SnapshotId + " for " + s.VolumeId + "..."); Ec2Helper.DeleteSnapsot(s.SnapshotId); } } } }
/// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeSnapshots"/> /// </summary> /// /// <param name="describeSnapshotsRequest">Container for the necessary parameters to execute the DescribeSnapshots operation on /// AmazonEC2.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeSnapshots /// operation.</returns> public IAsyncResult BeginDescribeSnapshots(DescribeSnapshotsRequest describeSnapshotsRequest, AsyncCallback callback, object state) { return invokeDescribeSnapshots(describeSnapshotsRequest, callback, state, false); }
private async Task UntilSnapshotStateAsync(string snapshotId, string state, CancellationToken? cancellationToken = null) { CancellationToken token = cancellationToken.HasValue ? cancellationToken.Value : new CancellationToken(); var describeSnapshotsRequest = new DescribeSnapshotsRequest() { SnapshotIds = new List<string>() { snapshotId }, }; while (true) { token.ThrowIfCancellationRequested(); var describeSnapshotsResponse = await this.Client.DescribeSnapshotsAsync(describeSnapshotsRequest); var status = describeSnapshotsResponse.Snapshots.FirstOrDefault(x => x.SnapshotId == snapshotId).State; if (status == state) break; else await Task.Delay(1000, token); } }
IAsyncResult invokeDescribeSnapshots(DescribeSnapshotsRequest describeSnapshotsRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new DescribeSnapshotsRequestMarshaller().Marshall(describeSnapshotsRequest); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; }
internal DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request) { var task = DescribeSnapshotsAsync(request); try { return task.Result; } catch(AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); return null; } }
/// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation on AmazonEC2Client.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeSnapshots /// operation.</returns> public IAsyncResult BeginDescribeSnapshots(DescribeSnapshotsRequest request, AsyncCallback callback, object state) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance; return BeginInvoke<DescribeSnapshotsRequest>(request, marshaller, unmarshaller, callback, state); }
/// <summary> /// <para>Describes one or more of the Amazon EBS snapshots available to you. Available snapshots include public snapshots available for any AWS /// account to launch, private snapshots that you own, and private snapshots owned by another AWS account but for which you've been given /// explicit create volume permissions.</para> <para>The create volume permissions fall into the following categories:</para> /// <ul> /// <li> <i>public</i> : The owner of the snapshot granted create volume permissions for the snapshot to the <c>all</c> group. All AWS accounts /// have create volume permissions for these snapshots.</li> /// <li> <i>explicit</i> : The owner of the snapshot granted create volume permissions to a specific AWS account.</li> /// <li> <i>implicit</i> : An AWS account has implicit create volume permissions for all snapshots it owns.</li> /// /// </ul> /// <para>The list of snapshots returned can be modified by specifying snapshot IDs, snapshot owners, or AWS accounts with create volume /// permissions. If no options are specified, Amazon EC2 returns all snapshots for which you have create volume permissions.</para> <para>If you /// specify one or more snapshot IDs, only snapshots that have the specified IDs are returned. If you specify an invalid snapshot ID, an error /// is returned. If you specify a snapshot ID for which you do not have access, it is not included in the returned results.</para> <para>If you /// specify one or more snapshot owners, only snapshots from the specified owners and for which you have access are returned. The results can /// include the AWS account IDs of the specified owners, <c>amazon</c> for snapshots owned by Amazon, or <c>self</c> for snapshots that you /// own.</para> <para>If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are returned. /// You can specify AWS account IDs (if you own the snapshots), <c>self</c> for snapshots for which you own or have explicit permissions, or /// <c>all</c> for public snapshots.</para> <para>For more information about Amazon EBS snapshots, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html">Amazon EBS Snapshots</a> in the <i>Amazon Elastic Compute Cloud /// User Guide</i> .</para> /// </summary> /// /// <param name="describeSnapshotsRequest">Container for the necessary parameters to execute the DescribeSnapshots service method on /// AmazonEC2.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by AmazonEC2.</returns> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> public Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest describeSnapshotsRequest, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.GetInstance(); return Invoke<IRequest, DescribeSnapshotsRequest, DescribeSnapshotsResponse>(describeSnapshotsRequest, marshaller, unmarshaller, signer, cancellationToken); }
/// <summary> /// <para> Returns information about the Amazon EBS snapshots available to you. Snapshots available to you include public snapshots available /// for any AWS account to launch, private snapshots you own, and private snapshots owned by another AWS account but for which you've been given /// explicit create volume permissions. </para> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method on /// AmazonEC2.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by AmazonEC2.</returns> public DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request) { var task = DescribeSnapshotsAsync(request); try { return task.Result; } catch(AggregateException e) { throw e.InnerException; } }
private void WaitForSnapshotsToFinish(List<string> snapshotIds) { var request = new DescribeSnapshotsRequest { SnapshotIds = snapshotIds }; var response = _client.DescribeSnapshots(request); Logger.WithLogSection("Status", () => { foreach (var snapshot in response.Snapshots) { Logger.Info("Snapshot: {0} Progress: {1} State: {2}", snapshot.SnapshotId, string.IsNullOrWhiteSpace(snapshot.Progress) ? "Unknown" : snapshot.Progress, snapshot.State.Value); } }); if (response.Snapshots.Any(x => x.State.Value != SnapshotState.Completed)) { Thread.Sleep(10000); WaitForSnapshotsToFinish(snapshotIds); } }
/// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance; return InvokeAsync<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller, unmarshaller, cancellationToken); }
/// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeSnapshots"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public async Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.GetInstance(); var response = await Invoke<IRequest, DescribeSnapshotsRequest, DescribeSnapshotsResponse>(request, marshaller, unmarshaller, signer, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); return response; }