Ejemplo n.º 1
0
        /// <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...");

            AmazonEC2 ec2 = Ec2Helper.CreateClient();

            DescribeSnapshotsRequest rq = new DescribeSnapshotsRequest();

            rq.WithOwner("self");
            rq.WithFilter(new Filter()
            {
                Name = "tag-key", Value = new List <string>()
                {
                    "expires"
                }
            });

            DescribeSnapshotsResponse rs = ec2.DescribeSnapshots(rq);

            foreach (Snapshot s in rs.DescribeSnapshotsResult.Snapshot)
            {
                string expireText = Ec2Helper.GetTagValue(s.Tag, "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);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private RunningInstance GetRunningInstance(AmazonEC2 ec2Client, string instanceId)
        {
            var describeInstancesResponse = ec2Client.DescribeInstances(new DescribeInstancesRequest().WithInstanceId(instanceId));

            return(describeInstancesResponse.DescribeInstancesResult.Reservation[0].RunningInstance.Find(
                       r => r.InstanceId == instanceId));
        }
Ejemplo n.º 3
0
        public static bool CheckConnection()
        {
            try
            {
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                    App.Settings.AWSAccessKey,
                    App.Settings.AWSSecretKey,
                    new AmazonEC2Config {
                    ServiceURL = App.Settings.ServiceUrl
                }
                    );

                ec2.DescribeInstances(new DescribeInstancesRequest());

                return(true);
            }
            catch (AmazonEC2Exception ex)
            {
                string message = ex.Message + "\r\n" +
                                 "Response Status Code: " + ex.StatusCode + "\r\n" +
                                 "Error Code: " + ex.ErrorCode + "\r\n" +
                                 "Error Type: " + ex.ErrorType + "\r\n" +
                                 "Request ID: " + ex.RequestId;
                ExceptionDialog.Show(new AmazonEC2Exception(message, ex));
                return(false);
            }
            catch (Exception ex)
            {
                ExceptionDialog.Show(ex);
                return(false);
            }
        }
Ejemplo n.º 4
0
        private static RunningInstance WaitForInstanceToStartUp(AmazonEC2 ec2Client, string instanceId)
        {
            var describeRequest = new DescribeInstancesRequest()
            {
                InstanceId = new List <string>()
                {
                    instanceId
                }
            };

            for (int tries = 0; tries < 40; tries++)
            {
                Thread.Sleep(10 * 1000);

                var result = ec2Client.DescribeInstances(describeRequest).DescribeInstancesResult;
                if (result.Reservation.Count != 1 && result.Reservation[0].RunningInstance.Count != 1)
                {
                    return(null);
                }

                RunningInstance instance = result.Reservation[0].RunningInstance[0];

                // Return the updated instance object if we're out of pending
                if (!instance.InstanceState.Name.Equals("pending"))
                {
                    return(instance);
                }
            }

            return(null);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the name of the instances with the given instanceID from EC2
        /// </summary>
        /// <param name="instanceId"></param>
        /// <returns></returns>
        public static string GetInstanceName(string instanceId)
        {
            AmazonEC2 ec2 = CreateClient();

            DescribeTagsRequest rq = new DescribeTagsRequest();

            rq.WithFilter(new Filter()
            {
                Name = "resource-id", Value = new List <string>()
                {
                    instanceId
                }
            });

            DescribeTagsResponse rs = ec2.DescribeTags(rq);

            string name = "";

            ResourceTag tag = rs.DescribeTagsResult.ResourceTag.Find(item => item.Key == "Name");

            if (tag != null)
            {
                name = tag.Value;
            }

            return(name);
        }
Ejemplo n.º 6
0
        private static RouteTable GetDefaultRouteTable(AmazonEC2 ec2Client, string vpcId)
        {
            var filters = new List <Filter>()
            {
                new Filter()
                {
                    Name = "vpc-id", Value = new List <string>()
                    {
                        vpcId
                    }
                },
                new Filter()
                {
                    Name = "association.main", Value = new List <string>()
                    {
                        "true"
                    }
                }
            };

            var response = ec2Client.DescribeRouteTables(new DescribeRouteTablesRequest()
            {
                Filter = filters
            });

            if (response.DescribeRouteTablesResult.RouteTables.Count != 1)
            {
                return(null);
            }

            return(response.DescribeRouteTablesResult.RouteTables[0]);
        }
Ejemplo n.º 7
0
        private static SecurityGroup GetDefaultSecurityGroup(AmazonEC2 ec2Client, string vpcId)
        {
            var filters = new List <Filter>()
            {
                new Filter()
                {
                    Name = "vpc-id", Value = new List <string>()
                    {
                        vpcId
                    }
                },
                new Filter()
                {
                    Name = "group-name", Value = new List <string>()
                    {
                        "default"
                    }
                }
            };

            var response = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest()
            {
                Filter = filters
            });

            if (response.DescribeSecurityGroupsResult.SecurityGroup.Count != 1)
            {
                return(null);
            }

            return(response.DescribeSecurityGroupsResult.SecurityGroup[0]);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <returns>The response contains all the VPC objects that were created.</returns>
        public static LaunchVPCWithPublicSubnetResponse LaunchVPCWithPublicSubnet(AmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request)
        {
            LaunchVPCWithPublicSubnetResponse response = new LaunchVPCWithPublicSubnetResponse();

            LaunchVPCWithPublicSubnet(ec2Client, request, response);
            return(response);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// The ReleaseAddress operation releases an elastic IP address associated with
        /// your account.
        /// Note:
        /// Releasing an IP address automatically disassociates it from any instance with
        /// which it is associated. For more information, see DisassociateAddress.
        /// Important:
        /// After releasing an elastic IP address, it is released to the IP address pool
        /// and might no longer be available to your account. Make sure to update your DNS
        /// records and any servers or devices that communicate with the address.
        /// If you run this operation on an elastic IP address that is already released,
        /// the address might be assigned to another account which will cause Amazon EC2 to
        /// return an error.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">ReleaseAddressRequest request</param>
        public static void InvokeReleaseAddress(AmazonEC2 service, ReleaseAddressRequest request)
        {
            try 
            {
                ReleaseAddressResponse response = service.ReleaseAddress(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        ReleaseAddressResponse");
                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);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// List all volumes found in region
        /// </summary>
        public static void ListVolumes()
        {
            AmazonEC2 ec2 = Ec2Helper.CreateClient();

            DescribeVolumesRequest  rq = new DescribeVolumesRequest();
            DescribeVolumesResponse rs = ec2.DescribeVolumes(rq);

            foreach (Volume v in rs.DescribeVolumesResult.Volume)
            {
                Console.WriteLine(v.VolumeId);


                DescribeTagsRequest trq = new DescribeTagsRequest();
                trq.WithFilter(new Filter()
                {
                    Name = "resource-id", Value = new List <string>()
                    {
                        v.VolumeId
                    }
                });
                DescribeTagsResponse trs = ec2.DescribeTags(trq);
                foreach (ResourceTag t in trs.DescribeTagsResult.ResourceTag)
                {
                    Console.WriteLine("  " + t.Key + "=" + t.Value);
                }
            }
        }
Ejemplo n.º 11
0
        static Snapshot CreateSnapshot(string VolumeID, string name)
        {
            AmazonEC2 ec2     = GetEC2Client();
            var       request = new CreateSnapshotRequest()
                                .WithVolumeId(VolumeID)
                                .WithDescription(name);
            var response = ec2.CreateSnapshot(request);
            var snapshot = response.CreateSnapshotResult.Snapshot;

            ec2.CreateTags(new CreateTagsRequest()
                           .WithResourceId(snapshot.SnapshotId)
                           .WithTag(new Tag {
                Key = "Name", Value = name
            })
                           .WithTag(new Tag {
                Key = "BackupDate", Value = DateTime.Today.ToShortDateString()
            }));

            while (CheckSnapshotCompletion(snapshot.SnapshotId) == false)
            {
                System.Threading.Thread.Sleep(5000);
                Console.WriteLine("Checking Status");
            }

            return(snapshot);
        }
        /// <summary>
        /// The DescribeAvailabilityZones operation describes availability zones that are
        /// currently available to the account and their states.
        /// Availability zones are not the same across accounts. The availability zone
        /// us-east-1a for account A is not necessarily the same as us-east-1a for account
        /// B. Zone assignments are mapped independently for each account.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeAvailabilityZonesRequest request</param>
        public static void InvokeDescribeAvailabilityZones(AmazonEC2 service, DescribeAvailabilityZonesRequest request)
        {
            try 
            {
                DescribeAvailabilityZonesResponse response = service.DescribeAvailabilityZones(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeAvailabilityZonesResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeAvailabilityZonesResult())
                {
                    Console.WriteLine("            DescribeAvailabilityZonesResult");
                    DescribeAvailabilityZonesResult  describeAvailabilityZonesResult = response.DescribeAvailabilityZonesResult;
                    List<AvailabilityZone> availabilityZoneList = describeAvailabilityZonesResult.AvailabilityZone;
                    foreach (AvailabilityZone availabilityZone in availabilityZoneList)
                    {
                        Console.WriteLine("                AvailabilityZone");
                        if (availabilityZone.IsSetZoneName())
                        {
                            Console.WriteLine("                    ZoneName");
                            Console.WriteLine("                        {0}", availabilityZone.ZoneName);
                        }
                        if (availabilityZone.IsSetZoneState())
                        {
                            Console.WriteLine("                    ZoneState");
                            Console.WriteLine("                        {0}", availabilityZone.ZoneState);
                        }
                        if (availabilityZone.IsSetRegionName())
                        {
                            Console.WriteLine("                    RegionName");
                            Console.WriteLine("                        {0}", availabilityZone.RegionName);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// The GetConsoleOutput operation retrieves console output for the specified
        /// instance.
        /// Instance console output is buffered and posted shortly after instance boot,
        /// reboot, and termination. Amazon EC2 preserves the most recent 64 KB output
        /// which will be available for at least one hour after the most recent post.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">GetConsoleOutputRequest request</param>
        public static void InvokeGetConsoleOutput(AmazonEC2 service, GetConsoleOutputRequest request)
        {
            try 
            {
                GetConsoleOutputResponse response = service.GetConsoleOutput(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        GetConsoleOutputResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetGetConsoleOutputResult())
                {
                    Console.WriteLine("            GetConsoleOutputResult");
                    GetConsoleOutputResult  getConsoleOutputResult = response.GetConsoleOutputResult;
                    if (getConsoleOutputResult.IsSetConsoleOutput())
                    {
                        Console.WriteLine("                ConsoleOutput");
                        ConsoleOutput  consoleOutput = getConsoleOutputResult.ConsoleOutput;
                        if (consoleOutput.IsSetInstanceId())
                        {
                            Console.WriteLine("                    InstanceId");
                            Console.WriteLine("                        {0}", consoleOutput.InstanceId);
                        }
                        if (consoleOutput.IsSetTimestamp())
                        {
                            Console.WriteLine("                    Timestamp");
                            Console.WriteLine("                        {0}", consoleOutput.Timestamp);
                        }
                        if (consoleOutput.IsSetOutput())
                        {
                            Console.WriteLine("                    Output");
                            Console.WriteLine("                        {0}", consoleOutput.Output);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// The DescribeKeyPairs operation returns information about key pairs available to
        /// you. If you specify key pairs, information about those key pairs is returned.
        /// Otherwise, information for all registered key pairs is returned.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeKeyPairsRequest request</param>
        public static void InvokeDescribeKeyPairs(AmazonEC2 service, DescribeKeyPairsRequest request)
        {
            try 
            {
                DescribeKeyPairsResponse response = service.DescribeKeyPairs(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeKeyPairsResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeKeyPairsResult())
                {
                    Console.WriteLine("            DescribeKeyPairsResult");
                    DescribeKeyPairsResult  describeKeyPairsResult = response.DescribeKeyPairsResult;
                    List<KeyPair> keyPairList = describeKeyPairsResult.KeyPair;
                    foreach (KeyPair keyPair in keyPairList)
                    {
                        Console.WriteLine("                KeyPair");
                        if (keyPair.IsSetKeyName())
                        {
                            Console.WriteLine("                    KeyName");
                            Console.WriteLine("                        {0}", keyPair.KeyName);
                        }
                        if (keyPair.IsSetKeyFingerprint())
                        {
                            Console.WriteLine("                    KeyFingerprint");
                            Console.WriteLine("                        {0}", keyPair.KeyFingerprint);
                        }
                        if (keyPair.IsSetKeyMaterial())
                        {
                            Console.WriteLine("                    KeyMaterial");
                            Console.WriteLine("                        {0}", keyPair.KeyMaterial);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The CreateKeyPair operation creates a new 2048 bit RSA key pair and returns a
        /// unique ID that can be used to reference this key pair when launching new
        /// instances. For more information, see RunInstances.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">CreateKeyPairRequest request</param>
        public static void InvokeCreateKeyPair(AmazonEC2 service, CreateKeyPairRequest request)
        {
            try 
            {
                CreateKeyPairResponse response = service.CreateKeyPair(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        CreateKeyPairResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetCreateKeyPairResult())
                {
                    Console.WriteLine("            CreateKeyPairResult");
                    CreateKeyPairResult  createKeyPairResult = response.CreateKeyPairResult;
                    if (createKeyPairResult.IsSetKeyPair())
                    {
                        Console.WriteLine("                KeyPair");
                        KeyPair  keyPair = createKeyPairResult.KeyPair;
                        if (keyPair.IsSetKeyName())
                        {
                            Console.WriteLine("                    KeyName");
                            Console.WriteLine("                        {0}", keyPair.KeyName);
                        }
                        if (keyPair.IsSetKeyFingerprint())
                        {
                            Console.WriteLine("                    KeyFingerprint");
                            Console.WriteLine("                        {0}", keyPair.KeyFingerprint);
                        }
                        if (keyPair.IsSetKeyMaterial())
                        {
                            Console.WriteLine("                    KeyMaterial");
                            Console.WriteLine("                        {0}", keyPair.KeyMaterial);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 16
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && _ec2 != null)
     {
         _ec2.Dispose();
         _ec2 = null;
     }
 }
Ejemplo n.º 17
0
        static void DeleteSnapshot(string SnapshotID)
        {
            AmazonEC2 ec2      = GetEC2Client();
            var       request  = new DeleteSnapshotRequest().WithSnapshotId(SnapshotID);
            var       response = ec2.DeleteSnapshot(request);

            Console.WriteLine(SnapshotID + "was Deleted");
        }
Ejemplo n.º 18
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && _ec2 != null)
     {
         _ec2.Dispose();
         _ec2 = null;
     }
 }
        /// <summary>
        /// This method will look up the current VPC NAT ami in the region and create an instance in the subnet specified.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the NAT instance</param>
        /// <param name="request">The properties used to launch the NAT instance.</param>
        /// <returns></returns>
        public static RunningInstance LaunchNATInstance(AmazonEC2 ec2Client, LaunchNATInstanceRequest request)
        {
            if (ec2Client == null)
                throw new ArgumentNullException("ec2Client");
            if (request == null)
                throw new ArgumentNullException("request");
            if (string.IsNullOrEmpty(request.SubnetId))
                throw new ArgumentNullException("request.SubnetId");
            if (string.IsNullOrEmpty(request.InstanceType))
                throw new ArgumentNullException("request.InstanceType");

            List<Filter> filters = new List<Filter>()
            {
                new Filter(){Name = "architecture", Value = new List<string>(){"x86_64"}},
                new Filter(){Name = "name", Value = new List<string>(){"ami-vpc-nat-*.x86_64-ebs"}}
            };
            DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest() { Filter = filters });
            var image = ImageUtilities.FindImage(ec2Client, ImageUtilities.VPC_NAT);
            if (image == null)
            {
                throw new AmazonEC2Exception("No NAT image found in this region");
            }

            RunInstancesRequest runRequest = new RunInstancesRequest()
            {
                InstanceType = request.InstanceType,
                KeyName = request.KeyName,
                ImageId = image.ImageId,
                MinCount = 1,
                MaxCount = 1,
                SubnetId = request.SubnetId
            };
            RunInstancesResponse runResponse = ec2Client.RunInstances(runRequest);
            string instanceId = runResponse.RunInstancesResult.Reservation.RunningInstance[0].InstanceId;
            // Can't associated elastic IP address until the instance is available
            WaitForInstanceToStartUp(ec2Client, instanceId);

            ModifyInstanceAttributeRequest modifyRequest = new ModifyInstanceAttributeRequest()
            {
                InstanceId = instanceId,
                Attribute = "sourceDestCheck",
                Value = "false"
            };
            ec2Client.ModifyInstanceAttribute(modifyRequest);

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { instanceId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "NAT" } }
            });

            var allocationId = ec2Client.AllocateAddress(new AllocateAddressRequest() { Domain = "vpc" }).AllocateAddressResult.AllocationId;
            ec2Client.AssociateAddress(new AssociateAddressRequest() { InstanceId = instanceId, AllocationId = allocationId });

            var instance = ec2Client.DescribeInstances(new DescribeInstancesRequest() { InstanceId = new List<string>() { instanceId } }).DescribeInstancesResult.Reservation[0].RunningInstance[0];

            return instance;
        }
Ejemplo n.º 20
0
        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);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Get list of running instances in region for
        /// web service URL in application config
        /// </summary>
        /// <returns></returns>
        static private List <RunningInstance> GetRunningInstances()
        {
            AppConfig.Refresh();
            AmazonEC2Config config = new AmazonEC2Config();

            config.ServiceURL = AppConfig.AWSServiceURL;

            AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                AppConfig.AWSAccessKey,
                AppConfig.AWSSecretKey,
                config
                );


            //list of running instances
            List <RunningInstance>  runningInstancesList = new List <RunningInstance>();
            DescribeInstancesResult serviceResult;

            if (!string.IsNullOrEmpty(AppConfig.FilterByTag))
            {
                RunningInstance currentInstance           = GetCurrentInstance(ec2);
                String          currentInstancegroupvalue = GetCurrentInstanceGroupValue(currentInstance);
                // ask service for descriptions
                serviceResult =
                    ec2.DescribeInstances(new DescribeInstancesRequest().WithFilter(new Filter().WithName("tag:" + AppConfig.FilterByTag).WithValue(currentInstancegroupvalue))).DescribeInstancesResult;
            }
            else
            {
                serviceResult =
                    ec2.DescribeInstances(new DescribeInstancesRequest()).DescribeInstancesResult;
            }

            if (serviceResult.IsSetReservation())
            {
                //reservation is a group of instances launched from the same console
                List <Reservation> reservationList = serviceResult.Reservation;
                foreach (Reservation reservation in reservationList)
                {
                    if (reservation.IsSetRunningInstance())
                    {
                        //with all instances in reservation
                        //This list contains not only running instances
                        List <RunningInstance> instancesList = reservation.RunningInstance;
                        foreach (RunningInstance instance in instancesList)
                        { //include in result only really running ones
                            if (RUNNING_STATE == instance.InstanceState.Code)
                            {
                                runningInstancesList.Add(instance);
                            }
                        }
                    }
                }
            }

            return(runningInstancesList);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Return the EC2 client
        /// </summary>
        /// <returns></returns>
        public static AmazonEC2 CreateClient()
        {
            AmazonEC2Config config = new AmazonEC2Config();

            config.ServiceURL = "https://ec2." + Program.options.Region + ".amazonaws.com";

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

            return(ec2);
        }
        /// <summary>
        /// Prevent inheritance of the method.  Bind required parameters.
        /// </summary>
        protected sealed override void InternalExecute()
        {
            // Setup the WCF channel to the EC2 computing environment
            if (this.EC2Client == null)
            {
                this.EC2Client = AWSClientFactory.CreateAmazonEC2Client(this.AccessKey.Get(this.ActivityContext), this.SecretKey.Get(this.ActivityContext));
            }

            this.AmazonExecute();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Prevent inheritance of the method.  Bind required parameters.
        /// </summary>
        protected sealed override void InternalExecute()
        {
            // Setup the WCF channel to the EC2 computing environment
            if (this.EC2Client == null)
            {
                this.EC2Client = AWSClientFactory.CreateAmazonEC2Client(this.AccessKey.Get(this.ActivityContext), this.SecretKey.Get(this.ActivityContext));
            }

            this.AmazonExecute();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Delete the snapshop with the given ID from EBS
        /// </summary>
        /// <param name="p"></param>
        public static void DeleteSnapsot(string snapshotid)
        {
            AmazonEC2 ec2 = CreateClient();

            DeleteSnapshotRequest rq = new DeleteSnapshotRequest();

            rq.SnapshotId = snapshotid;

            DeleteSnapshotResponse rs = ec2.DeleteSnapshot(rq);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// The DescribeRegions operation describes regions zones that are currently available to the account.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeRegionsRequest request</param>
        public static void InvokeDescribeRegions(AmazonEC2 service, DescribeRegionsRequest request)
        {
            try 
            {
                DescribeRegionsResponse response = service.DescribeRegions(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeRegionsResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeRegionsResult())
                {
                    Console.WriteLine("            DescribeRegionsResult");
                    DescribeRegionsResult  describeRegionsResult = response.DescribeRegionsResult;
                    List<Region> regionList = describeRegionsResult.Region;
                    foreach (Region region in regionList)
                    {
                        Console.WriteLine("                Region");
                        if (region.IsSetRegionName())
                        {
                            Console.WriteLine("                    RegionName");
                            Console.WriteLine("                        {0}", region.RegionName);
                        }
                        if (region.IsSetEndpoint())
                        {
                            Console.WriteLine("                    Endpoint");
                            Console.WriteLine("                        {0}", region.Endpoint);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// The DescribeAddresses operation lists elastic IP addresses assigned to your
        /// account.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeAddressesRequest request</param>
        public static void InvokeDescribeAddresses(AmazonEC2 service, DescribeAddressesRequest request)
        {
            try 
            {
                DescribeAddressesResponse response = service.DescribeAddresses(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeAddressesResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeAddressesResult())
                {
                    Console.WriteLine("            DescribeAddressesResult");
                    DescribeAddressesResult  describeAddressesResult = response.DescribeAddressesResult;
                    List<Address> addressList = describeAddressesResult.Address;
                    foreach (Address address in addressList)
                    {
                        Console.WriteLine("                Address");
                        if (address.IsSetInstanceId())
                        {
                            Console.WriteLine("                    InstanceId");
                            Console.WriteLine("                        {0}", address.InstanceId);
                        }
                        if (address.IsSetPublicIp())
                        {
                            Console.WriteLine("                    PublicIp");
                            Console.WriteLine("                        {0}", address.PublicIp);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 28
0
        public Ec2Factory(string AWSAccessKey, string AWSSecretKey, string serviceUrl, ChaosLogger logger)
        {
            this.logger = logger;
            if (!serviceUrl.Contains("http://"))
            {
                serviceUrl = "http://" + serviceUrl;
            }

            amazonEc2 = AWSClientFactory.CreateAmazonEC2Client(
                AWSAccessKey,
                AWSSecretKey,
                new AmazonEC2Config().WithServiceURL(serviceUrl));
        }
Ejemplo n.º 29
0
        public Ec2Factory(string AWSAccessKey, string AWSSecretKey, string serviceUrl, ChaosLogger logger)
        {
            this.logger = logger;
            if (!serviceUrl.Contains("http://"))
            {
                serviceUrl = "http://" + serviceUrl;
            }

            amazonEc2 = AWSClientFactory.CreateAmazonEC2Client(
                AWSAccessKey,
                AWSSecretKey,
                new AmazonEC2Config().WithServiceURL(serviceUrl));
        }
Ejemplo n.º 30
0
        public static List <Instance> GetInstances()
        {
            try
            {
                var result = new List <Instance>();

                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                    App.Settings.AWSAccessKey,
                    App.Settings.AWSSecretKey,
                    new AmazonEC2Config {
                    ServiceURL = App.Settings.ServiceUrl
                }
                    );

                var ec2Response = ec2.DescribeInstances(new DescribeInstancesRequest());

                foreach (var image in ec2Response.DescribeInstancesResult.Reservation.SelectMany(a => a.RunningInstance))
                {
                    var nameTag = image.Tag.Where(t => t.Key == "Name").FirstOrDefault();
                    var name    = nameTag != null ? nameTag.Value : image.InstanceId;

                    var instance = new Instance()
                    {
                        Id             = image.InstanceId,
                        Name           = name,
                        StateName      = image.InstanceState.Name,
                        State          = (InstatnceStates)image.InstanceState.Code,
                        PublicIp       = image.IpAddress,
                        PrivateIp      = image.PrivateIpAddress,
                        InstanceType   = image.InstanceType,
                        PublicDnsName  = image.PublicDnsName,
                        PrivateDnsName = image.PrivateDnsName
                    };
                    if (!Enum.IsDefined(typeof(InstatnceStates), instance.State))
                    {
                        instance.State = InstatnceStates.Unknown;
                    }
                    result.Add(instance);
                }
                return(result.OrderBy(a => a.Name).ToList());
            }
            catch (AmazonEC2Exception ex)
            {
                string message = ex.Message + "\r\n" +
                                 "Response Status Code: " + ex.StatusCode + "\r\n" +
                                 "Error Code: " + ex.ErrorCode + "\r\n" +
                                 "Error Type: " + ex.ErrorType + "\r\n" +
                                 "Request ID: " + ex.RequestId;
                throw new AmazonEC2Exception(message, ex);
            }
        }
Ejemplo n.º 31
0
        private static void StopInstance()
        {
            try
            {
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(_awsKey, _awsSecretKey);

                StopInstancesRequest request = new StopInstancesRequest();
                request.WithInstanceId(new string[] { _instanceId });

                ec2.StopInstances(request);
                Mail(string.Format("Successfully stopped EC2 instance {0}", _instanceId));
            }
            catch (Exception e)
            {
                MailError("Error stopping instance", e);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// The AllocateAddress operation acquires an elastic IP address for use with your
        /// account.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">AllocateAddressRequest request</param>
        public static void InvokeAllocateAddress(AmazonEC2 service, AllocateAddressRequest request)
        {
            try 
            {
                AllocateAddressResponse response = service.AllocateAddress(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        AllocateAddressResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetAllocateAddressResult())
                {
                    Console.WriteLine("            AllocateAddressResult");
                    AllocateAddressResult  allocateAddressResult = response.AllocateAddressResult;
                    if (allocateAddressResult.IsSetPublicIp())
                    {
                        Console.WriteLine("                PublicIp");
                        Console.WriteLine("                    {0}", allocateAddressResult.PublicIp);
                    }
                }

            } 
            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);
            }
        }
        /// <summary>
        /// The PurchaseReservedInstancesOffering operation purchases a
        /// Reserved Instance for use with your account. With Amazon EC2
        /// Reserved Instances, you purchase the right to launch Amazon EC2
        /// instances for a period of time (without getting insufficient
        /// capacity errors) and pay a lower usage rate for the
        /// actual time used.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">PurchaseReservedInstancesOfferingRequest request</param>
        public static void InvokePurchaseReservedInstancesOffering(AmazonEC2 service, PurchaseReservedInstancesOfferingRequest request)
        {
            try 
            {
                PurchaseReservedInstancesOfferingResponse response = service.PurchaseReservedInstancesOffering(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        PurchaseReservedInstancesOfferingResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetPurchaseReservedInstancesOfferingResult())
                {
                    Console.WriteLine("            PurchaseReservedInstancesOfferingResult");
                    PurchaseReservedInstancesOfferingResult  purchaseReservedInstancesOfferingResult = response.PurchaseReservedInstancesOfferingResult;
                    if (purchaseReservedInstancesOfferingResult.IsSetReservedInstancesId())
                    {
                        Console.WriteLine("                ReservedInstancesId");
                        Console.WriteLine("                    {0}", purchaseReservedInstancesOfferingResult.ReservedInstancesId);
                    }
                }

            } 
            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);
            }
        }
        /// <summary>
        /// The ConfirmProductInstance operation returns true if the specified product code
        /// is attached to the specified instance. The operation returns false if the
        /// product code is not attached to the instance.
        /// The ConfirmProductInstance operation can only be executed by the owner of the
        /// AMI. This feature is useful when an AMI owner is providing support and wants to
        /// verify whether a user's instance is eligible.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">ConfirmProductInstanceRequest request</param>
        public static void InvokeConfirmProductInstance(AmazonEC2 service, ConfirmProductInstanceRequest request)
        {
            try 
            {
                ConfirmProductInstanceResponse response = service.ConfirmProductInstance(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        ConfirmProductInstanceResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetConfirmProductInstanceResult())
                {
                    Console.WriteLine("            ConfirmProductInstanceResult");
                    ConfirmProductInstanceResult  confirmProductInstanceResult = response.ConfirmProductInstanceResult;
                    if (confirmProductInstanceResult.IsSetOwnerId())
                    {
                        Console.WriteLine("                OwnerId");
                        Console.WriteLine("                    {0}", confirmProductInstanceResult.OwnerId);
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        ///  Get current instance
        /// </summary>
        /// <returns>Current instance or NULL if instance not found</returns>
        public static RunningInstance GetCurrentInstance(AmazonEC2 ec2)
        {
            DescribeInstancesResult serviceResult =
                ec2.DescribeInstances(new DescribeInstancesRequest()).DescribeInstancesResult;

            foreach (Reservation reservation in serviceResult.Reservation)
            {
                // these are not only really running ones...
                foreach (RunningInstance instance in reservation.RunningInstance)
                {
                    // deal only with really running instances
                    if (instance.InstanceState.Code == RUNNING_STATE && CheckIpAddress(instance.PrivateIpAddress))
                    {
                        return(instance);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 36
0
        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);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Find the Amazon machine image identified by the ImageDescriptor
        /// </summary>
        /// <param name="ec2Client">The EC2 client used to search for the image.</param>
        /// <param name="descriptor">The descriptor used to identify the image.</param>
        /// <returns>The Amazon machine image.</returns>
        public static Image FindImage(AmazonEC2 ec2Client, ImageDescriptor descriptor)
        {
            if (ec2Client == null)
                throw new ArgumentNullException("ec2Client");
            if (descriptor == null)
                throw new ArgumentNullException("descriptor");

            var result = ec2Client.DescribeImages(new DescribeImagesRequest()
            {
                Owner = new List<string>() { "amazon" },
                Filter = new List<Filter>()
                {
                    new Filter(){Name = "name", Value = new List<string>(){descriptor.NamePrefix}}
                }
            }).DescribeImagesResult;

            if (result.Image.Count == 0)
                return null;

            var image = result.Image.OrderByDescending(x => x.Name).First();
            return image;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Find the Amazon machine image identified by the ImageDescriptor
        /// </summary>
        /// <param name="ec2Client">The EC2 client used to search for the image.</param>
        /// <param name="descriptor">The descriptor used to identify the image.</param>
        /// <returns>The Amazon machine image.</returns>
        public static Image FindImage(AmazonEC2 ec2Client, ImageDescriptor descriptor)
        {
            if (ec2Client == null)
            {
                throw new ArgumentNullException("ec2Client");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }

            var result = ec2Client.DescribeImages(new DescribeImagesRequest()
            {
                Owner = new List <string>()
                {
                    "amazon"
                },
                Filter = new List <Filter>()
                {
                    new Filter()
                    {
                        Name = "name", Value = new List <string>()
                        {
                            descriptor.NamePrefix
                        }
                    }
                }
            }).DescribeImagesResult;

            if (result.Image.Count == 0)
            {
                return(null);
            }

            var image = result.Image.OrderByDescending(x => x.Name).First();

            return(image);
        }
        /// <summary>
        /// The DescribeImageAttribute operation returns information about an attribute of
        /// an AMI. Only one attribute can be specified per call.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeImageAttributeRequest request</param>
        public static void InvokeDescribeImageAttribute(AmazonEC2 service, DescribeImageAttributeRequest request)
        {
            try 
            {
                DescribeImageAttributeResponse response = service.DescribeImageAttribute(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeImageAttributeResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeImageAttributeResult())
                {
                    Console.WriteLine("            DescribeImageAttributeResult");
                    DescribeImageAttributeResult  describeImageAttributeResult = response.DescribeImageAttributeResult;
                    List<ImageAttribute> imageAttributeList = describeImageAttributeResult.ImageAttribute;
                    foreach (ImageAttribute imageAttribute in imageAttributeList)
                    {
                        Console.WriteLine("                ImageAttribute");
                        if (imageAttribute.IsSetImageId())
                        {
                            Console.WriteLine("                    ImageId");
                            Console.WriteLine("                        {0}", imageAttribute.ImageId);
                        }
                        List<LaunchPermission> launchPermissionList = imageAttribute.LaunchPermission;
                        foreach (LaunchPermission launchPermission in launchPermissionList)
                        {
                            Console.WriteLine("                    LaunchPermission");
                            if (launchPermission.IsSetUserId())
                            {
                                Console.WriteLine("                        UserId");
                                Console.WriteLine("                            {0}", launchPermission.UserId);
                            }
                            if (launchPermission.IsSetGroupName())
                            {
                                Console.WriteLine("                        GroupName");
                                Console.WriteLine("                            {0}", launchPermission.GroupName);
                            }
                        }
                        List<String> productCodeList  =  imageAttribute.ProductCode;
                        foreach (String productCode in productCodeList)
                        {
                            Console.WriteLine("                    ProductCode");
                            Console.WriteLine("                        {0}", productCode);
                        }
                        if (imageAttribute.IsSetKernelId())
                        {
                            Console.WriteLine("                    KernelId");
                            Console.WriteLine("                        {0}", imageAttribute.KernelId);
                        }
                        if (imageAttribute.IsSetRamdiskId())
                        {
                            Console.WriteLine("                    RamdiskId");
                            Console.WriteLine("                        {0}", imageAttribute.RamdiskId);
                        }
                        if (imageAttribute.IsSetBlockDeviceMapping())
                        {
                            Console.WriteLine("                    BlockDeviceMapping");
                            BlockDeviceMapping  blockDeviceMapping = imageAttribute.BlockDeviceMapping;
                            if (blockDeviceMapping.IsSetVirtualName())
                            {
                                Console.WriteLine("                        VirtualName");
                                Console.WriteLine("                            {0}", blockDeviceMapping.VirtualName);
                            }
                            if (blockDeviceMapping.IsSetDeviceName())
                            {
                                Console.WriteLine("                        DeviceName");
                                Console.WriteLine("                            {0}", blockDeviceMapping.DeviceName);
                            }
                        }
                    }
                }

            } 
            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);
            }
        }
        private static SecurityGroup GetDefaultSecurityGroup(AmazonEC2 ec2Client, string vpcId)
        {
            var filters = new List<Filter>()
            {
                new Filter() { Name = "vpc-id", Value = new List<string>() { vpcId } },
                new Filter() { Name = "group-name", Value = new List<string>() { "default" } }
            };

            var response = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest() { Filter = filters });
            if (response.DescribeSecurityGroupsResult.SecurityGroup.Count != 1)
                return null;

            return response.DescribeSecurityGroupsResult.SecurityGroup[0];
        }
Ejemplo n.º 41
0
        /// <summary>
        /// The RunInstances operation launches a specified number of instances.
        /// If Amazon EC2 cannot launch the minimum number AMIs you request, no instances
        /// launch. If there is insufficient capacity to launch the maximum number of AMIs
        /// you request, Amazon EC2 launches as many as possible to satisfy the requested
        /// maximum values.
        /// Every instance is launched in a security group. If you do not specify a
        /// security group at launch, the instances start in your default security group.
        /// For more information on creating security groups, see CreateSecurityGroup.
        /// An optional instance type can be specified. For information about instance
        /// types, see Instance Types.
        /// You can provide an optional key pair ID for each image in the launch request
        /// (for more information, see CreateKeyPair). All instances that are created from
        /// images that use this key pair will have access to the associated public key at
        /// boot. You can use this key to provide secure access to an instance of an image
        /// on a per-instance basis. Amazon EC2 public images use this feature to provide
        /// secure access without passwords.
        /// Important:
        /// Launching public images without a key pair ID will leave them inaccessible.
        /// The public key material is made available to the instance at boot time by
        /// placing it in the openssh_id.pub file on a logical device that is exposed to
        /// the instance as /dev/sda2 (the ephemeral store). The format of this file is
        /// suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH
        /// format). This can be done at boot (e.g., as part of rc.local) allowing for
        /// secure access without passwords.
        /// Optional user data can be provided in the launch request. All instances that
        /// collectively comprise the launch request have access to this data For more
        /// information, see Instance Metadata.
        /// Note:
        /// If any of the AMIs have a product code attached for which the user has not
        /// subscribed, the RunInstances call will fail.
        /// Important:
        /// We strongly recommend using the 2.6.18 Xen stock kernel with the c1.medium and
        /// c1.xlarge instances. Although the default Amazon EC2 kernels will work, the new
        /// kernels provide greater stability and performance for these instance types. For
        /// more information about kernels, see Kernels, RAM Disks, and Block Device
        /// Mappings.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">RunInstancesRequest request</param>
        public static void InvokeRunInstances(AmazonEC2 service, RunInstancesRequest request)
        {
            try 
            {
                RunInstancesResponse response = service.RunInstances(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        RunInstancesResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetRunInstancesResult())
                {
                    Console.WriteLine("            RunInstancesResult");
                    RunInstancesResult  runInstancesResult = response.RunInstancesResult;
                    if (runInstancesResult.IsSetReservation())
                    {
                        Console.WriteLine("                Reservation");
                        Reservation  reservation = runInstancesResult.Reservation;
                        if (reservation.IsSetReservationId())
                        {
                            Console.WriteLine("                    ReservationId");
                            Console.WriteLine("                        {0}", reservation.ReservationId);
                        }
                        if (reservation.IsSetOwnerId())
                        {
                            Console.WriteLine("                    OwnerId");
                            Console.WriteLine("                        {0}", reservation.OwnerId);
                        }
                        if (reservation.IsSetRequesterId())
                        {
                            Console.WriteLine("                    RequesterId");
                            Console.WriteLine("                        {0}", reservation.RequesterId);
                        }
                        List<String> groupNameList  =  reservation.GroupName;
                        foreach (String groupName in groupNameList)
                        {
                            Console.WriteLine("                    GroupName");
                            Console.WriteLine("                        {0}", groupName);
                        }
                        List<RunningInstance> runningInstanceList = reservation.RunningInstance;
                        foreach (RunningInstance runningInstance in runningInstanceList)
                        {
                            Console.WriteLine("                    RunningInstance");
                            if (runningInstance.IsSetInstanceId())
                            {
                                Console.WriteLine("                        InstanceId");
                                Console.WriteLine("                            {0}", runningInstance.InstanceId);
                            }
                            if (runningInstance.IsSetImageId())
                            {
                                Console.WriteLine("                        ImageId");
                                Console.WriteLine("                            {0}", runningInstance.ImageId);
                            }
                            if (runningInstance.IsSetInstanceState())
                            {
                                Console.WriteLine("                        InstanceState");
                                InstanceState  instanceState = runningInstance.InstanceState;
                                if (instanceState.IsSetCode())
                                {
                                    Console.WriteLine("                            Code");
                                    Console.WriteLine("                                {0}", instanceState.Code);
                                }
                                if (instanceState.IsSetName())
                                {
                                    Console.WriteLine("                            Name");
                                    Console.WriteLine("                                {0}", instanceState.Name);
                                }
                            }
                            if (runningInstance.IsSetPrivateDnsName())
                            {
                                Console.WriteLine("                        PrivateDnsName");
                                Console.WriteLine("                            {0}", runningInstance.PrivateDnsName);
                            }
                            if (runningInstance.IsSetPublicDnsName())
                            {
                                Console.WriteLine("                        PublicDnsName");
                                Console.WriteLine("                            {0}", runningInstance.PublicDnsName);
                            }
                            if (runningInstance.IsSetStateTransitionReason())
                            {
                                Console.WriteLine("                        StateTransitionReason");
                                Console.WriteLine("                            {0}", runningInstance.StateTransitionReason);
                            }
                            if (runningInstance.IsSetKeyName())
                            {
                                Console.WriteLine("                        KeyName");
                                Console.WriteLine("                            {0}", runningInstance.KeyName);
                            }
                            if (runningInstance.IsSetAmiLaunchIndex())
                            {
                                Console.WriteLine("                        AmiLaunchIndex");
                                Console.WriteLine("                            {0}", runningInstance.AmiLaunchIndex);
                            }
                            List<String> productCodeList  =  runningInstance.ProductCode;
                            foreach (String productCode in productCodeList)
                            {
                                Console.WriteLine("                        ProductCode");
                                Console.WriteLine("                            {0}", productCode);
                            }
                            if (runningInstance.IsSetInstanceType())
                            {
                                Console.WriteLine("                        InstanceType");
                                Console.WriteLine("                            {0}", runningInstance.InstanceType);
                            }
                            if (runningInstance.IsSetLaunchTime())
                            {
                                Console.WriteLine("                        LaunchTime");
                                Console.WriteLine("                            {0}", runningInstance.LaunchTime);
                            }
                            if (runningInstance.IsSetPlacement())
                            {
                                Console.WriteLine("                        Placement");
                                Placement  placement = runningInstance.Placement;
                                if (placement.IsSetAvailabilityZone())
                                {
                                    Console.WriteLine("                            AvailabilityZone");
                                    Console.WriteLine("                                {0}", placement.AvailabilityZone);
                                }
                            }
                            if (runningInstance.IsSetKernelId())
                            {
                                Console.WriteLine("                        KernelId");
                                Console.WriteLine("                            {0}", runningInstance.KernelId);
                            }
                            if (runningInstance.IsSetRamdiskId())
                            {
                                Console.WriteLine("                        RamdiskId");
                                Console.WriteLine("                            {0}", runningInstance.RamdiskId);
                            }
                            if (runningInstance.IsSetPlatform())
                            {
                                Console.WriteLine("                        Platform");
                                Console.WriteLine("                            {0}", runningInstance.Platform);
                            }
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 42
0
 private string GetPublicDnsName(AmazonEC2 ec2Client, string instanceId)
 {
     return(GetRunningInstance(ec2Client, instanceId).PublicDnsName);
 }
Ejemplo n.º 43
0
 private string GetInstanceStatus(AmazonEC2 ec2Client, string instanceId)
 {
     return(GetRunningInstance(ec2Client, instanceId).InstanceState.Name);
 }
 /// <summary>
 /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available to the internet.
 /// </summary>
 /// <param name="ec2Client">The ec2client used to create the VPC</param>
 /// <param name="request">The properties used to create the VPC.</param>
 /// <returns>The response contains all the VPC objects that were created.</returns>
 public static LaunchVPCWithPublicSubnetResponse LaunchVPCWithPublicSubnet(AmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request)
 {
     LaunchVPCWithPublicSubnetResponse response = new LaunchVPCWithPublicSubnetResponse();
     LaunchVPCWithPublicSubnet(ec2Client, request, response);
     return response;
 }
        /// <summary>
        /// The DescribeReservedInstancesOfferings operation describes Reserved
        /// Instance offerings that are available for purchase. With Amazon EC2
        /// Reserved Instances, you purchase the right to launch Amazon EC2 instances
        /// for a period of time (without getting insufficient capacity errors) and
        /// pay a lower usage rate for the actual time used.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeReservedInstancesOfferingsRequest request</param>
        public static void InvokeDescribeReservedInstancesOfferings(AmazonEC2 service, DescribeReservedInstancesOfferingsRequest request)
        {
            try 
            {
                DescribeReservedInstancesOfferingsResponse response = service.DescribeReservedInstancesOfferings(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeReservedInstancesOfferingsResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeReservedInstancesOfferingsResult())
                {
                    Console.WriteLine("            DescribeReservedInstancesOfferingsResult");
                    DescribeReservedInstancesOfferingsResult  describeReservedInstancesOfferingsResult = response.DescribeReservedInstancesOfferingsResult;
                    List<ReservedInstancesOffering> reservedInstancesOfferingList = describeReservedInstancesOfferingsResult.ReservedInstancesOffering;
                    foreach (ReservedInstancesOffering reservedInstancesOffering in reservedInstancesOfferingList)
                    {
                        Console.WriteLine("                ReservedInstancesOffering");
                        if (reservedInstancesOffering.IsSetReservedInstancesOfferingId())
                        {
                            Console.WriteLine("                    ReservedInstancesOfferingId");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.ReservedInstancesOfferingId);
                        }
                        if (reservedInstancesOffering.IsSetInstanceType())
                        {
                            Console.WriteLine("                    InstanceType");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.InstanceType);
                        }
                        if (reservedInstancesOffering.IsSetAvailabilityZone())
                        {
                            Console.WriteLine("                    AvailabilityZone");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.AvailabilityZone);
                        }
                        if (reservedInstancesOffering.IsSetDuration())
                        {
                            Console.WriteLine("                    Duration");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.Duration);
                        }
                        if (reservedInstancesOffering.IsSetUsagePrice())
                        {
                            Console.WriteLine("                    UsagePrice");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.UsagePrice);
                        }
                        if (reservedInstancesOffering.IsSetFixedPrice())
                        {
                            Console.WriteLine("                    FixedPrice");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.FixedPrice);
                        }
                        if (reservedInstancesOffering.IsSetProductDescription())
                        {
                            Console.WriteLine("                    ProductDescription");
                            Console.WriteLine("                        {0}", reservedInstancesOffering.ProductDescription);
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 46
0
 public EC2()
 {
     this.client = EC2Client();
 }
Ejemplo n.º 47
0
        /// <summary>
        /// This method will look up the current VPC NAT ami in the region and create an instance in the subnet specified.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the NAT instance</param>
        /// <param name="request">The properties used to launch the NAT instance.</param>
        /// <returns></returns>
        public static RunningInstance LaunchNATInstance(AmazonEC2 ec2Client, LaunchNATInstanceRequest request)
        {
            if (ec2Client == null)
            {
                throw new ArgumentNullException("ec2Client");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrEmpty(request.SubnetId))
            {
                throw new ArgumentNullException("request.SubnetId");
            }
            if (string.IsNullOrEmpty(request.InstanceType))
            {
                throw new ArgumentNullException("request.InstanceType");
            }

            List <Filter> filters = new List <Filter>()
            {
                new Filter()
                {
                    Name = "architecture", Value = new List <string>()
                    {
                        "x86_64"
                    }
                },
                new Filter()
                {
                    Name = "name", Value = new List <string>()
                    {
                        "ami-vpc-nat-*.x86_64-ebs"
                    }
                }
            };
            DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest()
            {
                Filter = filters
            });
            var image = ImageUtilities.FindImage(ec2Client, ImageUtilities.VPC_NAT);

            if (image == null)
            {
                throw new AmazonEC2Exception("No NAT image found in this region");
            }

            RunInstancesRequest runRequest = new RunInstancesRequest()
            {
                InstanceType = request.InstanceType,
                KeyName      = request.KeyName,
                ImageId      = image.ImageId,
                MinCount     = 1,
                MaxCount     = 1,
                SubnetId     = request.SubnetId
            };
            RunInstancesResponse runResponse = ec2Client.RunInstances(runRequest);
            string instanceId = runResponse.RunInstancesResult.Reservation.RunningInstance[0].InstanceId;

            // Can't associated elastic IP address until the instance is available
            WaitForInstanceToStartUp(ec2Client, instanceId);

            ModifyInstanceAttributeRequest modifyRequest = new ModifyInstanceAttributeRequest()
            {
                InstanceId = instanceId,
                Attribute  = "sourceDestCheck",
                Value      = "false"
            };

            ec2Client.ModifyInstanceAttribute(modifyRequest);

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List <string>()
                {
                    instanceId
                },
                Tag = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "NAT"
                    }
                }
            });

            var allocationId = ec2Client.AllocateAddress(new AllocateAddressRequest()
            {
                Domain = "vpc"
            }).AllocateAddressResult.AllocationId;

            ec2Client.AssociateAddress(new AssociateAddressRequest()
            {
                InstanceId = instanceId, AllocationId = allocationId
            });

            var instance = ec2Client.DescribeInstances(new DescribeInstancesRequest()
            {
                InstanceId = new List <string>()
                {
                    instanceId
                }
            }).DescribeInstancesResult.Reservation[0].RunningInstance[0];

            return(instance);
        }
        /// <summary>
        /// This method will create a VPC, a public subnet, private subnet and a NAT EC2 instance to allow EC2 instances in the private
        /// subnet to establish outbound connections to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <returns>The response contains all the VPC objects that were created.</returns>
        public static LaunchVPCWithPublicAndPrivateSubnetsResponse LaunchVPCWithPublicAndPrivateSubnets(AmazonEC2 ec2Client, LaunchVPCWithPublicAndPrivateSubnetsRequest request)
        {
            LaunchVPCWithPublicAndPrivateSubnetsResponse response = new LaunchVPCWithPublicAndPrivateSubnetsResponse();

            LaunchVPCWithPublicSubnet(ec2Client, request, response);

            response.PrivateSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PrivateSubnetAvailabilityZone ?? response.PublicSubnet.AvailabilityZone,
                CidrBlock = request.PrivateSubnetCiderBlock,
                VpcId = response.VPC.VpcId
            }).CreateSubnetResult.Subnet;
            WriteProgress(request.ProgressCallback, "Created private subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest(){SubnetId = new List<string>(){response.PrivateSubnet.SubnetId}}).DescribeSubnetsResult.Subnet.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { response.PrivateSubnet.SubnetId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "Private" } }
            });

            WriteProgress(request.ProgressCallback, "Launching NAT instance");
            response.NATInstance = LaunchNATInstance(ec2Client, new LaunchNATInstanceRequest()
            {
                InstanceType = request.InstanceType,
                KeyName = request.KeyName,
                SubnetId = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "NAT instance is available");

            var defaultRouteTable = GetDefaultRouteTable(ec2Client, response.VPC.VpcId);
            if (defaultRouteTable == null)
                throw new AmazonEC2Exception("No default route table found for VPC");
            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                RouteTableId = defaultRouteTable.RouteTableId,
                DestinationCidrBlock = "0.0.0.0/0",
                InstanceId = response.NATInstance.InstanceId
            });
            WriteProgress(request.ProgressCallback, "Added route to the NAT instance in the default route table");

            if (request.ConfigureDefaultVPCGroupForNAT)
            {
                var defaultSecurityGroup = GetDefaultSecurityGroup(ec2Client, response.VPC.VpcId);
                var groupId = ec2Client.CreateSecurityGroup(new CreateSecurityGroupRequest()
                {
                    VpcId = response.VPC.VpcId,
                    GroupName = "NATGroup",
                    GroupDescription = "Give EC2 Instances access through the NAT"
                }).CreateSecurityGroupResult.GroupId;
                WriteProgress(request.ProgressCallback, "Created security group for NAT configuration");

                IpPermissionSpecification spec = new IpPermissionSpecification()
                {
                    IpProtocol = "-1",
                    IpRanges = new List<string>(){"0.0.0.0/0"},
                    Groups = new List<UserIdGroupPair>() { new UserIdGroupPair() { GroupId = groupId } }
                };

                ec2Client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest()
                {
                    IpPermissions = new List<IpPermissionSpecification>(){spec},
                    GroupId = defaultSecurityGroup.GroupId
                });
                WriteProgress(request.ProgressCallback, "Added permission to the default security group {0} to allow traffic from security group {1}", defaultSecurityGroup.GroupId, groupId);

                response.NATSecurityGroup = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest()
                {
                    GroupId = new List<string>(){ groupId }
                }).DescribeSecurityGroupsResult.SecurityGroup[0];
            }

            return response;
        }
Ejemplo n.º 49
0
        /// <summary>
        /// This method will create a VPC, a public subnet, private subnet and a NAT EC2 instance to allow EC2 instances in the private
        /// subnet to establish outbound connections to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <returns>The response contains all the VPC objects that were created.</returns>
        public static LaunchVPCWithPublicAndPrivateSubnetsResponse LaunchVPCWithPublicAndPrivateSubnets(AmazonEC2 ec2Client, LaunchVPCWithPublicAndPrivateSubnetsRequest request)
        {
            LaunchVPCWithPublicAndPrivateSubnetsResponse response = new LaunchVPCWithPublicAndPrivateSubnetsResponse();

            LaunchVPCWithPublicSubnet(ec2Client, request, response);

            response.PrivateSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PrivateSubnetAvailabilityZone ?? response.PublicSubnet.AvailabilityZone,
                CidrBlock        = request.PrivateSubnetCiderBlock,
                VpcId            = response.VPC.VpcId
            }).CreateSubnetResult.Subnet;
            WriteProgress(request.ProgressCallback, "Created private subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func <bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest()
            {
                SubnetId = new List <string>()
                {
                    response.PrivateSubnet.SubnetId
                }
            }).DescribeSubnetsResult.Subnet.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List <string>()
                {
                    response.PrivateSubnet.SubnetId
                },
                Tag = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "Private"
                    }
                }
            });

            WriteProgress(request.ProgressCallback, "Launching NAT instance");
            response.NATInstance = LaunchNATInstance(ec2Client, new LaunchNATInstanceRequest()
            {
                InstanceType = request.InstanceType,
                KeyName      = request.KeyName,
                SubnetId     = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "NAT instance is available");

            var defaultRouteTable = GetDefaultRouteTable(ec2Client, response.VPC.VpcId);

            if (defaultRouteTable == null)
            {
                throw new AmazonEC2Exception("No default route table found for VPC");
            }
            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                RouteTableId         = defaultRouteTable.RouteTableId,
                DestinationCidrBlock = "0.0.0.0/0",
                InstanceId           = response.NATInstance.InstanceId
            });
            WriteProgress(request.ProgressCallback, "Added route to the NAT instance in the default route table");

            if (request.ConfigureDefaultVPCGroupForNAT)
            {
                var defaultSecurityGroup = GetDefaultSecurityGroup(ec2Client, response.VPC.VpcId);
                var groupId = ec2Client.CreateSecurityGroup(new CreateSecurityGroupRequest()
                {
                    VpcId            = response.VPC.VpcId,
                    GroupName        = "NATGroup",
                    GroupDescription = "Give EC2 Instances access through the NAT"
                }).CreateSecurityGroupResult.GroupId;
                WriteProgress(request.ProgressCallback, "Created security group for NAT configuration");


                IpPermissionSpecification spec = new IpPermissionSpecification()
                {
                    IpProtocol = "-1",
                    IpRanges   = new List <string>()
                    {
                        "0.0.0.0/0"
                    },
                    Groups = new List <UserIdGroupPair>()
                    {
                        new UserIdGroupPair()
                        {
                            GroupId = groupId
                        }
                    }
                };

                ec2Client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest()
                {
                    IpPermissions = new List <IpPermissionSpecification>()
                    {
                        spec
                    },
                    GroupId = defaultSecurityGroup.GroupId
                });
                WriteProgress(request.ProgressCallback, "Added permission to the default security group {0} to allow traffic from security group {1}", defaultSecurityGroup.GroupId, groupId);

                response.NATSecurityGroup = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest()
                {
                    GroupId = new List <string>()
                    {
                        groupId
                    }
                }).DescribeSecurityGroupsResult.SecurityGroup[0];
            }

            return(response);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <param name="response">The response contains all the VPC objects that were created.</param>
        private static void LaunchVPCWithPublicSubnet(AmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request, LaunchVPCWithPublicSubnetResponse response)
        {
            response.VPC = ec2Client.CreateVpc(new CreateVpcRequest()
            {
                CidrBlock       = request.VPCCidrBlock,
                InstanceTenancy = request.InstanceTenancy
            }).CreateVpcResult.Vpc;
            WriteProgress(request.ProgressCallback, "Created vpc {0}", response.VPC.VpcId);

            var describeVPCRequest = new DescribeVpcsRequest()
            {
                VpcId = new List <string>()
                {
                    response.VPC.VpcId
                }
            };

            WaitTillTrue(((Func <bool>)(() => ec2Client.DescribeVpcs(describeVPCRequest).DescribeVpcsResult.Vpc.Count == 1)));

            if (!string.IsNullOrEmpty(request.VPCName))
            {
                ec2Client.CreateTags(new CreateTagsRequest()
                {
                    ResourceId = new List <string>()
                    {
                        response.VPC.VpcId
                    },
                    Tag = new List <Tag>()
                    {
                        new Tag()
                        {
                            Key = "Name", Value = request.VPCName
                        }
                    }
                });
            }

            response.PublicSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PublicSubnetAvailabilityZone,
                CidrBlock        = request.PublicSubnetCiderBlock,
                VpcId            = response.VPC.VpcId
            }).CreateSubnetResult.Subnet;
            WriteProgress(request.ProgressCallback, "Created public subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func <bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest()
            {
                SubnetId = new List <string>()
                {
                    response.PublicSubnet.SubnetId
                }
            }).DescribeSubnetsResult.Subnet.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List <string>()
                {
                    response.PublicSubnet.SubnetId
                },
                Tag = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "Public"
                    }
                }
            });

            response.InternetGateway = ec2Client.CreateInternetGateway(new CreateInternetGatewayRequest()
            {
            }).CreateInternetGatewayResult.InternetGateway;
            WriteProgress(request.ProgressCallback, "Created internet gateway {0}", response.InternetGateway.InternetGatewayId);

            ec2Client.AttachInternetGateway(new AttachInternetGatewayRequest()
            {
                InternetGatewayId = response.InternetGateway.InternetGatewayId,
                VpcId             = response.VPC.VpcId
            });
            WriteProgress(request.ProgressCallback, "Attached internet gateway to vpc");

            response.PublicSubnetRouteTable = ec2Client.CreateRouteTable(new CreateRouteTableRequest()
            {
                VpcId = response.VPC.VpcId
            }).CreateRouteTableResult.RouteTable;
            WriteProgress(request.ProgressCallback, "Created route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            var describeRouteTableRequest = new DescribeRouteTablesRequest()
            {
                RouteTableId = new List <string>()
                {
                    response.PublicSubnetRouteTable.RouteTableId
                }
            };

            WaitTillTrue(((Func <bool>)(() => (ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List <string>()
                {
                    response.PublicSubnetRouteTable.RouteTableId
                },
                Tag = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "Public"
                    }
                }
            });

            ec2Client.AssociateRouteTable(new AssociateRouteTableRequest()
            {
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId,
                SubnetId     = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "Associated route table to public subnet");

            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                DestinationCidrBlock = "0.0.0.0/0",
                GatewayId            = response.InternetGateway.InternetGatewayId,
                RouteTableId         = response.PublicSubnetRouteTable.RouteTableId
            });
            WriteProgress(request.ProgressCallback, "Added route for internet gateway to route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            response.PublicSubnetRouteTable = ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables[0];
        }
Ejemplo n.º 51
0
        public static string GetServiceOutput()
        {
            StringBuilder sb = new StringBuilder(1024);

            using (StringWriter sr = new StringWriter(sb))
            {
                sr.WriteLine("===========================================");
                sr.WriteLine("Welcome to the AWS .NET SDK!");
                sr.WriteLine("===========================================");

                // Print the number of Amazon EC2 instances.
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client();
                DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();

                try
                {
                    DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request);
                    int numInstances = 0;
                    numInstances = ec2Response.DescribeInstancesResult.Reservation.Count;
                    sr.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running in the US-East (Northern Virginia) region.");
                }
                catch (AmazonEC2Exception ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon EC2.");
                        sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon SimpleDB domains.
                AmazonSimpleDB     sdb        = AWSClientFactory.CreateAmazonSimpleDBClient();
                ListDomainsRequest sdbRequest = new ListDomainsRequest();

                try
                {
                    ListDomainsResponse sdbResponse = sdb.ListDomains(sdbRequest);

                    if (sdbResponse.IsSetListDomainsResult())
                    {
                        int numDomains = 0;
                        numDomains = sdbResponse.ListDomainsResult.DomainName.Count;
                        sr.WriteLine("You have " + numDomains + " Amazon SimpleDB domain(s) in the US-East (Northern Virginia) region.");
                    }
                }
                catch (AmazonSimpleDBException ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB.");
                        sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon S3 Buckets.
                AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client();

                try
                {
                    ListBucketsResponse response = s3Client.ListBuckets();
                    int numBuckets = 0;
                    if (response.Buckets != null &&
                        response.Buckets.Count > 0)
                    {
                        numBuckets = response.Buckets.Count;
                    }
                    sr.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s) in the US Standard region.");
                }
                catch (AmazonS3Exception ex)
                {
                    if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                                                 ex.ErrorCode.Equals("InvalidSecurity")))
                    {
                        sr.WriteLine("Please check the provided AWS Credentials.");
                        sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine("Press any key to continue...");
            }
            return(sb.ToString());
        }
Ejemplo n.º 52
0
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder(1024);
            using (StringWriter sr = new StringWriter(sb))
            {
                try
                {
                    ec2 = AWSClientFactory.CreateAmazonEC2Client(RegionEndpoint.USWest2);
                    this.WriteEC2Info();
                }
                catch (AmazonEC2Exception ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon EC2.");
                        sr.WriteLine("<br />");
                        sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("<br />");
                        sr.WriteLine("XML: " + ex.XML);
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    this.ec2Placeholder.Text = sr.ToString();
                }
            }

            sb = new StringBuilder(1024);
            using (StringWriter sr = new StringWriter(sb))
            {
                try
                {
                    s3 = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest2);
                    this.WriteS3Info();
                }
                catch (AmazonS3Exception ex)
                {
                    if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                        ex.ErrorCode.Equals("InvalidSecurity")))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon S3");
                        sr.WriteLine("<br />");
                        sr.WriteLine("You can sign up for Amazon S3 at http://aws.amazon.com/s3");
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("<br />");
                        sr.WriteLine("XML: " + ex.XML);
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    this.s3Placeholder.Text = sr.ToString();
                }
            }

            sb = new StringBuilder(1024);
            using (StringWriter sr = new StringWriter(sb))
            {
                try
                {
                    sdb = AWSClientFactory.CreateAmazonSimpleDBClient(RegionEndpoint.USWest2);
                    this.WriteSimpleDBInfo();
                }
                catch (AmazonSimpleDBException ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("InvalidClientTokenId"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB.");
                        sr.WriteLine("<br />");
                        sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb");
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    else
                    {
                        sr.WriteLine("Exception Message: " + ex.Message);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("<br />");
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("<br />");
                        sr.WriteLine("XML: " + ex.XML);
                        sr.WriteLine("<br />");
                        sr.WriteLine("<br />");
                    }
                    this.sdbPlaceholder.Text = sr.ToString();
                }
            }
        }
        /// <summary>
        /// Find the Amazon machine image identified by the ImageDescriptor.
        /// </summary>
        /// <param name="ec2Client">The EC2 client used to search for the image.</param>
        /// <param name="descriptor">The descriptor used to identify the image.</param>
        /// <returns>The Amazon machine image.</returns>
        public static Image FindImage(AmazonEC2 ec2Client, ImageDescriptor descriptor)
        {
            if (ec2Client == null)
                throw new ArgumentNullException("ec2Client");
            if (descriptor == null)
                throw new ArgumentNullException("descriptor");

            int retryCount = 1;
            Image image = null;
            do
            {
                var result = ec2Client.DescribeImages(new DescribeImagesRequest()
                {
                    Owner = new List<string>() { "amazon" },
                    Filter = new List<Filter>()
                {
                    new Filter(){Name = "name", Value = new List<string>(){descriptor.NamePrefix}}
                }
                }).DescribeImagesResult;

                if (result.Image.Count != 0)
                    image = result.Image.OrderByDescending(x => x.Name).First();
                else
                {
                    // backing control file may be outdated, reload and try once more
                    if (retryCount == 1)
                    {
                        LOGGER.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading",
                                          descriptor.DefinitionKey,
                                          descriptor.NamePrefix);
                        LoadDefinitionsFromWeb();
                    }
                    retryCount++;
                }
            } while (image == null && retryCount <= 2);

            if (image == null)
                LOGGER.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')",
                                  descriptor.DefinitionKey,
                                  descriptor.NamePrefix);

            return image;
        }
        private static RunningInstance WaitForInstanceToStartUp(AmazonEC2 ec2Client, string instanceId)
        {
            var describeRequest = new DescribeInstancesRequest() { InstanceId = new List<string>() { instanceId } };
            for (int tries = 0; tries < 40; tries++)
            {
                Thread.Sleep(10 * 1000);

                var result = ec2Client.DescribeInstances(describeRequest).DescribeInstancesResult;
                if (result.Reservation.Count != 1 && result.Reservation[0].RunningInstance.Count != 1)
                    return null;

                RunningInstance instance = result.Reservation[0].RunningInstance[0];

                // Return the updated instance object if we're out of pending
                if (!instance.InstanceState.Name.Equals("pending"))
                {
                    return instance;
                }
            }

            return null;
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Describes the status of the indicated or, in lieu of any specified,  all volumes belonging to the caller. Volumes that have been deleted are not described.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeVolumesRequest request</param>
        public static void InvokeDescribeVolumes(AmazonEC2 service, DescribeVolumesRequest request)
        {
            try 
            {
                DescribeVolumesResponse response = service.DescribeVolumes(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeVolumesResponse");
                if (response.IsSetDescribeVolumesResult())
                {
                    Console.WriteLine("            DescribeVolumesResult");
                    DescribeVolumesResult  describeVolumesResult = response.DescribeVolumesResult;
                    List<Volume> volumeList = describeVolumesResult.Volume;
                    foreach (Volume volume in volumeList)
                    {
                        Console.WriteLine("                Volume");
                        if (volume.IsSetVolumeId())
                        {
                            Console.WriteLine("                    VolumeId");
                            Console.WriteLine("                        {0}", volume.VolumeId);
                        }
                        if (volume.IsSetSize())
                        {
                            Console.WriteLine("                    Size");
                            Console.WriteLine("                        {0}", volume.Size);
                        }
                        if (volume.IsSetSnapshotId())
                        {
                            Console.WriteLine("                    SnapshotId");
                            Console.WriteLine("                        {0}", volume.SnapshotId);
                        }
                        if (volume.IsSetAvailabilityZone())
                        {
                            Console.WriteLine("                    AvailabilityZone");
                            Console.WriteLine("                        {0}", volume.AvailabilityZone);
                        }
                        if (volume.IsSetStatus())
                        {
                            Console.WriteLine("                    Status");
                            Console.WriteLine("                        {0}", volume.Status);
                        }
                        if (volume.IsSetCreateTime())
                        {
                            Console.WriteLine("                    CreateTime");
                            Console.WriteLine("                        {0}", volume.CreateTime);
                        }
                        List<Attachment> attachmentList = volume.Attachment;
                        foreach (Attachment attachment in attachmentList)
                        {
                            Console.WriteLine("                    Attachment");
                            if (attachment.IsSetVolumeId())
                            {
                                Console.WriteLine("                        VolumeId");
                                Console.WriteLine("                            {0}", attachment.VolumeId);
                            }
                            if (attachment.IsSetInstanceId())
                            {
                                Console.WriteLine("                        InstanceId");
                                Console.WriteLine("                            {0}", attachment.InstanceId);
                            }
                            if (attachment.IsSetDevice())
                            {
                                Console.WriteLine("                        Device");
                                Console.WriteLine("                            {0}", attachment.Device);
                            }
                            if (attachment.IsSetStatus())
                            {
                                Console.WriteLine("                        Status");
                                Console.WriteLine("                            {0}", attachment.Status);
                            }
                            if (attachment.IsSetAttachTime())
                            {
                                Console.WriteLine("                        AttachTime");
                                Console.WriteLine("                            {0}", attachment.AttachTime);
                            }
                        }
                    }
                }
                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);
            }
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Detach a previously attached volume from a running instance.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DetachVolumeRequest request</param>
        public static void InvokeDetachVolume(AmazonEC2 service, DetachVolumeRequest request)
        {
            try 
            {
                DetachVolumeResponse response = service.DetachVolume(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DetachVolumeResponse");
                if (response.IsSetDetachVolumeResult())
                {
                    Console.WriteLine("            DetachVolumeResult");
                    DetachVolumeResult  detachVolumeResult = response.DetachVolumeResult;
                    if (detachVolumeResult.IsSetAttachment())
                    {
                        Console.WriteLine("                Attachment");
                        Attachment  attachment = detachVolumeResult.Attachment;
                        if (attachment.IsSetVolumeId())
                        {
                            Console.WriteLine("                    VolumeId");
                            Console.WriteLine("                        {0}", attachment.VolumeId);
                        }
                        if (attachment.IsSetInstanceId())
                        {
                            Console.WriteLine("                    InstanceId");
                            Console.WriteLine("                        {0}", attachment.InstanceId);
                        }
                        if (attachment.IsSetDevice())
                        {
                            Console.WriteLine("                    Device");
                            Console.WriteLine("                        {0}", attachment.Device);
                        }
                        if (attachment.IsSetStatus())
                        {
                            Console.WriteLine("                    Status");
                            Console.WriteLine("                        {0}", attachment.Status);
                        }
                        if (attachment.IsSetAttachTime())
                        {
                            Console.WriteLine("                    AttachTime");
                            Console.WriteLine("                        {0}", attachment.AttachTime);
                        }
                    }
                }
                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);
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        /// CancelBundleTask operation cancels a pending or
        /// in-progress bundling task. This is an asynchronous
        /// call and it make take a while for the task to be cancelled.
        /// If a task is cancelled while it is storing items,
        /// there may be parts of the incomplete AMI stored in S3.
        /// It is up to the caller to clean up these parts from S3.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">CancelBundleTaskRequest request</param>
        public static void InvokeCancelBundleTask(AmazonEC2 service, CancelBundleTaskRequest request)
        {
            try 
            {
                CancelBundleTaskResponse response = service.CancelBundleTask(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        CancelBundleTaskResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetCancelBundleTaskResult())
                {
                    Console.WriteLine("            CancelBundleTaskResult");
                    CancelBundleTaskResult  cancelBundleTaskResult = response.CancelBundleTaskResult;
                    List<BundleTask> bundleTaskList = cancelBundleTaskResult.BundleTask;
                    foreach (BundleTask bundleTask in bundleTaskList)
                    {
                        Console.WriteLine("                BundleTask");
                        if (bundleTask.IsSetInstanceId())
                        {
                            Console.WriteLine("                    InstanceId");
                            Console.WriteLine("                        {0}", bundleTask.InstanceId);
                        }
                        if (bundleTask.IsSetBundleId())
                        {
                            Console.WriteLine("                    BundleId");
                            Console.WriteLine("                        {0}", bundleTask.BundleId);
                        }
                        if (bundleTask.IsSetBundleState())
                        {
                            Console.WriteLine("                    BundleState");
                            Console.WriteLine("                        {0}", bundleTask.BundleState);
                        }
                        if (bundleTask.IsSetStartTime())
                        {
                            Console.WriteLine("                    StartTime");
                            Console.WriteLine("                        {0}", bundleTask.StartTime);
                        }
                        if (bundleTask.IsSetUpdateTime())
                        {
                            Console.WriteLine("                    UpdateTime");
                            Console.WriteLine("                        {0}", bundleTask.UpdateTime);
                        }
                        if (bundleTask.IsSetStorage())
                        {
                            Console.WriteLine("                    Storage");
                            Storage  storage = bundleTask.Storage;
                            if (storage.IsSetS3())
                            {
                                Console.WriteLine("                        S3");
                                S3Storage  s3 = storage.S3;
                                if (s3.IsSetBucket())
                                {
                                    Console.WriteLine("                            Bucket");
                                    Console.WriteLine("                                {0}", s3.Bucket);
                                }
                                if (s3.IsSetPrefix())
                                {
                                    Console.WriteLine("                            Prefix");
                                    Console.WriteLine("                                {0}", s3.Prefix);
                                }
                                if (s3.IsSetAWSAccessKeyId())
                                {
                                    Console.WriteLine("                            AWSAccessKeyId");
                                    Console.WriteLine("                                {0}", s3.AWSAccessKeyId);
                                }
                                if (s3.IsSetUploadPolicy())
                                {
                                    Console.WriteLine("                            UploadPolicy");
                                    Console.WriteLine("                                {0}", s3.UploadPolicy);
                                }
                                if (s3.IsSetUploadPolicySignature())
                                {
                                    Console.WriteLine("                            UploadPolicySignature");
                                    Console.WriteLine("                                {0}", s3.UploadPolicySignature);
                                }
                            }
                        }
                        if (bundleTask.IsSetProgress())
                        {
                            Console.WriteLine("                    Progress");
                            Console.WriteLine("                        {0}", bundleTask.Progress);
                        }
                        if (bundleTask.IsSetBundleTaskError())
                        {
                            Console.WriteLine("                    BundleTaskError");
                            BundleTaskError  bundleTaskError = bundleTask.BundleTaskError;
                            if (bundleTaskError.IsSetCode())
                            {
                                Console.WriteLine("                        Code");
                                Console.WriteLine("                            {0}", bundleTaskError.Code);
                            }
                            if (bundleTaskError.IsSetMessage())
                            {
                                Console.WriteLine("                        Message");
                                Console.WriteLine("                            {0}", bundleTaskError.Message);
                            }
                        }
                    }
                }

            } 
            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);
            }
        }
Ejemplo n.º 58
0
 private bool IsInstancePending(AmazonEC2 ec2Client, string instanceId)
 {
     return(GetInstanceStatus(ec2Client, instanceId) == "pending");
 }
        private static RouteTable GetDefaultRouteTable(AmazonEC2 ec2Client, string vpcId)
        {
            var filters = new List<Filter>()
            {
                new Filter() { Name = "vpc-id", Value = new List<string>() { vpcId } },
                new Filter() { Name = "association.main", Value = new List<string>() { "true" } }
            };

            var response = ec2Client.DescribeRouteTables(new DescribeRouteTablesRequest() { Filter = filters });
            if (response.DescribeRouteTablesResult.RouteTables.Count != 1)
                return null;

            return response.DescribeRouteTablesResult.RouteTables[0];
        }
        /// <summary>
        /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <param name="response">The response contains all the VPC objects that were created.</param>
        private static void LaunchVPCWithPublicSubnet(AmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request, LaunchVPCWithPublicSubnetResponse response)
        {
            response.VPC = ec2Client.CreateVpc(new CreateVpcRequest()
            {
                CidrBlock = request.VPCCidrBlock,
                InstanceTenancy = request.InstanceTenancy
            }).CreateVpcResult.Vpc;
            WriteProgress(request.ProgressCallback, "Created vpc {0}", response.VPC.VpcId);

            var describeVPCRequest = new DescribeVpcsRequest() { VpcId = new List<string>() { response.VPC.VpcId } };
            WaitTillTrue(((Func<bool>)(() => ec2Client.DescribeVpcs(describeVPCRequest).DescribeVpcsResult.Vpc.Count == 1)));

            if(!string.IsNullOrEmpty(request.VPCName))
            {
                ec2Client.CreateTags(new CreateTagsRequest()
                {
                    ResourceId = new List<string>(){ response.VPC.VpcId},
                    Tag = new List<Tag>(){new Tag(){Key = "Name", Value = request.VPCName}}
                });
            }

            response.PublicSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PublicSubnetAvailabilityZone,
                CidrBlock = request.PublicSubnetCiderBlock,
                VpcId = response.VPC.VpcId
            }).CreateSubnetResult.Subnet;
            WriteProgress(request.ProgressCallback, "Created public subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest() { SubnetId = new List<string>() { response.PublicSubnet.SubnetId } }).DescribeSubnetsResult.Subnet.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { response.PublicSubnet.SubnetId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "Public" } }
            });

            response.InternetGateway = ec2Client.CreateInternetGateway(new CreateInternetGatewayRequest()
            {
            }).CreateInternetGatewayResult.InternetGateway;
            WriteProgress(request.ProgressCallback, "Created internet gateway {0}", response.InternetGateway.InternetGatewayId);

            ec2Client.AttachInternetGateway(new AttachInternetGatewayRequest()
            {
                InternetGatewayId = response.InternetGateway.InternetGatewayId,
                VpcId = response.VPC.VpcId
            });
            WriteProgress(request.ProgressCallback, "Attached internet gateway to vpc");

            response.PublicSubnetRouteTable = ec2Client.CreateRouteTable(new CreateRouteTableRequest()
            {
                VpcId = response.VPC.VpcId
            }).CreateRouteTableResult.RouteTable;
            WriteProgress(request.ProgressCallback, "Created route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            var describeRouteTableRequest = new DescribeRouteTablesRequest() { RouteTableId = new List<string>() { response.PublicSubnetRouteTable.RouteTableId } };
            WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { response.PublicSubnetRouteTable.RouteTableId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "Public" } }
            });

            ec2Client.AssociateRouteTable(new AssociateRouteTableRequest()
            {
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId,
                SubnetId = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "Associated route table to public subnet");

            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                DestinationCidrBlock = "0.0.0.0/0",
                GatewayId = response.InternetGateway.InternetGatewayId,
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId
            });
            WriteProgress(request.ProgressCallback, "Added route for internet gateway to route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            response.PublicSubnetRouteTable = ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables[0];
        }