Example #1
0
        public string CreateNameTags(string bootstrapId, IEnumerable<string> ids)
        {
            var tag = TAG_NAME_PREFIX + bootstrapId;

            var tagRequest = new CreateTagsRequest();
            tagRequest.Resources.AddRange(ids);

            tagRequest.Tags.Add(new Tag { Key = "Name", Value = tag });
            try
            {
                _client.CreateTags(tagRequest);
            }
            catch
            {
                Thread.Sleep(5000);
                _client.CreateTags(tagRequest);
            }
            return tag;
        }
        public static void Backup(string name, string description, string volumeid, string volumename, string instancename, string expires)
        {
            Console.WriteLine("    Creating snapshot of " + volumeid + " / " + volumename + " / " + instancename);

            AmazonEC2Client ec2 = Ec2Helper.CreateClient();

            CreateSnapshotRequest rq = new CreateSnapshotRequest();
            rq.VolumeId = volumeid;
            rq.Description = description;

            CreateSnapshotResponse rs = ec2.CreateSnapshot(rq);

            string snapshotid = rs.Snapshot.SnapshotId;

            // build tags for snapshot

            CreateTagsRequest rqq = new CreateTagsRequest();

            rqq.Resources.Add(snapshotid);

            rqq.Tags.Add(new Tag { Key = "Name", Value = name });
            rqq.Tags.Add(new Tag { Key = "source", Value = "scheduler" });
            rqq.Tags.Add(new Tag { Key = "instance", Value = instancename });
            rqq.Tags.Add(new Tag { Key = "volume", Value = volumename });
            rqq.Tags.Add(new Tag { Key = "expires", Value = expires.ToString() });

            // get tags from volume to be applied to snapshot

            DescribeTagsRequest trq = new DescribeTagsRequest();
            trq.Filters.Add(new Filter() { Name = "resource-id", Values = new List<string>() { volumeid } });
            DescribeTagsResponse trs = ec2.DescribeTags(trq);

            foreach (TagDescription t in trs.Tags)
            {
                if(t.Key!="nextSnapshot" && t.Key!="lastSnapshot" && t.Key!="Name")
                    rqq.Tags.Add(new Tag { Key = t.Key, Value = t.Value});
            }

            // apply tags to snapshopt

            var createTagResponse = ec2.CreateTags(rqq);
        }
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new Amazon.EC2.Model.CreateTagsRequest();

            if (cmdletContext.Resource != null)
            {
                request.Resources = cmdletContext.Resource;
            }
            if (cmdletContext.Tag != null)
            {
                request.Tags = cmdletContext.Tag;
            }

            CmdletOutput output;

            // issue call
            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);

            try
            {
                var    response       = CallAWSServiceOperation(client, request);
                object pipelineOutput = null;
                pipelineOutput = cmdletContext.Select(response, this);
                output         = new CmdletOutput
                {
                    PipelineOutput  = pipelineOutput,
                    ServiceResponse = response
                };
            }
            catch (Exception e)
            {
                output = new CmdletOutput {
                    ErrorResponse = e
                };
            }

            return(output);
        }
        public Snapshot SnapshotVolume(Ec2Key ec2Key, string volumeId, string snapshotDescription, string backupType)
        {
            AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);

            var ec2Request = new CreateSnapshotRequest {Description = snapshotDescription, VolumeId = volumeId};

            CreateSnapshotResponse result = ec2.CreateSnapshot(ec2Request);

            var request = new CreateTagsRequest();
            request.ResourceId = new List<string>
            {
                result.CreateSnapshotResult.Snapshot.SnapshotId
            };

            request.Tag = new List<Tag>
                              {
                                  new Tag
                                      {
                                         Key = "Name",
                                         Value = "EC2BackupUtility"
                                      },
                                  new Tag
                                      {
                                         Key = "EC2BackupSnapshotType",
                                         Value = backupType
                                      }
                              };

            ec2.CreateTags(request);

            return result.CreateSnapshotResult.Snapshot;
        }
Example #5
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateTags operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the CreateTags 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 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);
        }
