Implementation for accessing EC2 Amazon Elastic Compute Cloud

Amazon Elastic Compute Cloud (Amazon EC2) provides resizable computing capacity in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your need to invest in hardware up front, so you can develop and deploy applications faster.

Inheritance: AmazonServiceClient, IAmazonEC2
Example #1
1
        public override void Execute()
        {
            AmazonEC2Client client = new AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
            DescribeSnapshotsResponse response = client.DescribeSnapshots(request);

            Dictionary<string, List<Amazon.EC2.Model.Snapshot>> snapshots = new Dictionary<string, List<Amazon.EC2.Model.Snapshot>>();
            foreach (Amazon.EC2.Model.Snapshot r in response.DescribeSnapshotsResult.Snapshot)
            {
                if (!snapshots.ContainsKey(r.VolumeId))
                    snapshots[r.VolumeId] = new List<Amazon.EC2.Model.Snapshot>();

                snapshots[r.VolumeId].Add(r);
            }

            foreach (string volumeId in snapshots.Keys)
            {
                Console.WriteLine("--- Volume: {0}", volumeId);
                snapshots[volumeId].Sort(delegate(Amazon.EC2.Model.Snapshot x,Amazon.EC2.Model.Snapshot y)
                    { return DateTime.Parse(x.StartTime).CompareTo(DateTime.Parse(y.StartTime)); });

                foreach (Amazon.EC2.Model.Snapshot s in snapshots[volumeId])
                {
                    DateTime startTime = DateTime.Parse(s.StartTime);
                    Console.Write("{0}\t{1}\t{2}\t{3}", s.SnapshotId, startTime, s.Progress, s.Status);
                    Console.WriteLine();
                }

                Console.WriteLine();
            }
        }
		//this quite an expensive operation (3M of data retrieved) - so I added caching support
		public static List<Image> getImagesList(this API_AmazonEC2 amazonEC2, AmazonEC2Client ec2Client)
		{										
			if (amazonEC2.CachedImageListRequest.fileExists())
				return amazonEC2.CachedImageListRequest.load<List<Amazon.EC2.Model.Image>>(); 
				
			var describeImagesRequest = new DescribeImagesRequest(); 				
			"Retrieving ImagesList from Amazon..".info();	
			var images = ec2Client.DescribeImages(describeImagesRequest)
					  .DescribeImagesResult.Image;
			if (images.isNull() || images.size()==0)
			{
				"in getImagesList, there was an error retrieving list (are we online?)".error();				
			}
			else
			{
				amazonEC2.CachedImageListRequest = images.save();
				"The Image List was saved to : {0}".info(amazonEC2.CachedImageListRequest);  
			}
			return images;
		}				
Example #3
0
        private static void ChangeInstanceTags(int changeType)
        {
            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client();
            DescribeInstancesResponse instanceResponse = ec2.DescribeInstances();
            var resourceIdList = new List <string>();
            var tagsList       = new List <Tag>();

            tagsList.Add(new Tag {
                Key = "Test1-AutoAdded", Value = "ToInduceConfigChages"
            });
            tagsList.Add(new Tag {
                Key = "Test2-AutoAdded", Value = "ToInduceConfigChages"
            });
            foreach (var reservation in instanceResponse.Reservations)
            {
                foreach (var rInstance in reservation.Instances)
                {
                    resourceIdList.Add(rInstance.InstanceId);
                }
            }
            if (changeType == 0)
            {
                var createTagsRequest = new CreateTagsRequest(resourceIdList, tagsList);
                ec2.CreateTags(createTagsRequest);
            }
            else if (changeType == 1)
            {
                var deleteTagsRequest = new DeleteTagsRequest();
                deleteTagsRequest.Resources = resourceIdList;
                deleteTagsRequest.Tags      = tagsList;
                ec2.DeleteTags(deleteTagsRequest);
            }
        }
            public void DryRun(AmazonEC2Client client, AmazonEC2Request request, ref DryRunResponse response)
            {
                response.IsSuccessful = false;

                SetDryRun(request, true);
                try
                {
                    Method.Invoke(client, new object[] { request });
                    // If no exception thrown, consider this a failure
                    response.Message = "Unrecognized service response for the dry-run request.";
                }
                catch (Exception invokeException)
                {
                    Exception actualException = invokeException.InnerException;
                    AmazonEC2Exception ec2e = actualException as AmazonEC2Exception;

                    response.Message = actualException.Message;
                    if (ec2e != null)
                    {
                        response.IsSuccessful = ec2e.StatusCode == HttpStatusCode.PreconditionFailed;
                        response.ResponseMetadata = new ResponseMetadata
                        {
                            RequestId = ec2e.RequestId
                        };
                    }

                    if (!response.IsSuccessful)
                        response.Error = actualException;
                }
                finally
                {
                    SetDryRun(request, false);
                }
            }
