private static void ChangeInstanceTags(int changeType) { IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client(); DescribeInstancesResponse instanceResponse = ec2.DescribeInstances(); var resourceIdList = new List <string>(); var tagsList = new List <Tag>(); tagsList.Add(new Tag { Key = "Test1-AutoAdded", Value = "ToInduceConfigChages" }); tagsList.Add(new Tag { Key = "Test2-AutoAdded", Value = "ToInduceConfigChages" }); foreach (var reservation in instanceResponse.Reservations) { foreach (var rInstance in reservation.Instances) { resourceIdList.Add(rInstance.InstanceId); } } if (changeType == 0) { var createTagsRequest = new CreateTagsRequest(resourceIdList, tagsList); ec2.CreateTags(createTagsRequest); } else if (changeType == 1) { var deleteTagsRequest = new DeleteTagsRequest(); deleteTagsRequest.Resources = resourceIdList; deleteTagsRequest.Tags = tagsList; ec2.DeleteTags(deleteTagsRequest); } }
internal CreateTagsResponse CreateTags(CreateTagsRequest request) { var marshaller = new CreateTagsRequestMarshaller(); var unmarshaller = CreateTagsResponseUnmarshaller.Instance; return(Invoke <CreateTagsRequest, CreateTagsResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// Initiates the asynchronous execution of the CreateTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateTags 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 <CreateTagsResponse> CreateTagsAsync(CreateTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateTagsRequestMarshaller(); var unmarshaller = CreateTagsResponseUnmarshaller.Instance; return(InvokeAsync <CreateTagsRequest, CreateTagsResponse>(request, marshaller, unmarshaller, cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the CreateTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateTags operation on AmazonWorkSpacesClient.</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 EndCreateTags /// operation.</returns> public IAsyncResult BeginCreateTags(CreateTagsRequest request, AsyncCallback callback, object state) { var marshaller = new CreateTagsRequestMarshaller(); var unmarshaller = CreateTagsResponseUnmarshaller.Instance; return(BeginInvoke <CreateTagsRequest>(request, marshaller, unmarshaller, callback, state)); }
public void set_name_tag(AmazonEC2Client client, string res_id, string val) { var req = new CreateTagsRequest(); req.Resources.Add(res_id); req.Tags.Add(new Tag("Name", val)); client.CreateTags(req); }
/// <summary> /// Adds tag to specified instance. /// </summary> /// <param name="instanceId">InstanceId</param> /// <param name="tag">Tag (key-value pair)</param> public void AddTagToInstance(String instanceId, Tag tag) { CreateTagsRequest createTagsRequest = new CreateTagsRequest(); createTagsRequest.WithResourceId(instanceId); createTagsRequest.WithTag(tag); _ec2.CreateTags(createTagsRequest); }
/// <summary> /// Initiates the asynchronous execution of the CreateTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateTags 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> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/CreateTags">REST API Reference for CreateTags Operation</seealso> public virtual Task <CreateTagsResponse> CreateTagsAsync(CreateTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTagsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTagsResponseUnmarshaller.Instance; return(InvokeAsync <CreateTagsResponse>(request, options, cancellationToken)); }
internal virtual CreateTagsResponse CreateTags(CreateTagsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTagsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTagsResponseUnmarshaller.Instance; return(Invoke <CreateTagsResponse>(request, options)); }
/// <summary> /// Clears the ShutdownAfter tagged value to prevent the instance getting shutdown /// when the user starts it next time. /// /// This allows the user to manually enter the tag value without having to remember the tag name. /// </summary> /// <param name="instance"></param> /// <param name="context"></param> /// <returns></returns> private async Task RemoveTagAsync(Instance instance, ILambdaContext context) { CreateTagsRequest createRequest = new CreateTagsRequest(new List <string> { instance.InstanceId }, new List <Tag> { new Tag("ShutdownAfter", "") }); await _client.CreateTagsAsync(createRequest); }
public void TagInstances(List <string> instanceIds, List <KeyValuePair <string, string> > tags) { if (tags.Count == 0) { return; } var request = new CreateTagsRequest(instanceIds, tags.Select(x => new Tag(x.Key, x.Value)).ToList()); _client.CreateTags(request); }
/****************************************** Other ******************************************/ private void AssignNameToResource(string resourceId, string name) { //string resourceName = AwsCommon.FormatresourceName(resourceTypeName); CreateTagsRequest reqCreateTag = new CreateTagsRequest(); reqCreateTag.Resources = new List <string>(); reqCreateTag.Resources.Add(resourceId); reqCreateTag.Tags = new List <Tag>(); reqCreateTag.Tags.Add(new Tag("Name", name)); client.CreateTags(reqCreateTag); }
public Instance CreateInstance(SecurityGroup securityGroup) { //Setup the network interface for the instance List <string> groups = new List <string>() { securityGroup.GroupId }; var eni = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = Configuration.InstanceSubnetId, Groups = groups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>() { eni }; //Setup the request for the new instance var launchRequest = new RunInstancesRequest() { ImageId = Configuration.InstanceImageId, InstanceType = Configuration.InstanceType, MinCount = 1, MaxCount = 1, KeyName = Configuration.InstanceKeyPairName, NetworkInterfaces = enis, }; //Request the new instance var launchResponse = EC2Client.RunInstances(launchRequest); var instance = launchResponse.Reservation.Instances.FirstOrDefault(); if (instance == null) { throw new Exception("Failed to create instance: " + launchResponse.HttpStatusCode); } Console.WriteLine("New instance created: " + instance.InstanceId); //Create a Name tag for the new instance var createTagsRequest = new CreateTagsRequest() { Resources = new[] { instance.InstanceId }.ToList(), Tags = new[] { new Tag("Name", Configuration.InstanceName) }.ToList() }; var createTagsResponse = EC2Client.CreateTags(createTagsRequest); return(instance); }
private static void AddTag() { AmazonEC2Client client = new AmazonEC2Client(); CreateTagsRequest tagReq = new CreateTagsRequest(); tagReq.Resources = new System.Collections.Generic.List <string> { "instanceId" }; tagReq.Tags = new System.Collections.Generic.List <Tag> { new Tag() { Key = "tagKey", Value = "tagValue" } }; CreateTagsResponse tagResp = client.CreateTags(tagReq); Console.WriteLine("EC2 Tag created- {0}", tagResp.ResponseMetadata); }
private async Task UpdateInstanceTags(SetInstanceShutdownDto instanceShutdownDto, ILambdaContext context) { var shutdownTime = DateTime.UtcNow.AddMinutes(instanceShutdownDto.StopAfterMinutes); CreateTagsRequest request = new CreateTagsRequest { Resources = new List <string> { instanceShutdownDto.InstanceId }, Tags = new List <Tag> { new Tag("ShutdownAfter", shutdownTime.ToString("O")) } }; context.Logger.LogLine($"Setting shutdown time for instance: {instanceShutdownDto.InstanceId} as {shutdownTime.ToString("O")}"); await _client.CreateTagsAsync(request); context.Logger.LogLine($"ShutdownAfter tag set."); }
public static void Backup(string name, string description, string volumeid, string volumename, string instancename, string expires) { Console.WriteLine("Creating snapshot of " + volumeid + " / " + volumename + " / " + instancename); AmazonEC2 ec2 = Ec2Helper.CreateClient(); CreateSnapshotRequest rq = new CreateSnapshotRequest(); rq.VolumeId = volumeid; rq.Description = description; CreateSnapshotResponse rs = ec2.CreateSnapshot(rq); string snapshotid = rs.CreateSnapshotResult.Snapshot.SnapshotId; // build tags for snapshot List <Tag> tags = new List <Tag>(); tags.Add(new Tag { Key = "Name", Value = name }); tags.Add(new Tag { Key = "source", Value = "scheduler" }); tags.Add(new Tag { Key = "instance", Value = instancename }); tags.Add(new Tag { Key = "volume", Value = volumename }); tags.Add(new Tag { Key = "expires", Value = expires.ToString() }); // get tags from volume to be applied to snapshot DescribeTagsRequest trq = new DescribeTagsRequest(); trq.WithFilter(new Filter() { Name = "resource-id", Value = new List <string>() { volumeid } }); DescribeTagsResponse trs = ec2.DescribeTags(trq); foreach (ResourceTag t in trs.DescribeTagsResult.ResourceTag) { if (t.Key != "nextSnapshot" && t.Key != "lastSnapshot" && t.Key != "Name") { tags.Add(new Tag { Key = t.Key, Value = t.Value }); } } // apply tags to snapshopt CreateTagsRequest rqq = new CreateTagsRequest(); rqq.WithResourceId(snapshotid); rqq.WithTag(tags.ToArray()); var createTagResponse = ec2.CreateTags(rqq); }
/// <summary> /// Check for any volumes that have a snapshot scheduled based on the schedule in the snapshotSchedule tag key. /// </summary> public static void CheckForScheduledSnapshots() { Console.WriteLine("Checking for scheduled snapshots..."); AmazonEC2 ec2 = Ec2Helper.CreateClient(); DescribeVolumesRequest rq = new DescribeVolumesRequest(); rq.WithFilter(new Filter() { Name = "tag-key", Value = new List <string>() { "snapshotSchedule" } }); DescribeVolumesResponse rs = ec2.DescribeVolumes(rq); foreach (Volume v in rs.DescribeVolumesResult.Volume) { string[] sch2 = Ec2Helper.GetTagValue(v.Tag, "snapshotSchedule").Split(' '); string volumename = Ec2Helper.GetTagValue(v.Tag, "Name"); DateTime lastSnap; // date of last snapshot DateTime nextSnap; // the next backup that should have occured based on last backup DateTime nextNextSnap; // the next backup that should occur assuming a backup runs now or ran at the last proper time DateTime now = DateTime.UtcNow; if (!DateTime.TryParse(Ec2Helper.GetTagValue(v.Tag, "lastSnapshot"), out lastSnap)) { lastSnap = Convert.ToDateTime("1/1/2010"); } Console.WriteLine("Checking " + v.VolumeId + " / " + volumename + "..."); //sch2 = ("hourly 4 :30 x30days").Split(' '); //lastSnap = Convert.ToDateTime("2/29/2012 6:00:15pm"); //now = Convert.ToDateTime("2/29/2012 10:00:14pm"); switch (sch2[0]) { case "hourly": // hourly, hourly 1 :15, hourly :30, hourly 4 (pass it hours between backups & when on the hour to do it, any order; defaults to every hour on the hour) int ah = GetAfterTheHour(sch2, 0); int hi = GetInt(sch2, 1); nextSnap = lastSnap.AddMinutes(-lastSnap.Minute).AddSeconds(-lastSnap.Second).AddMilliseconds(-lastSnap.Millisecond); nextSnap = nextSnap.AddHours(hi).AddMinutes(ah); // this is not right nextNextSnap = now.AddMinutes(-now.Minute).AddSeconds(-now.Second).AddMilliseconds(-now.Millisecond); nextNextSnap = nextNextSnap.AddMinutes(ah).AddHours(hi); break; case "daily": // daily, 3pm, daily 15:15, daily 3:30pm (times are UTC; defaults to midnight UTC) DateTime hour = GetTime(sch2, Convert.ToDateTime("0:00")); nextSnap = lastSnap.Date.AddDays(1).AddTicks(hour.TimeOfDay.Ticks); nextNextSnap = now.Date.AddDays(1).AddTicks(hour.TimeOfDay.Ticks); break; case "weekly": // weekly, weekly sunday, weekly thursday 3pm (times are UTC; defaults to sunday midnight UTC) DateTime whour = GetTime(sch2, Convert.ToDateTime("0:00")); DayOfWeek dow = GetDow(sch2, DayOfWeek.Sunday); if (lastSnap.DayOfWeek >= dow) { nextSnap = lastSnap.Date.AddDays(-(int)lastSnap.DayOfWeek).AddDays(7 + (int)dow).AddTicks(whour.TimeOfDay.Ticks); } else { nextSnap = lastSnap.Date.AddDays(-(int)lastSnap.DayOfWeek).AddDays((int)dow).AddTicks(whour.TimeOfDay.Ticks); } nextNextSnap = now.Date.AddDays(-(int)now.DayOfWeek).AddDays(7 + (int)dow).AddTicks(whour.TimeOfDay.Ticks); if (nextSnap == nextNextSnap) { nextNextSnap = nextNextSnap.AddDays(7); } break; default: lastSnap = now.AddYears(1); nextSnap = lastSnap; nextNextSnap = lastSnap; break; } //Console.WriteLine("last=" + lastSnap.ToString()); //Console.WriteLine("now=" + now); //Console.WriteLine("next=" + nextSnap.ToString()); //Console.WriteLine("nextNext=" + nextNextSnap.ToString()); //Console.ReadKey(); //return; if (nextSnap <= now) { // create snapshot of volume string expires = ""; int expireHours = GetExpireHours(sch2, 0); if (expireHours > 0) { expires = now.AddHours(expireHours).ToString(); } Backup(volumename, "automatic", v.VolumeId, volumename, Ec2Helper.GetInstanceName(v.Attachment[0].InstanceId), expires); // update volume tags CreateTagsRequest rqq = new CreateTagsRequest(); rqq.WithResourceId(v.VolumeId); nextSnap = nextSnap.AddSeconds(-nextSnap.Second).AddMilliseconds(-nextSnap.Millisecond); rqq.WithTag(new Tag[] { new Tag { Key = "lastSnapshot", Value = now.ToString() }, new Tag { Key = "nextSnapshot", Value = nextNextSnap.ToString() } }); var createTagResponse = ec2.CreateTags(rqq); } else { Console.WriteLine(" Next scheduled " + nextSnap.ToString()); } } }