Example #6
0
 IAsyncResult invokeCreateTags(CreateTagsRequest createTagsRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new CreateTagsRequestMarshaller().Marshall(createTagsRequest);
     var unmarshaller = CreateTagsResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Example #7
0
 /// <summary>
 /// Initiates the asynchronous execution of the CreateTags operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.CreateTags"/>
 /// </summary>
 /// 
 /// <param name="createTagsRequest">Container for the necessary parameters to execute the CreateTags 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>
 public IAsyncResult BeginCreateTags(CreateTagsRequest createTagsRequest, AsyncCallback callback, object state)
 {
     return invokeCreateTags(createTagsRequest, callback, state, false);
 }
Example #8
0
 /// <summary>
 /// <para>Adds or overwrites one or more tags for the specified EC2 resource or resources. Each resource can have a maximum of 10 tags. Each tag
 /// consists of a key and optional value. Tag keys must be unique per resource.</para> <para>For more information about tags, see <a
 /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html" >Tagging Your Resources</a> in the <i>Amazon Elastic Compute Cloud
 /// User Guide</i> .</para>
 /// </summary>
 /// 
 /// <param name="createTagsRequest">Container for the necessary parameters to execute the CreateTags service method on AmazonEC2.</param>
 /// 
 public CreateTagsResponse CreateTags(CreateTagsRequest createTagsRequest)
 {
     IAsyncResult asyncResult = invokeCreateTags(createTagsRequest, null, null, true);
     return EndCreateTags(asyncResult);
 }
        /// <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 in " + Program.options.Region + "...");

            AmazonEC2Client ec2 = Ec2Helper.CreateClient();

            DescribeVolumesRequest rq = new DescribeVolumesRequest();
            rq.Filters.Add(new Filter() { Name = "tag-key", Values = new List<string>() { "snapshotSchedule" } });
            DescribeVolumesResponse rs = ec2.DescribeVolumes(rq);

            foreach (Volume v in rs.Volumes)
            {

                string[] sch2 = Ec2Helper.GetTagValue(v.Tags, "snapshotSchedule").Split(' ');

                string volumename = Ec2Helper.GetTagValue(v.Tags, "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.Tags, "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.Attachments.First().InstanceId), expires);

                    // update volume tags

                    CreateTagsRequest rqq = new CreateTagsRequest();

                    rqq.Resources.Add(v.VolumeId);

                    nextSnap = nextSnap.AddSeconds(-nextSnap.Second).AddMilliseconds(-nextSnap.Millisecond);

                    rqq.Tags.Add(new Tag { Key = "lastSnapshot", Value = now.ToString() });
                    rqq.Tags.Add(new Tag { Key = "nextSnapshot", Value = nextNextSnap.ToString() });

                    var createTagResponse = ec2.CreateTags(rqq);
                }
                else
                {
                    Console.WriteLine("    Next scheduled " + nextSnap.ToString());
                }

            }
        }