Example #5
0
        private static void ManageInstanceSecurityGroups()
        {
            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client();
            DescribeInstancesResponse instanceResponse = ec2.DescribeInstances();

            foreach (var reservation in instanceResponse.Reservations)
            {
                foreach (var rInstance in reservation.Instances)
                {
                    var securityGroupList = new List <string>();
                    foreach (var groupIdentifier in rInstance.SecurityGroups)
                    {
                        securityGroupList.Add(groupIdentifier.GroupId);
                    }
                    if (!securityGroupList.Contains("sg-9cc4a3fb"))
                    {
                        securityGroupList.Add("sg-9cc4a3fb");
                    }
                    else
                    {
                        securityGroupList.Remove("sg-9cc4a3fb");
                    }
                    var modifyInstanceAttributeRequest = new ModifyInstanceAttributeRequest();
                    modifyInstanceAttributeRequest.InstanceId = rInstance.InstanceId;
                    modifyInstanceAttributeRequest.Groups     = securityGroupList;
                    try
                    {
                        ec2.ModifyInstanceAttribute(modifyInstanceAttributeRequest);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
		public static List<string> getEC2Regions(this API_AmazonEC2 amazonEC2)
		{
			var ec2Client = new AmazonEC2Client(amazonEC2.ApiKey.UserName, amazonEC2.ApiKey.Password); 
			return (from region in  ec2Client.DescribeRegions(new DescribeRegionsRequest())
		 		      			 			.DescribeRegionsResult.Region
					select region.RegionName).toList();
		}
        public async Task<string> GetPrivateSubnetIdAsync(string vpcId, string availabilityZone)
        {
            using (var ec2Client = new AmazonEC2Client(credentials, ec2ConfigurationProvider.RegionEndpoint))
            {
                var allSubnetsInMyVpcAndAz = await ec2Client.DescribeSubnetsAsync(new DescribeSubnetsRequest
                {
                    Filters = new List<Filter>
                    {
                        new Filter {Name = "vpc-id", Values = new List<string> {vpcId}},
                        new Filter {Name = "availabilityZone", Values = new List<string> {availabilityZone}}
                    }
                });

                var privateSubnet = allSubnetsInMyVpcAndAz.Subnets.SingleOrDefault(s => s.Tags.Any(t =>
                    string.Equals(t.Key, "AccessLevel", StringComparison.CurrentCultureIgnoreCase) &&
                    string.Equals(t.Value, "private", StringComparison.CurrentCultureIgnoreCase)));
                if (privateSubnet == null)
                {
                    var message = $"Could not locate private subnet for vpc:{vpcId} and az:{availabilityZone}";
                    loggerProvider.GetLogger().Error(message);
                    throw new Ec2ServiceException(message);
                }

                return privateSubnet.SubnetId;
            }
        }
Example #8
0
        public static void ReadFlowLogs(string accountNumber, RegionEndpoint regionEndPoint, int durationType, IDatabase db)
        {
            Log.InfoFormat("Start reading flowlogs and writing traffic data to redis ({0})", regionEndPoint.SystemName);
            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client(regionEndPoint);

            try
            {
                ec2.DescribeSubnets();
            }
            catch (Exception ex)
            {
                Log.InfoFormat("Unable to read subnets: {0}", ex.Message);
                return;
            }

            var dataKey = Common.GetDataKey(accountNumber, regionEndPoint);

            db.SetAdd("TST", dataKey);
            db.StringSet(string.Format("LATESTTST-{0}-{1}", accountNumber, regionEndPoint.SystemName), dataKey);

            var subnetResponse = ec2.DescribeSubnets();
            var vgResponse     = ec2.DescribeVpnGateways();
            var igResponse     = ec2.DescribeInternetGateways();

            try
            {
                FlowLogManager.ReadES(db, dataKey, durationType, subnetResponse.Subnets, vgResponse.VpnGateways, igResponse.InternetGateways);
                Log.InfoFormat("End reading flowlogs and writing traffic data to redis ({0})", regionEndPoint.SystemName);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Error reading flowlogs and writing traffic data to redis ({0}): {1}", regionEndPoint.SystemName, ex.Message);
            }
        }
        public static Ec2Response StartServer(DeveloperOptions developerOptions)
        {
            try
            {
                var ec2Config = new AmazonEC2Config { AuthenticationRegion = developerOptions.RegionEndpont };

                var ec2Client = new AmazonEC2Client(
                    new BasicAWSCredentials(developerOptions.AccessKey, developerOptions.SecretAccessKey), ec2Config);

                var launchRequest = new RunInstancesRequest
                {
                    ImageId = developerOptions.AmiId,
                    InstanceType = developerOptions.InstanceType,
                    MinCount = 1,
                    MaxCount = 1,
                    KeyName = developerOptions.Ec2KeyPair,
                    SecurityGroupIds = new List<string> { developerOptions.SecurityGroupId }
                };
                var launchResponse = ec2Client.RunInstances(launchRequest);
                if (launchResponse.HttpStatusCode.Equals(HttpStatusCode.OK))
                {
                    while (true)
                    {
                        var instances = ec2Client.DescribeInstances();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            // TODO
            return null;
        }
 /// <summary>
 ///     This method kicks off the process of the server sending out the tests
 /// </summary>
 /// <param name="testSuite"></param>
 /// <returns></returns>
 public async Task BeginTestRun(TestSuite testSuite)
 {
     //first thing we do is make sure all test runs have ips, if they dont we set them
     //up in AWS, this is very tighly coupled at the moment. we get the instance ids back so we 
     //can close them later
     Log4NetLogger.LogEntry(GetType(), "BeginTestRun", "starting test run", LoggerLevel.Info);
     var ec2Client = new AmazonEC2Client(RegionEndpoint.EUWest1);
     Log4NetLogger.LogEntry(GetType(), "BeginTestRun", "created EC2 client, now assiging ips", LoggerLevel.Info);
     List<string> instanceIds = AssignAgentIps(ec2Client, testSuite);
     Log4NetLogger.LogEntry(GetType(), "BeginTestRun",
         "assigned ips if there were any required, about to run tests", LoggerLevel.Info);
     //now we need to send our dlls to the agents
     UploadDllsToAgents(testSuite);
     //once we are all good we run the tests. 
     await Run(testSuite);
     Log4NetLogger.LogEntry(GetType(), "BeginTestRun", "tests have finished running, now terminate any agents",
         LoggerLevel.Info);
     //we return null from AssignAgentIps if we dont need any IPs, bad programming but it will do 
     //for now.
     if (instanceIds != null)
     {
         Log4NetLogger.LogEntry(GetType(), "BeginTestRun", "terminating agents", LoggerLevel.Info);
         //terminate the agents LIKE A BAUSSSSSSSSSSS
         TerminateAgents(ec2Client, instanceIds);
         Log4NetLogger.LogEntry(GetType(), "BeginTestRun", "terminated agents", LoggerLevel.Info);
     }
 }
        public override void Execute()
        {
            Amazon.EC2.AmazonEC2Client client = new Amazon.EC2.AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            List<string> snapshotsToDelete = new List<string>();

            if (isVolumeId)
            {
                // delete snapshots belonging to this volume
                DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
                DescribeSnapshotsResponse response = client.DescribeSnapshots(request);

                foreach (Amazon.EC2.Model.Snapshot s in response.DescribeSnapshotsResult.Snapshot)
                {
                    if (string.Equals(s.VolumeId, id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DateTime snapshotDate = DateTime.Parse(s.StartTime);
                        if (snapshotDate.AddDays(days) < DateTime.Now)
                            snapshotsToDelete.Add(s.SnapshotId);
                    }
                }
            }
            else
            {
                snapshotsToDelete.Add(id);
            }

            foreach (string snapshotId in snapshotsToDelete)
            {
                Console.WriteLine("Deleting snapshot ID {0}", snapshotId);
                Amazon.EC2.Model.DeleteSnapshotRequest request = new Amazon.EC2.Model.DeleteSnapshotRequest();
                request.SnapshotId = snapshotId;
                Amazon.EC2.Model.DeleteSnapshotResponse response = client.DeleteSnapshot(request);
            }
        }
        public Snapper(int DurationInHours, ArrayList VolumeIDs, int NumberOfSnapsToKeep)
        {
            aec = new AmazonEC2Client(new AmazonEC2Config());

            volumes = VolumeIDs;
            hours = DurationInHours;
            snaps2keep = NumberOfSnapsToKeep;
        }
        public static AmazonEC2Client GetEc2Connection()
        {
            if (ec2 == null)
            {
                ec2 = new AmazonEC2Client(AwsKeyProviders.Key, AwsKeyProviders.Secret, RegionEndpoint.EUWest1);
            }

            return ec2;
        }
Example #14
0
        private static void ManageSecurityGroups()
        {
            IAmazonEC2 ec2        = new Amazon.EC2.AmazonEC2Client();
            var        sgResponse = ec2.DescribeSecurityGroups();

            string        ipRange = "22.22.22.22/0";
            List <string> ranges  = new List <string>()
            {
                ipRange
            };

            var ipPermission = new IpPermission();

            ipPermission.IpProtocol = "tcp";
            ipPermission.FromPort   = 3333;
            ipPermission.ToPort     = 3333;
            ipPermission.IpRanges   = ranges;

            var ingressRequest = new AuthorizeSecurityGroupIngressRequest();

            ingressRequest.IpPermissions.Add(ipPermission);
            var revokeRequest = new RevokeSecurityGroupIngressRequest();

            revokeRequest.IpPermissions.Add(ipPermission);
            foreach (var sg in sgResponse.SecurityGroups)
            {
                try
                {
                    if (new Random().Next(2) == 1)
                    {
                        ingressRequest.GroupId = sg.GroupId;
                        var ingressResponse = ec2.AuthorizeSecurityGroupIngress(ingressRequest);
                    }
                    else
                    {
                        revokeRequest.GroupId = sg.GroupId;
                        ec2.RevokeSecurityGroupIngress(revokeRequest);
                    }
                    //Console.WriteLine("New RDP rule for: " + ipRange);
                }
                catch (AmazonEC2Exception ex)
                {
                    // Check the ErrorCode to see if the rule already exists.
                    if ("InvalidPermission.Duplicate" == ex.ErrorCode)
                    {
                        //Console.WriteLine("An RDP rule for: {0} already exists.", ipRange);
                    }
                    else
                    {
                        // The exception was thrown for another reason, so re-throw the exception.
                        //throw;
                    }
                }
            }
        }
        /// <summary>
        /// Return the EC2 client
        /// </summary>
        /// <returns></returns>
        public static AmazonEC2Client CreateClient()
        {
            AmazonEC2Config config = new AmazonEC2Config();
            config.ServiceURL = "https://ec2." + Program.options.Region + ".amazonaws.com";
            //config.RegionEndpoint = RegionEndpoint.USEast1;

            AmazonEC2Client ec2 = new Amazon.EC2.AmazonEC2Client(Program.options.AccessKey, Program.options.SecretKey, config);
            //AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(Program.options.AccessKey, Program.options.SecretKey, config);

            return ec2;
        }
Example #16
0
        public Ec2Instance(AmazonEC2Client client, Config config, string name, InstanceSpecification specification)
        {
            this.Client = client;
            this.config = config;
            this.Name = name;
            this.Specification = specification;
            this.uniqueKey = Guid.NewGuid().ToString();

            this.state = CreationState.DoesntExist;

            this.Logger = new StubLogger();
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			
			var client = new AmazonEC2Client (new BasicAWSCredentials (ACCESS_KEY, SECRET_KEY), Amazon.RegionEndpoint.USEast1);
			var response = client.AllocateAddress ();

			var textView = new UITextView (new RectangleF (new PointF (64.0f, 64.0f), new SizeF (96.0f, 32.0f)));

			textView.Text = response.PublicIp;

			this.View.AddSubview (textView);
		}
Example #18
0
        /// <summary>
        /// Return the EC2 client
        /// </summary>
        /// <returns></returns>
        public static AmazonEC2Client CreateClient()
        {
            AmazonEC2Config config = new AmazonEC2Config();

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

            AmazonEC2Client ec2 = new Amazon.EC2.AmazonEC2Client(Program.options.AccessKey, Program.options.SecretKey, config);

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

            return(ec2);
        }
Example #19
0
        public override void Execute()
        {
            AmazonEC2Client client = new AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            DescribeInstancesRequest request = new DescribeInstancesRequest();
            DescribeInstancesResponse response = client.DescribeInstances(request);

            Dictionary<string, List<RunningInstance>> instances = new Dictionary<string, List<RunningInstance>>();
            foreach (Reservation r in response.DescribeInstancesResult.Reservation)
                foreach (RunningInstance i in r.RunningInstance)
                {
                    if (!instances.ContainsKey(i.ImageId))
                        instances[i.ImageId] = new List<RunningInstance>();

                    instances[i.ImageId].Add(i);
                }

            List<string> allImageIds = new List<string>();
            foreach (string imageId in instances.Keys)
                allImageIds.Add(imageId);

            DescribeImagesRequest imageReq = new DescribeImagesRequest();
            imageReq.ImageId = allImageIds;
            DescribeImagesResponse imageResp = client.DescribeImages(imageReq);

            Dictionary<string, Image> imageDescriptions = new Dictionary<string, Image>();
            foreach (Image image in imageResp.DescribeImagesResult.Image)
                imageDescriptions.Add(image.ImageId, image);

            foreach (string imageId in instances.Keys)
            {
                if (imageDescriptions.ContainsKey(imageId))
                    Console.WriteLine("--- {0} {1} ({2} {3})",
                        imageId,
                        imageDescriptions[imageId].ImageLocation,
                        imageDescriptions[imageId].Platform,
                        imageDescriptions[imageId].Architecture);
                else
                    Console.WriteLine("--- {0} (AMI not found)", imageId);

                foreach (RunningInstance i in instances[imageId])
                {
                    DateTime launchTime = DateTime.Parse(i.LaunchTime);
                    Console.Write("{0}\t{1}\t{2}\t{3}\t{4}", launchTime, i.InstanceType, i.InstanceState.Name, i.InstanceId, i.StateTransitionReason);
                    if (ips)
                        Console.Write("\t{0}\t{1}", i.PublicDnsName, i.PrivateDnsName);
                    Console.WriteLine();
                }

                Console.WriteLine();
            }
        }
Example #20
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			var textView = FindViewById<TextView> (Resource.Id.textView1);

			var client = new AmazonEC2Client (new BasicAWSCredentials (ACCESS_KEY, SECRET_KEY), Amazon.RegionEndpoint.USEast1);
			var response = client.AllocateAddress ();

			textView.Text = response.PublicIp;
		}
Example #21
0
        public override void Execute()
        {
            Amazon.EC2.AmazonEC2Client client = new Amazon.EC2.AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            List <string> snapshotsToDelete   = new List <string>();

            if (isVolumeId)
            {
                // delete snapshots belonging to this volume
                DescribeSnapshotsRequest  request  = new DescribeSnapshotsRequest();
                DescribeSnapshotsResponse response = client.DescribeSnapshots(request);

                foreach (Amazon.EC2.Model.Snapshot s in response.DescribeSnapshotsResult.Snapshot)
                {
                    if (string.Equals(s.VolumeId, id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DateTime snapshotDate = DateTime.Parse(s.StartTime);
                        if (snapshotDate.AddDays(days) < DateTime.Now)
                        {
                            snapshotsToDelete.Add(s.SnapshotId);
                        }
                    }
                }
            }
            else
            {
                snapshotsToDelete.Add(id);
            }

            foreach (string snapshotId in snapshotsToDelete)
            {
                Console.WriteLine("Deleting snapshot ID {0}", snapshotId);
                Amazon.EC2.Model.DeleteSnapshotRequest request = new Amazon.EC2.Model.DeleteSnapshotRequest();
                request.SnapshotId = snapshotId;
                //Amazon.EC2.Model.DeleteSnapshotResponse response =
                client.DeleteSnapshot(request);
            }
        }
        public async Task<string> GetVpcIdAsync()
        {
            using (var ec2Client = new AmazonEC2Client(credentials, ec2ConfigurationProvider.RegionEndpoint))
            {
                var filters = new List<Filter>
                {
                    new Filter("tag:Product", new List<string> { "Material" }),
                    new Filter("tag:Service", new List<string> { ec2ConfigurationProvider.ServiceName }),
                    new Filter("tag:DeploymentEnvironment", new List<string> { ec2ConfigurationProvider.DeploymentEnvironmentName })

                };
                var response = await ec2Client.DescribeVpcsAsync(new DescribeVpcsRequest { Filters = filters });

                var vpcs = response.Vpcs;

                //get vpc with latest created
                loggerProvider.GetLogger().Debug("Sorting VPCs by Created Tag with most recent time first.");
                vpcs.Sort((p, q) => {
                    var dtP = DateTime.Parse(p.Tags.First(t => t.Key == "Created").Value);
                    var dtQ = DateTime.Parse(q.Tags.First(t => t.Key == "Created").Value);

                    return DateTime.Compare(dtQ, dtP);
                });


                var materialVpc = vpcs.FirstOrDefault();
                if (materialVpc == null)
                {
                    var message = "Could not locate Material API VPC.";
                    loggerProvider.GetLogger().Error(message);
                    throw new Ec2ServiceException(message);
                }

                return materialVpc.VpcId;
            }
        }
Example #23
0
 private void Initialize(string ec2AccessKey, string ec2SecretKey, string serviceURL)
 {
     ec2 = new AmazonEC2Client(ec2AccessKey, ec2SecretKey, new AmazonEC2Config().WithServiceURL(serviceURL));
 }
        public async Task<List<string>> GetPublicSubnetIdsAsync(string vpcId, List<string> availabilityZones)
        {
            using (var ec2Client = new AmazonEC2Client(credentials, ec2ConfigurationProvider.RegionEndpoint))
            {
                var allSubnetsInMyVpcAndAz = await ec2Client.DescribeSubnetsAsync(new DescribeSubnetsRequest
                {
                    Filters = new List<Filter>
                    {
                        new Filter {Name = "vpc-id", Values = new List<string> {vpcId}},
                        new Filter {Name = "availabilityZone", Values = availabilityZones}
                    }
                });

                var publicSubnets = allSubnetsInMyVpcAndAz.Subnets
                    .Where(s => s.Tags.Any(t =>
                        string.Equals(t.Key, "AccessLevel", StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(t.Value, "public", StringComparison.CurrentCultureIgnoreCase)))
                    .ToList();
                if (publicSubnets.IsNullOrEmpty())
                {
                    var message =
                        $"Could not locate public subnet for vpc:{vpcId} and azs:{availabilityZones.Join(",")}";
                    loggerProvider.GetLogger().Error(message);
                    throw new Ec2ServiceException(message);
                }

                return publicSubnets.Select(publicSubnet => publicSubnet.SubnetId).ToList();
            }
        }
		public static List<Image> show_ImagesList_In_TreeView(this API_AmazonEC2 amazonEC2, AmazonEC2Client ec2Client, Control control)
		{				
			var treeView = control.clear().add_TreeView_with_PropertyGrid(false).sort();  	 
			treeView.parent().backColor(System.Drawing.Color.Azure);
			treeView.visible(false);
			Application.DoEvents();
			var imagesList = amazonEC2.getImagesList(ec2Client); 
			
			Func<Amazon.EC2.Model.Image,string> imageName = 
				(image)=> (image.Description.valid())
									? "{0} - {1}".format(image.Description, image.Name)
									: "{0}".format(image.Name).trim();
									
			Action<string> mapByProperty  = 
				(propertyName)=>{				
									var byPropertyNode = treeView.add_Node("by {0}".format(propertyName),"");
									foreach(var distinctPropertyValue in imagesList.Select((image)=>image.property(propertyName).str()).Distinct())
									{										
										var byDistinctPropertyValue = byPropertyNode.add_Node(distinctPropertyValue,"");

										var mappedByImageName = new Dictionary<string, List<Image>>();
										foreach(var imageInProperty in imagesList.Where((image) => image.property(propertyName).str() == distinctPropertyValue))
											mappedByImageName.add(imageName(imageInProperty),imageInProperty);																				
											
										foreach(var mappedData in mappedByImageName)
										{
											if (mappedData.Value.size() > 1)
												byDistinctPropertyValue.add_Node("{0}".format(mappedData.Key,mappedData.Value.size()))
														      		   .add_Nodes(mappedData.Value, imageName);
											else
												byDistinctPropertyValue.add_Node(imageName(mappedData.Value.first()),mappedData.Value.first());
										}			     
									}													  			
								};
			mapByProperty("Visibility");
			mapByProperty("ImageOwnerAlias");
			mapByProperty("Platform"); 
			mapByProperty("Architecture"); 
			"Completed processing show_ImagesList_In_TreeView".info();
			if (treeView.nodes().size()>0)
				treeView.backColor(System.Drawing.Color.White); 
			treeView.visible(true);				
			return imagesList;
		}
		public static List<Image> show_ImagesList_In_TreeView(this API_AmazonEC2 amazonEC2, AmazonEC2Client ec2Client)
		{
			return amazonEC2.show_ImagesList_In_TreeView(ec2Client, "Amazon EC2 Images List".popupWindow());
		}				
Example #27
0
       /**
        * Samples for Amazon EC2 functionality
        */
        public static void Main(string [] args) 
        {
            Console.WriteLine("===========================================");
            Console.WriteLine("Welcome to Amazon EC2 Samples!");
            Console.WriteLine("===========================================");

            Console.WriteLine("To get started:");
            Console.WriteLine("===========================================");
            Console.WriteLine("  - Fill in your AWS credentials");
            Console.WriteLine("  - Uncomment sample you're interested in trying");
            Console.WriteLine("  - Set request with desired parameters");
            Console.WriteLine("  - Hit F5 to run!");
            Console.WriteLine();

            Console.WriteLine("===========================================");
            Console.WriteLine("Samples Output");
            Console.WriteLine("===========================================");
            Console.WriteLine();

           /************************************************************************
            * Access Key ID and Secret Acess Key ID, obtained from:
            * http://aws.amazon.com
            ***********************************************************************/
            String accessKeyId = "<Your Access Key ID>";
            String secretAccessKey = "<Your Secret Access Key>";
        
            /************************************************************************
            * Instantiate  Implementation of Amazon EC2 
            ***********************************************************************/
            AmazonEC2 service = new AmazonEC2Client(accessKeyId, secretAccessKey);
        
            /************************************************************************
            * Uncomment to try advanced configuration options. Available options are:
            *
            *  - Signature Version
            *  - Proxy Host and Proxy Port
            *  - Service URL
            *  - User Agent String to be sent to Amazon EC2  service
            *
            ***********************************************************************/
            // AmazonEC2Config config = new AmazonEC2Config();
            // config.SignatureVersion = "0";
            // AmazonEC2 service = new AmazonEC2Client(accessKeyId, secretAccessKey, config);
        
        
            /************************************************************************
            * Uncomment to try out Mock Service that simulates Amazon EC2 
            * responses without calling Amazon EC2  service.
            *
            * Responses are loaded from local XML files. You can tweak XML files to
            * experiment with various outputs during development
            *
            * XML files available under Amazon\EC2\Mock tree
            *
            ***********************************************************************/
            // AmazonEC2 service = new AmazonEC2Mock();


            /************************************************************************
            * Uncomment to invoke Allocate Address Action
            ***********************************************************************/
            // AllocateAddressRequest request = new AllocateAddressRequest();
            // @TODO: set request parameters here
            // AllocateAddressSample.InvokeAllocateAddress(service, request);
            /************************************************************************
            * Uncomment to invoke Associate Address Action
            ***********************************************************************/
            // AssociateAddressRequest request = new AssociateAddressRequest();
            // @TODO: set request parameters here
            // AssociateAddressSample.InvokeAssociateAddress(service, request);
            /************************************************************************
            * Uncomment to invoke Attach Volume Action
            ***********************************************************************/
            // AttachVolumeRequest request = new AttachVolumeRequest();
            // @TODO: set request parameters here
            // AttachVolumeSample.InvokeAttachVolume(service, request);
            /************************************************************************
            * Uncomment to invoke Authorize Security Group Ingress Action
            ***********************************************************************/
            // AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest();
            // @TODO: set request parameters here
            // AuthorizeSecurityGroupIngressSample.InvokeAuthorizeSecurityGroupIngress(service, request);
            /************************************************************************
            * Uncomment to invoke Bundle Instance Action
            ***********************************************************************/
            // BundleInstanceRequest request = new BundleInstanceRequest();
            // @TODO: set request parameters here
            // BundleInstanceSample.InvokeBundleInstance(service, request);
            /************************************************************************
            * Uncomment to invoke Cancel Bundle Task Action
            ***********************************************************************/
            // CancelBundleTaskRequest request = new CancelBundleTaskRequest();
            // @TODO: set request parameters here
            // CancelBundleTaskSample.InvokeCancelBundleTask(service, request);
            /************************************************************************
            * Uncomment to invoke Confirm Product Instance Action
            ***********************************************************************/
            // ConfirmProductInstanceRequest request = new ConfirmProductInstanceRequest();
            // @TODO: set request parameters here
            // ConfirmProductInstanceSample.InvokeConfirmProductInstance(service, request);
            /************************************************************************
            * Uncomment to invoke Create Key Pair Action
            ***********************************************************************/
            // CreateKeyPairRequest request = new CreateKeyPairRequest();
            // @TODO: set request parameters here
            // CreateKeyPairSample.InvokeCreateKeyPair(service, request);
            /************************************************************************
            * Uncomment to invoke Create Security Group Action
            ***********************************************************************/
            // CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
            // @TODO: set request parameters here
            // CreateSecurityGroupSample.InvokeCreateSecurityGroup(service, request);
            /************************************************************************
            * Uncomment to invoke Create Snapshot Action
            ***********************************************************************/
            // CreateSnapshotRequest request = new CreateSnapshotRequest();
            // @TODO: set request parameters here
            // CreateSnapshotSample.InvokeCreateSnapshot(service, request);
            /************************************************************************
            * Uncomment to invoke Create Volume Action
            ***********************************************************************/
            // CreateVolumeRequest request = new CreateVolumeRequest();
            // @TODO: set request parameters here
            // CreateVolumeSample.InvokeCreateVolume(service, request);
            /************************************************************************
            * Uncomment to invoke Delete Key Pair Action
            ***********************************************************************/
            // DeleteKeyPairRequest request = new DeleteKeyPairRequest();
            // @TODO: set request parameters here
            // DeleteKeyPairSample.InvokeDeleteKeyPair(service, request);
            /************************************************************************
            * Uncomment to invoke Delete Security Group Action
            ***********************************************************************/
            // DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest();
            // @TODO: set request parameters here
            // DeleteSecurityGroupSample.InvokeDeleteSecurityGroup(service, request);
            /************************************************************************
            * Uncomment to invoke Delete Snapshot Action
            ***********************************************************************/
            // DeleteSnapshotRequest request = new DeleteSnapshotRequest();
            // @TODO: set request parameters here
            // DeleteSnapshotSample.InvokeDeleteSnapshot(service, request);
            /************************************************************************
            * Uncomment to invoke Delete Volume Action
            ***********************************************************************/
            // DeleteVolumeRequest request = new DeleteVolumeRequest();
            // @TODO: set request parameters here
            // DeleteVolumeSample.InvokeDeleteVolume(service, request);
            /************************************************************************
            * Uncomment to invoke Deregister Image Action
            ***********************************************************************/
            // DeregisterImageRequest request = new DeregisterImageRequest();
            // @TODO: set request parameters here
            // DeregisterImageSample.InvokeDeregisterImage(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Addresses Action
            ***********************************************************************/
            // DescribeAddressesRequest request = new DescribeAddressesRequest();
            // @TODO: set request parameters here
            // DescribeAddressesSample.InvokeDescribeAddresses(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Availability Zones Action
            ***********************************************************************/
            // DescribeAvailabilityZonesRequest request = new DescribeAvailabilityZonesRequest();
            // @TODO: set request parameters here
            // DescribeAvailabilityZonesSample.InvokeDescribeAvailabilityZones(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Bundle Tasks Action
            ***********************************************************************/
            // DescribeBundleTasksRequest request = new DescribeBundleTasksRequest();
            // @TODO: set request parameters here
            // DescribeBundleTasksSample.InvokeDescribeBundleTasks(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Image Attribute Action
            ***********************************************************************/
            // DescribeImageAttributeRequest request = new DescribeImageAttributeRequest();
            // @TODO: set request parameters here
            // DescribeImageAttributeSample.InvokeDescribeImageAttribute(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Images Action
            ***********************************************************************/
            // DescribeImagesRequest request = new DescribeImagesRequest();
            // @TODO: set request parameters here
            // DescribeImagesSample.InvokeDescribeImages(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Instances Action
            ***********************************************************************/
            // DescribeInstancesRequest request = new DescribeInstancesRequest();
            // @TODO: set request parameters here
            // DescribeInstancesSample.InvokeDescribeInstances(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Regions Action
            ***********************************************************************/
            // DescribeRegionsRequest request = new DescribeRegionsRequest();
            // @TODO: set request parameters here
            // DescribeRegionsSample.InvokeDescribeRegions(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Reserved Instances Action
            ***********************************************************************/
            // DescribeReservedInstancesRequest request = new DescribeReservedInstancesRequest();
            // @TODO: set request parameters here
            // DescribeReservedInstancesSample.InvokeDescribeReservedInstances(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Reserved Instances Offerings Action
            ***********************************************************************/
            // DescribeReservedInstancesOfferingsRequest request = new DescribeReservedInstancesOfferingsRequest();
            // @TODO: set request parameters here
            // DescribeReservedInstancesOfferingsSample.InvokeDescribeReservedInstancesOfferings(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Key Pairs Action
            ***********************************************************************/
            // DescribeKeyPairsRequest request = new DescribeKeyPairsRequest();
            // @TODO: set request parameters here
            // DescribeKeyPairsSample.InvokeDescribeKeyPairs(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Security Groups Action
            ***********************************************************************/
            // DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
            // @TODO: set request parameters here
            // DescribeSecurityGroupsSample.InvokeDescribeSecurityGroups(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Snapshots Action
            ***********************************************************************/
            // DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
            // @TODO: set request parameters here
            // DescribeSnapshotsSample.InvokeDescribeSnapshots(service, request);
            /************************************************************************
            * Uncomment to invoke Describe Volumes Action
            ***********************************************************************/
            // DescribeVolumesRequest request = new DescribeVolumesRequest();
            // @TODO: set request parameters here
            // DescribeVolumesSample.InvokeDescribeVolumes(service, request);
            /************************************************************************
            * Uncomment to invoke Detach Volume Action
            ***********************************************************************/
            // DetachVolumeRequest request = new DetachVolumeRequest();
            // @TODO: set request parameters here
            // DetachVolumeSample.InvokeDetachVolume(service, request);
            /************************************************************************
            * Uncomment to invoke Disassociate Address Action
            ***********************************************************************/
            // DisassociateAddressRequest request = new DisassociateAddressRequest();
            // @TODO: set request parameters here
            // DisassociateAddressSample.InvokeDisassociateAddress(service, request);
            /************************************************************************
            * Uncomment to invoke Get Console Output Action
            ***********************************************************************/
            // GetConsoleOutputRequest request = new GetConsoleOutputRequest();
            // @TODO: set request parameters here
            // GetConsoleOutputSample.InvokeGetConsoleOutput(service, request);
            /************************************************************************
            * Uncomment to invoke Modify Image Attribute Action
            ***********************************************************************/
            // ModifyImageAttributeRequest request = new ModifyImageAttributeRequest();
            // @TODO: set request parameters here
            // ModifyImageAttributeSample.InvokeModifyImageAttribute(service, request);
            /************************************************************************
            * Uncomment to invoke Purchase Reserved Instances Offering Action
            ***********************************************************************/
            // PurchaseReservedInstancesOfferingRequest request = new PurchaseReservedInstancesOfferingRequest();
            // @TODO: set request parameters here
            // PurchaseReservedInstancesOfferingSample.InvokePurchaseReservedInstancesOffering(service, request);
            /************************************************************************
            * Uncomment to invoke Reboot Instances Action
            ***********************************************************************/
            // RebootInstancesRequest request = new RebootInstancesRequest();
            // @TODO: set request parameters here
            // RebootInstancesSample.InvokeRebootInstances(service, request);
            /************************************************************************
            * Uncomment to invoke Register Image Action
            ***********************************************************************/
            // RegisterImageRequest request = new RegisterImageRequest();
            // @TODO: set request parameters here
            // RegisterImageSample.InvokeRegisterImage(service, request);
            /************************************************************************
            * Uncomment to invoke Release Address Action
            ***********************************************************************/
            // ReleaseAddressRequest request = new ReleaseAddressRequest();
            // @TODO: set request parameters here
            // ReleaseAddressSample.InvokeReleaseAddress(service, request);
            /************************************************************************
            * Uncomment to invoke Reset Image Attribute Action
            ***********************************************************************/
            // ResetImageAttributeRequest request = new ResetImageAttributeRequest();
            // @TODO: set request parameters here
            // ResetImageAttributeSample.InvokeResetImageAttribute(service, request);
            /************************************************************************
            * Uncomment to invoke Revoke Security Group Ingress Action
            ***********************************************************************/
            // RevokeSecurityGroupIngressRequest request = new RevokeSecurityGroupIngressRequest();
            // @TODO: set request parameters here
            // RevokeSecurityGroupIngressSample.InvokeRevokeSecurityGroupIngress(service, request);
            /************************************************************************
            * Uncomment to invoke Run Instances Action
            ***********************************************************************/
            // RunInstancesRequest request = new RunInstancesRequest();
            // @TODO: set request parameters here
            // RunInstancesSample.InvokeRunInstances(service, request);
            /************************************************************************
            * Uncomment to invoke Terminate Instances Action
            ***********************************************************************/
            // TerminateInstancesRequest request = new TerminateInstancesRequest();
            // @TODO: set request parameters here
            // TerminateInstancesSample.InvokeTerminateInstances(service, request);
            Console.WriteLine();
            Console.WriteLine("===========================================");
            Console.WriteLine("End of output. You can close this window");
            Console.WriteLine("===========================================");

            System.Threading.Thread.Sleep(50000);
        }
Example #28
0
 public AwsClient()
 {
     Ec2Client = new AmazonEC2Client(ConfigurationManager.AppSettings["AWSAccessKey"], ConfigurationManager.AppSettings["AWSSecretKey"], RegionEndpoint.USEast1);
 }
        /// <summary>
        /// Load security groups to view model with AWS data based on region selected and EC2 classic/vpc
        /// </summary>
        private void LoadSecurityGroups(AmazonEC2Client ec2Client)
        {
            try
            {
                DescribeSecurityGroupsRequest sgreq = new DescribeSecurityGroupsRequest();
                DescribeSecurityGroupsResponse sgresp = ec2Client.DescribeSecurityGroups(sgreq);
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    vm.SecurityGroups.Clear();
                }));

                foreach (SecurityGroup sg in sgresp.DescribeSecurityGroupsResult.SecurityGroup)
                {
                    if (vm.IsVpc)
                    {
                        if (sg.VpcId != null && vm.SelectedVpc != null)
                        {
                            if (sg.VpcId == vm.SelectedVpc.VPC.VpcId)
                            {
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                                {
                                    vm.SecurityGroups.Add(new Models.ConsoleSG() { SecurityGroup = sg, DisplayName = string.Concat(sg.GroupName, " ( VPC: ", sg.VpcId, " )") });
                                }));
                            }
                        }
                    }
                    else
                    {
                        if (!(sg.VpcId != null && sg.VpcId != string.Empty && !vm.IsVpc))
                        {
                            //vm.SecurityGroups.Add(new Models.LcSecurityGroup() { SecurityGroup = sg, DisplayName = sg.GroupName });
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                            {
                                vm.SecurityGroups.Add(new Models.ConsoleSG() { SecurityGroup = sg, DisplayName = sg.GroupName });
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.LogEntry(ex.Message);
                LogManager.LogEntry(ex.StackTrace);
                throw new DataLoadingException("Error occurred loading security groups for region and environment type");
            }
        }
Example #30
0
        public static void WriteTopology(string accountNumber, RegionEndpoint regionEndPoint, IDatabase db)
        {
            Log.InfoFormat("Start writing data to redis ({0})", regionEndPoint.SystemName);

            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client(regionEndPoint);

            try
            {
                ec2.DescribeVpcs();
            }
            catch (Exception ex)
            {
                Log.InfoFormat("Unable to read Vpcs: {0}", ex.Message);
                return;
            }

            var currentDateTime = DateTime.UtcNow;

            //var dataKey = Common.GetDataKey(currentDateTime, accountNumber, regionEndPoint.SystemName);
            //db.SetAdd("TS", dataKey);
            //db.StringSet(string.Format("LATESTTS-{0}-{1}", accountNumber, regionEndPoint.SystemName), dataKey);


            //WriteVpcs(ec2, dataKey, db);
            //WriteVpcPeeringConnections(ec2, dataKey, db);
            //WriteVpcEndPoints(ec2, dataKey, db);
            //var subnetResponse = WriteSubnets(ec2, dataKey, db);
            //WriteRouteTables(ec2, dataKey, db);
            //var igResponse = WriteInternetGateways(ec2, dataKey, db);
            //var vgResponse = WriteVpnGateways(ec2, dataKey, db);
            //WriteVpnConnections(ec2, dataKey, db);
            //WriteEnis(ec2, dataKey, db);
            //WriteEbs(ec2, dataKey, db);
            //WriteSnapshots(accountNumber, ec2, dataKey, db);
            //WriteRds(regionEndPoint, dataKey, db);
            //WriteContainers(regionEndPoint, dataKey, db);
            //WriteInstances(ec2, dataKey, db);
            //WriteAsgs(regionEndPoint, dataKey, db);
            //WriteElbs(regionEndPoint, dataKey, db);
            //WriteSecurityGroups(ec2, dataKey, db);

            TopologyWriter.WriteVpcs(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteVpcPeeringConnections(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteVpcEndPoints(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteSubnets(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteSecurityGroups(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteInstances(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteRouteTables(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteInternetGateways(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteVpnGateways(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteVpnConnections(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteEnis(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteEbs(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteSnapshots(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteTags(ec2, currentDateTime, accountNumber, regionEndPoint.SystemName);
            TopologyWriter.WriteRds(currentDateTime, accountNumber, regionEndPoint);
            TopologyWriter.WriteContainers(currentDateTime, accountNumber, regionEndPoint);
            TopologyWriter.WriteAsgs(currentDateTime, accountNumber, regionEndPoint);
            TopologyWriter.WriteElbs(currentDateTime, accountNumber, regionEndPoint);

            Log.InfoFormat("End writing data to redis ({0})", regionEndPoint.SystemName);
        }
 /// <summary>
 /// Load key pairs to view model with AWS data based on region selected and EC2 classic/vpc
 /// </summary>
 private void LoadKeyPairs(AmazonEC2Client ec2Client)
 {
     try
     {
         DescribeKeyPairsRequest keyreq = new DescribeKeyPairsRequest();
         DescribeKeyPairsResponse keyresp = ec2Client.DescribeKeyPairs(keyreq);
         Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
         {
             vm.KeyPairs.Clear();
         }));
         foreach (KeyPair kp in keyresp.DescribeKeyPairsResult.KeyPair)
         {
             Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
             {
                 vm.KeyPairs.Add(kp.KeyName);
             }));
         }
     }
     catch (Exception ex)
     {
         LogManager.LogEntry(ex.Message);
         LogManager.LogEntry(ex.StackTrace);
         throw new DataLoadingException("Error occurred loading key pairs for region and environment type");
     }
 }
        /// <summary>
        /// Load availability zones to view model with AWS data based on region selected and EC2 classic/vpc
        /// </summary>
        private void LoadAvailabilityZones(AmazonEC2Client ec2Client)
        {
            try
            {

                DescribeAvailabilityZonesRequest azreq = new DescribeAvailabilityZonesRequest();
                DescribeAvailabilityZonesResponse azresp = ec2Client.DescribeAvailabilityZones(azreq);
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    vm.Zones.Clear();
                }));
                foreach (AvailabilityZone az in azresp.DescribeAvailabilityZonesResult.AvailabilityZone)
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {
                        vm.Zones.Add(az);
                    }));
                }
            }
            catch (Exception ex)
            {
                LogManager.LogEntry(ex.Message);
                LogManager.LogEntry(ex.StackTrace);
                throw new DataLoadingException("Error occurred loading availability zones for region and environment type");
            }
        }
        /// <summary>
        /// Creates AWS EC2 client
        /// </summary>
        /// <returns>AmazonEC2Client</returns>
        private AmazonEC2Client GetEc2Client()
        {
            if (vm.Region == null)
            {
                throw new InvalidRegionException("No region defined when creating EC2 client");
            }

            AmazonEC2Config config = new AmazonEC2Config();
            config.ServiceURL = vm.Region.Ec2Url;

            AmazonEC2Client client = new AmazonEC2Client(config);

            return client;
        }
        /// <summary>
        /// Auto Scaling Console load event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConsoleView_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                AmazonEC2Client ec2Client = new AmazonEC2Client();
                DescribeRegionsRequest rreq = new DescribeRegionsRequest();
                DescribeRegionsResponse rresp = ec2Client.DescribeRegions(rreq);
                ((ViewModel)this.DataContext).Regions.Clear();
                foreach (Region r in rresp.DescribeRegionsResult.Region)
                {
                    ((ViewModel)this.DataContext).Regions.Add(new Models.Region(r.RegionName));
                }

                ((ViewModel)this.DataContext).Region = ((ViewModel)this.DataContext).Regions.Where(o => o.Name.ToLower() == "us-east-1").FirstOrDefault();

                AmazonAutoScalingClient client = GetAutoScaleClient();
                if (client == null)
                {
                    MessageBoxResult mbr = MessageBox.Show(Window.GetWindow(this), "AWS Credentials and region must be defined in app.config file.");
                    Application.Current.Shutdown();
                }

            }
            catch (Exception ex)
            {
                LogManager.LogEntry(ex.Message);
                LogManager.LogEntry(ex.StackTrace);
                ((ViewModel)this.DataContext).IsBusy = false;
                MessageBox.Show(Window.GetWindow(this), "Error occured while setting credentials. Please ensure your credentials are correct in app.config.", "Error", MessageBoxButton.OK);
                Application.Current.Shutdown();
            }
        }
Example #35
0
 public EC2TestHelper(AmazonEC2Client client)
 {
     _ec2Client = client;
 }
 public Ec2SnapshotBrowser(AmazonEC2Client client)
 {
     this.client = client;
 }
Example #37
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.
                IAmazonEC2 ec2 = new AmazonEC2Client();
                DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();

                try
                {
                    DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request);
                    int numInstances = 0;
                    numInstances = ec2Response.Reservations.Count;
                    sr.WriteLine(string.Format("You have {0} Amazon EC2 instance(s) running in the {1} region.",
                                               numInstances, ConfigurationManager.AppSettings["AWSRegion"]));
                }
                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();

                // Print the number of Amazon SimpleDB domains.
                IAmazonSimpleDB sdb = new AmazonSimpleDBClient();
                ListDomainsRequest sdbRequest = new ListDomainsRequest();

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

                    int numDomains = 0;
                    numDomains = sdbResponse.DomainNames.Count;
                    sr.WriteLine(string.Format("You have {0} Amazon SimpleDB domain(s) in the {1} region.",
                                               numDomains, ConfigurationManager.AppSettings["AWSRegion"]));
                }
                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();

                // Print the number of Amazon S3 Buckets.
                IAmazonS3 s3Client = new AmazonS3Client();

                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).");
                }
                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("Press any key to continue...");
            }
            return sb.ToString();
        }