Example #10
0
		internal CreateTagsResponse CreateTags(CreateTagsRequest request)
        {
            var task = CreateTagsAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Example #11
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateTags operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.CreateTags"/>
        /// </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 async Task<CreateTagsResponse> CreateTagsAsync(CreateTagsRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new CreateTagsRequestMarshaller();
            var unmarshaller = CreateTagsResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, CreateTagsRequest, CreateTagsResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
Example #12
0
        /// <summary>
        /// <para> Adds or overwrites tags for the specified resources. Each resource can have a maximum of 10 tags. Each tag consists of a key-value
        /// pair. Tag keys must be unique per resource. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the CreateTags service method on AmazonEC2.</param>
		public CreateTagsResponse CreateTags(CreateTagsRequest request)
        {
            var task = CreateTagsAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
 private Amazon.EC2.Model.CreateTagsResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.CreateTagsRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "CreateTags");
     try
     {
         #if DESKTOP
         return(client.CreateTags(request));
         #elif CORECLR
         return(client.CreateTagsAsync(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>
        /// Adds or overwrites one or more tags for the specified Amazon EC2 resource or resources.
        /// Each resource can have a maximum of 10 tags. Each tag consists of a key and optional
        /// value. Tag keys must be unique per resource.
        /// 
        ///  
        /// <para>
        /// For more information about tags, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html">Tagging
        /// Your Resources</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the CreateTags service method.</param>
        /// 
        /// <returns>The response from the CreateTags service method, as returned by EC2.</returns>
        public CreateTagsResponse CreateTags(CreateTagsRequest request)
        {
            var marshaller = new CreateTagsRequestMarshaller();
            var unmarshaller = CreateTagsResponseUnmarshaller.Instance;

            return Invoke<CreateTagsRequest,CreateTagsResponse>(request, marshaller, unmarshaller);
        }
Example #15
0
        /// <summary>
        /// <para>Adds or overwrites one or more tags for the specified EC2 resource or resources. Each resource can have a maximum of 10 tags. Each tag
        /// consists of a key and optional value. Tag keys must be unique per resource.</para> <para>For more information about tags, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html">Tagging Your Resources</a> in the <i>Amazon Elastic Compute Cloud
        /// User Guide</i> .</para>
        /// </summary>
        /// 
        /// <param name="createTagsRequest">Container for the necessary parameters to execute the CreateTags service method on AmazonEC2.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public Task<CreateTagsResponse> CreateTagsAsync(CreateTagsRequest createTagsRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new CreateTagsRequestMarshaller();
            var unmarshaller = CreateTagsResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, CreateTagsRequest, CreateTagsResponse>(createTagsRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
        /// <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);
        }
        public void LaunchInstance(string instanceName, InstanceSize size, string metadata)
        {
            var ec2Client = new AmazonEC2Client(_awsCredentials);

            string instanceType = "t1.micro";
            // WEB: string imageId = "ami-a9da0ec0";
            // Compute: string imageId = "ami-443fe32d";
            string imageId = "ami-09d96e60";

            switch (size)
            {
                case InstanceSize.Medium:
                    instanceType = "t1.small";
                    break;

                case InstanceSize.Small:
                default:
                    instanceType = "t1.micro";
                    break;
            }

            var request = new RunInstancesRequest()
                .WithInstanceType(instanceType)
                .WithPlacement(new Placement().WithAvailabilityZone("us-east-1d"))
                .WithImageId(imageId)
                .WithMinCount(1)
                .WithMaxCount(1)
                .WithSecurityGroup("default")
                .WithKeyName("IgorTest3");

            if (!string.IsNullOrEmpty(metadata))
                request = request.WithUserData(Convert.ToBase64String(Encoding.UTF8.GetBytes(metadata)));

            var runInstancesResponse = ec2Client.RunInstances(request);

            var instances = runInstancesResponse.RunInstancesResult.Reservation.RunningInstance;
            var index = 0;
            foreach (var instance in instances)
            {
                var name = instanceName;

                if (instances.Count > 0)
                    instanceName = instanceName + index;

                var createTagsRequest = new CreateTagsRequest();
                createTagsRequest
                    .WithResourceId(instance.InstanceId)
                    .WithTag(new Tag().WithKey("Name")
                    .WithValue(name));
                ec2Client.CreateTags(createTagsRequest);

                index++;
            }

            /*
            string rsaPrivateKey;
            using (var reader = new StreamReader(@"C:\Dev\BlueMetal\CloudAbstractions\SecurityStorage\IgorKeyPair.pem"))
            {
                rsaPrivateKey = reader.ReadToEnd();
            }
            var result = ec2Client.GetPasswordData(
                        new GetPasswordDataRequest().WithInstanceId(instanceId))
                .GetPasswordDataResult;

            Console.WriteLine(result.GetDecryptedPassword(rsaPrivateKey));
            */

            /*
                        AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                          appConfig["AWSAccessKey"],
                          appConfig["AWSSecretKey"],
                          new AmazonEC2Config().WithServiceURL("https://eu-west-1.ec2.amazonaws.com")
                          );

                        DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();
            */
        }