示例#1
0
 /// <summary>
 /// Create a client for the Amazon EC2 Service with the specified configuration
 /// </summary>
 /// <param name="awsAccessKey">The AWS Access Key associated with the account</param>
 /// <param name="awsSecretAccessKey">The AWS Secret Access Key associated with the account</param>
 /// <param name="config">Configuration options for the service like HTTP Proxy, # of connections, etc
 /// </param>
 /// <returns>An Amazon EC2 client</returns>
 /// <remarks>
 /// </remarks>
 public static AmazonEC2 CreateAmazonEC2Client(
     string awsAccessKey,
     string awsSecretAccessKey, AmazonEC2Config config
     )
 {
     return(new AmazonEC2Client(awsAccessKey, awsSecretAccessKey, config));
 }
示例#2
0
 public AwsVpcReader(
     ILogger <AwsAdapterBase> logger,
     AwsContext awsContext,
     AmazonEC2Config amazonEc2Config)
     : base(logger, awsContext, amazonEc2Config)
 {
 }
示例#3
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonEC2Config config = new AmazonEC2Config();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonEC2Client client = new AmazonEC2Client(creds, config);

            DescribeTransitGatewayConnectsResponse resp = new DescribeTransitGatewayConnectsResponse();

            do
            {
                DescribeTransitGatewayConnectsRequest req = new DescribeTransitGatewayConnectsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.DescribeTransitGatewayConnects(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.TransitGatewayConnects)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        private string GetTag(string name)
        {
            var instanceId      = EC2InstanceMetadata.InstanceId;
            var amazonEC2Config = new AmazonEC2Config
            {
                RegionEndpoint   = RegionEndpoint.EUWest1,
                ProxyCredentials = CredentialCache.DefaultCredentials
            };
            var client = new AmazonEC2Client(amazonEC2Config);

            var describeTagsRequest = new DescribeTagsRequest
            {
                Filters = new List <Filter>
                {
                    new Filter("resource-id", new List <string> {
                        instanceId
                    }),
                    new Filter("key", new List <string> {
                        name
                    })
                }
            };

            var describeTagsAsyncResult = client.DescribeTagsAsync(describeTagsRequest).Result;

            return(describeTagsAsyncResult?.Tags?.FirstOrDefault()?.Value);
        }
示例#5
0
        public StandardVpcTests()
        {
            var config = new AmazonEC2Config
            {
                RegionEndpoint = RegionEndpoint.EUWest1
            };

            _ec2Client = new AmazonEC2Client(config);
        }
示例#6
0
        public static IAmazonEC2 CreateAmazonClient()
        {
            var amazonEC2Config = new AmazonEC2Config
            {
                RegionEndpoint = RegionEndpoint.USWest2
            };

            return(new AmazonEC2Client(amazonEC2Config));
        }
示例#7
0
        public override IAmazonEC2 CreateEC2Client()
        {
            var config = new AmazonEC2Config()
            {
                RegionEndpoint = AWSRegion
            };

            return(new AmazonEC2Client(Credentials, config));
        }
示例#8
0
        /// <summary>
        /// Prevent explicit instance creation
        /// </summary>
        private EC2Helper()
        {
            //create amazon client instance
            AmazonEC2Config config = new AmazonEC2Config();

            AppConfig.Refresh();
            config.ServiceURL = AppConfig.AWSServiceURL;
            _ec2 = new AmazonEC2Client(config);
        }
        /// <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);
        }
示例#10
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);
        }
示例#11
0
        public Ec2Stopper(AwsStopOptionsValues options)
        {
            _options = options;
            var config = new AmazonEC2Config {
                RegionEndpoint = _options.RegionEndpoint
            };

            _client          = new AmazonEC2Client(_options.Credentials, config);
            _instanceHandler = new Ec2InstanceHandler(_client);
        }
示例#12
0
        public Ec2Starter(AwsStartOptionsValues options, ConDepSettings settings)
        {
            _options  = options;
            _settings = settings;
            var config = new AmazonEC2Config {
                RegionEndpoint = _options.RegionEndpoint
            };

            _client          = new AmazonEC2Client(_options.Credentials, config);
            _instanceHandler = new Ec2InstanceHandler(_client);
            _passwordHandler = new Ec2InstancePasswordHandler(_client);
        }
示例#13
0
    void Start()
    {
        // Evitar erro de certificado no Mono.NET
        ServicePointManager.ServerCertificateValidationCallback =
            MonoCertificateFix.MyRemoteCertificateValidationCallback;

        // Ler o profile a partir de arquivo de configuração externo.
        ReadProfileData();

        // Define a configuração do endpoint.
        Config = new AmazonEC2Config();
        Config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
    }
示例#14
0
        private AmazonEC2Client get_client()
        {
            if (instance != null)
            {
                return(instance);
            }

            AmazonEC2Config config = new AmazonEC2Config();

            config.ServiceURL = "https://ec2." + region + ".amazonaws.com";
            instance          = new AmazonEC2Client(
                Globals.aws_access_key_id.Trim(), Globals.aws_secret_access_key.Trim(), config);
            return(instance);
        }
        protected IAmazonEC2 CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonEC2Config {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonEC2Client(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
示例#16
0
        public EnvService()
        {
            _amazonEC2Config = new AmazonEC2Config()
            {
                RegionEndpoint = RegionEndpoint.USWest2
            };

            _ids = new List <string>()
            {
                "i-10f40d1e"
            };

            _ec2 = AWSClientFactory.CreateAmazonEC2Client(_amazonEC2Config);
        }
示例#17
0
        public void TestProxySetupHostAndPortOnly()
        {
            var dummyConfig = new AmazonEC2Config();

            dummyConfig.ProxyHost = Host;
            dummyConfig.ProxyPort = Port;

            WebProxy proxy   = dummyConfig.GetWebProxy();
            var      address = proxy.Address;

            Assert.AreEqual(address.Host, Host);
            Assert.AreEqual(address.Port, Port);
            Assert.AreEqual(0, proxy.BypassList.Length);
            Assert.IsFalse(proxy.BypassProxyOnLocal);
        }
示例#18
0
        private void Initialize(RegionEndpoint regionEndpoint, string AWSAcessKey, string AWSSecretKey)
        {
            // Set configuration info
            AmazonEC2Config config = new AmazonEC2Config();

            config.Timeout          = new TimeSpan(1, 0, 0);
            config.ReadWriteTimeout = new TimeSpan(1, 0, 0);
            config.RegionEndpoint   = regionEndpoint;

            // Create EC2 client
            EC2client = AWSClientFactory.CreateAmazonEC2Client(
                AWSAcessKey,
                AWSSecretKey,
                config);
        }
示例#19
0
        public void TestProxySetupWithSchemedHost()
        {
            // verifies bug fix that the http:// scheme is not doubled
            // up in the proxy address if the user specifies it when setting
            // proxy host (the bug yielded an address like http://http/host)

            var dummyConfig = new AmazonEC2Config();

            var host = string.Concat("http://", Host);

            dummyConfig.ProxyHost = host;
            dummyConfig.ProxyPort = Port;

            WebProxy proxy = dummyConfig.GetWebProxy();

            Assert.IsTrue(proxy.Address.ToString().StartsWith(host, StringComparison.OrdinalIgnoreCase));
        }
示例#20
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(IAmazonEC2 ec2Client, ImageDescriptor descriptor)
        {
            AmazonEC2Config config = CreateConfigFromClient(ec2Client, descriptor);

            LoadDefinitionsFromWeb(config);

            int   retryCount = 1;
            Image image      = null;

            do
            {
                var result = ec2Client.DescribeImages(CreateDescribeImagesRequest(descriptor));

                if (result.Images.Any())
                {
                    image = result.Images.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);
                        lock (LOCK_OBJECT)
                        {
                            ImageDefinitionsLoaded = false;
                        }

                        LoadDefinitionsFromWeb(config);
                    }
                    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);
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonEC2Config config = new AmazonEC2Config();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonEC2Client client = new AmazonEC2Client(creds, config);

            DescribeAvailabilityZonesResponse resp = new DescribeAvailabilityZonesResponse();
            DescribeAvailabilityZonesRequest  req  = new DescribeAvailabilityZonesRequest
            {
            };

            resp = client.DescribeAvailabilityZones(req);
            CheckError(resp.HttpStatusCode, "200");

            foreach (var obj in resp.AvailabilityZones)
            {
                AddObject(obj);
            }
        }
示例#22
0
        public void TestProxySetupWithBypass()
        {
            var dummyConfig = new AmazonEC2Config();

            dummyConfig.ProxyHost = Host;
            dummyConfig.ProxyPort = Port;

            dummyConfig.ProxyBypassList    = new List <string>(BypassList);
            dummyConfig.ProxyBypassOnLocal = true;

            WebProxy proxy = dummyConfig.GetWebProxy();

            Assert.AreEqual(BypassList.Count, proxy.BypassList.Length);
            // making assumption here that order is retained on assignment
            // inside WebProxy - seems to be the case
            for (int i = 0; i < BypassList.Count; i++)
            {
                Assert.AreEqual(BypassList[i], proxy.BypassList[i]);
            }

            Assert.IsTrue(proxy.BypassProxyOnLocal);
        }
示例#23
0
        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);
        }
示例#24
0
        private static void LoadDefinitionsFromWeb(AmazonEC2Config ec2Config)
        {
            lock (LOCK_OBJECT)
            {
                if (ImageDefinitionsLoaded)
                {
                    return;
                }
            }

            IWebProxy webProxy = null;

            if (ec2Config != null)
            {
                webProxy = ec2Config.GetWebProxy();
            }

            int retries = 0;

            while (retries < MAX_DOWNLOAD_RETRIES)
            {
                try
                {
                    HttpWebResponse response = null;
                    foreach (var location in DownloadLocations)
                    {
                        try
                        {
                            response = DownloadControlFile(location, webProxy);
                            if (response != null)
                            {
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.InfoFormat("Failed to download stockamis.json from {0}, exception {1}", location, e);
                        }
                    }

                    if (response == null)
                    {
                        throw new AmazonClientException("Failed to download ImageUtilities metadata file stockamis.json from known locations.");
                    }

                    using (response)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            lock (LOCK_OBJECT)
                            {
                                ParseAMIDefinitions(reader);
                                ImageDefinitionsLoaded = true;

                                return;
                            }
                        }
                    }
                }
                catch (AmazonClientException e)
                {
                    retries++;
                    if (retries == MAX_DOWNLOAD_RETRIES)
                    {
                        Logger.Error(e, "Error downloading AMI definition file, ImageDescriptors were not initialized.");
                        break;
                    }
                }

                int delay = (int)(Math.Pow(4, retries) * 100);
                delay = Math.Min(delay, 30 * 1000);
                Thread.Sleep(delay);
            }
        }
示例#25
0
        private void RegionlistView_SelectedIndexChanged(object sender, EventArgs e)
        {
            AmazonEC2Config config = new AmazonEC2Config();

            CredInit();
            EC2listView.Items.Clear();


            //config.RegionEndpoint = RegionEndpoint.EUWest1;


            foreach (ListViewItem item in RegionlistView.SelectedItems)

            {
                RegionEndpoint region = RegionEndpoint.GetBySystemName(item.SubItems[0].Text);
                config.RegionEndpoint = region;
                ec2 = new AmazonEC2Client(credentials, config);


                try
                {
                    //ec2 = new AmazonEC2Client();
                    // List<string> ec2inst_list = MyAWSService.WriteEC2Info(ec2);
                    //List<AWSServices.EC2Instance>
                    ec2obj_list = MyAWSService.GetEC2InstanceList(ec2);
                    //MyAWSService.WriteEC2Info(ec2);
                    //MyAWSService.GetEC2InstanceList(ec2);

                    ListViewItem lvitem;
                    foreach (AWSServices.EC2Instance ec2obj in ec2obj_list)
                    {
                        lvitem = EC2listView.Items.Add(ec2obj.getid());
                        lvitem.SubItems.Add(ec2obj.getTagName());
                        lvitem.SubItems.Add(ec2obj.getState());
                        lvitem.SubItems.Add(ec2obj.getType());
                        lvitem.SubItems.Add(ec2obj.getPlatforms());
                        lvitem.SubItems.Add(ec2obj.getPrivateDNSName());
                        lvitem.SubItems.Add(ec2obj.getPrivateIP());
                        lvitem.SubItems.Add(ec2obj.getPublicDNSName());
                        lvitem.SubItems.Add(ec2obj.getPublicIP());
                        lvitem.SubItems.Add(ec2obj.getPlacment());
                        lvitem.SubItems.Add(ec2obj.getVpcId());
                        lvitem.SubItems.Add(ec2obj.getKeyName());
                        lvitem.SubItems.Add(ec2obj.getSubnetId());
                        lvitem.SubItems.Add(ec2obj.getAmiId());

                        string sgstr = "";
                        foreach (string sg in ec2obj.getSG())
                        {
                            sgstr = sgstr + sg + ",";
                        }

                        lvitem.SubItems.Add(sgstr);

                        string bdstr = "";
                        foreach (string bd in ec2obj.getBlockDevice())
                        {
                            bdstr = bdstr + bd + ",";
                        }

                        lvitem.SubItems.Add(bdstr);

                        // lvitem.SubItems.Add(ec2obj.getTokenName());
                    }
                }
                catch (AmazonEC2Exception ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        MessageBox.Show("The account you are using is not signed up for Amazon EC2.\n please check your preferneces");
                    }
                    else
                    {
                        MessageBox.Show("Caught Exception: " + ex.Message + "/n" + "Response Status Code: " + ex.StatusCode + " " + ex.ErrorCode + " " + ex.ErrorType + " " + ex.RequestId);
                    }
                }

                instanseslabel.Text = "No. of Instances:" + EC2listView.Items.Count;
            }
        }
示例#26
0
        static void Main(string[] args)
        {
            try
            {
                var config = new AmazonEC2Config
                {
                    RegionEndpoint = RegionEndpoint.GetBySystemName("us-east-2")
                };

                var client   = new AmazonEC2Client(config);
                var response = client.DescribeInstances();

                if (response != null)
                {
                    if (response.HttpStatusCode == HttpStatusCode.OK)
                    {
                        if (response.DescribeInstancesResult.Reservations != null && response.DescribeInstancesResult.Reservations.Any())
                        {
                            var sBuilder = new StringBuilder();

                            foreach (var item in response.DescribeInstancesResult.Reservations)
                            {
                                sBuilder.AppendLine($"OwnerId: {item.OwnerId}");
                                sBuilder.AppendLine($"RequesterId: {item.RequesterId}");
                                sBuilder.AppendLine($"ReservationId: {item.ReservationId}");
                                sBuilder.AppendLine("GroupNames:");

                                foreach (var name in item.GroupNames)
                                {
                                    sBuilder.AppendLine($"* {name}");
                                }

                                sBuilder.AppendLine("Instances:");

                                foreach (var instance in item.Instances)
                                {
                                    sBuilder.AppendLine($"* AmiLaunchIndex: {instance.AmiLaunchIndex}; ImageId: {instance.ImageId}; KeyName: {instance.KeyName}");
                                }

                                sBuilder.AppendLine("--------------------------------------------------------");
                            }

                            Console.WriteLine(sBuilder.ToString());
                        }
                        else
                        {
                            Console.WriteLine("Reservations is null or empty.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Something went wrong with the request.");
                    }
                }
                else
                {
                    Console.WriteLine("The response is null.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex}: {ex.Message}");
            }

            Console.WriteLine("\n\nTap to continue...");
            Console.ReadKey();
        }
示例#27
0
 /// <summary>
 /// Create a client for the Amazon EC2 Service with AWSCredentials and an AmazonEC2 Configuration object.
 /// </summary>
 /// <param name="credentials">AWS Credentials</param>
 /// <param name="config">Configuration options for the service like HTTP Proxy, # of connections, etc</param>
 /// <returns>An Amazon EC2 client</returns>
 /// <remarks>
 /// </remarks>
 public static IAmazonEC2 CreateAmazonEC2Client(AWSCredentials credentials, AmazonEC2Config config)
 {
     return(new AmazonEC2Client(credentials, config));
 }
示例#28
0
        /// <summary>
        /// Constructs an <see cref="AmazonEC2Client" /> instance with the
        /// temporary details generated from role assumption.
        /// </summary>
        /// <param name="explicitCredentials">
        /// An instance of <see cref="AWSCredentials" /> containing explicitly
        /// declared credentials (i.e. from the command line). Can be null.
        /// </param>
        /// <param name="amazonEC2Config">
        /// An instance of <see cref="AmazonEC2Config" />.
        /// </param>
        /// <param name="roleArn">
        /// An IAM role ARN to assume.
        /// </param>
        /// <returns>
        /// A configured instance of <see cref="AmazonEC2Client" />.
        /// </returns>
        private AmazonEC2Client AssumeRoleAndCreateEC2Client(
            AWSCredentials explicitCredentials,
            AmazonEC2Config amazonEC2Config,
            string roleArn)
        {
            AmazonEC2Client toReturn = null;

            AmazonSecurityTokenServiceConfig amazonSecurityTokenServiceConfig =
                new AmazonSecurityTokenServiceConfig()
            {
                // Nothing for now...
            };

            IAmazonSecurityTokenService amazonSecurityTokenService = null;

            // Explcit credentials supplied?
            if (explicitCredentials == null)
            {
                this.loggingProvider.Debug(
                    $"No explicit credentials provided. Creating an " +
                    $"instance of the " +
                    $"{nameof(AmazonSecurityTokenServiceClient)} using " +
                    "credentials stored in the credentials file...");

                // Nope. Use the credentials file.
                amazonSecurityTokenService =
                    new AmazonSecurityTokenServiceClient(
                        amazonSecurityTokenServiceConfig);
            }
            else
            {
                this.loggingProvider.Debug(
                    $"Explicit credentials provided. Creating an instance " +
                    $"of the {nameof(AmazonSecurityTokenServiceClient)} " +
                    $"using these details...");

                // Yep.
                amazonSecurityTokenService =
                    new AmazonSecurityTokenServiceClient(
                        explicitCredentials,
                        amazonSecurityTokenServiceConfig);
            }

            this.loggingProvider.Info(
                $"Instance of {nameof(AmazonSecurityTokenServiceClient)} " +
                $"established.");

            this.loggingProvider.Debug(
                $"Parsing role ARN \"{roleArn}\" to create the session " +
                $"name...");

            // Just use the latter part of the ARN as the session name.
            string roleSessionName = roleArn.Split('/')
                                     .Last();

            this.loggingProvider.Info(
                $"Session name created from ARN: \"{roleSessionName}\".");

            AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            {
                RoleArn         = roleArn,
                RoleSessionName = roleSessionName
            };

            this.loggingProvider.Debug(
                $"Pulling back credentials from " +
                $"{nameof(AmazonSecurityTokenServiceClient)} by assuming " +
                $"specified role...");

            // Get the temporary credentials using the specified role.
            AssumeRoleResponse assumeRoleResponse =
                amazonSecurityTokenService.AssumeRole(assumeRoleRequest);

            Credentials roleCreds = assumeRoleResponse.Credentials;

            this.loggingProvider.Info(
                $"Credentials returned. Access ID: " +
                $"\"{roleCreds.AccessKeyId}\". Returning " +
                $"an instance of {nameof(AmazonEC2Client)}.");

            toReturn = new AmazonEC2Client(
                roleCreds,
                amazonEC2Config);

            return(toReturn);
        }
示例#29
0
 public Application(IOptions <AmazonEC2Config> config)
 {
     _config = config.Value;
 }
示例#30
0
        private static void LoadDefinitionsFromWeb(AmazonEC2Config ec2Config)
        {
            lock (LOCK_OBJECT)
            {
                if (ImageDefinitionsLoaded)
                    return;
            }

            IWebProxy webProxy = null;
            if (ec2Config != null)
                webProxy = ec2Config.GetWebProxy();

            int retries = 0;
            while (retries < MAX_DOWNLOAD_RETRIES)
            {
                try
                {
                    HttpWebResponse response = null;
                    foreach (var location in DownloadLocations)
                    {
                        try
                        {
                            response = DownloadControlFile(location, webProxy);
                            if (response != null)
                                break;
                        }
                        catch (Exception e)
                        {
                            Logger.InfoFormat("Failed to download stockamis.json from {0}, exception {1}", location, e);
                        }
                    }

                    if (response == null)
                        throw new AmazonClientException("Failed to download ImageUtilities metadata file stockamis.json from known locations.");

                    using (response)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            lock (LOCK_OBJECT)
                            {
                                ParseAMIDefinitions(reader);
                                ImageDefinitionsLoaded = true;

                                return;
                            }
                        }
                    }
                }
                catch (AmazonClientException e)
                {
                    retries++;
                    if (retries == MAX_DOWNLOAD_RETRIES)
                    {
                        Logger.Error(e, "Error downloading AMI definition file, ImageDescriptors were not initialized.");
                        break;
                    }
                }

                int delay = (int)(Math.Pow(4, retries) * 100);
                delay = Math.Min(delay, 30 * 1000);
                Thread.Sleep(delay);
            }
        }
示例#31
0
        /// <summary>
        /// Implements
        /// <see cref="IInstanceScanner.ExtractDetails(Tuple{string, string}, string, FileInfo, string)" />.
        /// </summary>
        /// <param name="awsAccessKeys">
        /// An instance of <see cref="Tuple{string, string}" /> containing
        /// firstly the access key id, followed by the the secret access key.
        /// If the variable is null, then credentials based authentication
        /// needs to be used.
        /// </param>
        /// <param name="region">
        /// The AWS region in which to execute AWS SDK methods against.
        /// </param>
        /// <param name="passwordEncryptionKeyFile">
        /// The location of the password encryption key file.
        /// </param>
        /// <param name="roleArn">
        /// An IAM role ARN to assume prior to pulling back EC2
        /// <see cref="InstanceDetail" />. Optional.
        /// </param>
        /// <returns>
        /// An array of <see cref="InstanceDetail" /> instances.
        /// </returns>
        public InstanceDetail[] ExtractDetails(
            Tuple <string, string> awsAccessKeys,
            string region,
            FileInfo passwordEncryptionKeyFile,
            string roleArn)
        {
            InstanceDetail[] toReturn = null;

            // If an access key and secret key were passed in via the command
            // line, use these details as a matter of priority.
            AWSCredentials explicitCredentials = null;

            if (awsAccessKeys != null)
            {
                this.loggingProvider.Info(
                    $"Explicit credentials provided. Access key ID: " +
                    $"\"{awsAccessKeys.Item1}\".");

                explicitCredentials = new BasicAWSCredentials(
                    awsAccessKeys.Item1,
                    awsAccessKeys.Item2);
            }
            else
            {
                this.loggingProvider.Info(
                    $"No explicit credentials provided. Instead, the " +
                    $"credentials file will be used.");
            }

            this.loggingProvider.Debug(
                $"Parsing the provided {nameof(RegionEndpoint)}...");

            RegionEndpoint regionEndpoint =
                RegionEndpoint.GetBySystemName(region);

            if (regionEndpoint.DisplayName == "Unknown")
            {
                throw new InvalidDataException(
                          $"The specified AWS region is unknown. Please specify a " +
                          $"valid region, for example: " +
                          $"\"{RegionEndpoint.EUWest2.SystemName}\".");
            }

            this.loggingProvider.Info(
                $"{nameof(RegionEndpoint)} parsed: " +
                $"{regionEndpoint.DisplayName}.");

            AmazonEC2Config amazonEC2Config = new AmazonEC2Config()
            {
                RegionEndpoint = regionEndpoint
            };

            IAmazonEC2 amazonEC2 = null;

            if (string.IsNullOrEmpty(roleArn))
            {
                this.loggingProvider.Debug(
                    "No role ARN was provided. Therefore, the API will be " +
                    "called with credentials either provided explicitly, or " +
                    "stored in the credentials file.");

                if (explicitCredentials == null)
                {
                    this.loggingProvider.Debug(
                        $"No explicit credentials were provided. A " +
                        $"{nameof(AmazonEC2Client)} will be generated using " +
                        $"the credentials in the credentials file...");

                    amazonEC2 = new AmazonEC2Client(amazonEC2Config);
                }
                else
                {
                    this.loggingProvider.Debug(
                        $"Explicit credentials were provided. The " +
                        $"{nameof(AmazonEC2Client)} will be generated using " +
                        $"these explicit credentials.");

                    amazonEC2 = new AmazonEC2Client(
                        explicitCredentials,
                        amazonEC2Config);
                }
            }
            else
            {
                this.loggingProvider.Debug(
                    $"Role ARN provided: \"{roleArn}\". Credentials will be " +
                    $"requested for this role in order to create the " +
                    $"{nameof(AmazonEC2Client)}.");

                amazonEC2 = this.AssumeRoleAndCreateEC2Client(
                    explicitCredentials,
                    amazonEC2Config,
                    roleArn);
            }

            this.loggingProvider.Info($"{nameof(AmazonEC2Client)} created.");

            this.loggingProvider.Debug(
                $"Pulling back all available {nameof(Reservation)} " +
                $"instances...");

            Reservation[] allReservations =
                this.GetRegionReservations(amazonEC2);

            this.loggingProvider.Info(
                $"{allReservations} {nameof(Reservation)}(s) returned. " +
                $"Selecting out all {nameof(Instance)}(s)...");

            Instance[] allInstances = allReservations
                                      .SelectMany(x => x.Instances)
                                      .ToArray();

            this.loggingProvider.Info(
                $"{allInstances.Length} {nameof(Instance)}(s) selected.");

            this.loggingProvider.Debug(
                $"Reading the password encryption key into memory " +
                $"(located at \"{passwordEncryptionKeyFile.FullName}\")...");

            // Read the password encryption key.
            string passwordEncryptionKey =
                this.fileSystemProvider.ReadFileInfoAsString(
                    passwordEncryptionKeyFile);

            this.loggingProvider.Info(
                $"Password encryption key read into memory - length: " +
                $"{passwordEncryptionKeyFile.Length}.");

            this.loggingProvider.Debug(
                $"Fetching passwords for all {allInstances.Length} " +
                $"{nameof(Instance)}(s)...");

            toReturn = allInstances
                       .Select(x => this.ConvertInstanceToInstanceDetail(
                                   amazonEC2,
                                   passwordEncryptionKey,
                                   x))
                       .ToArray();

            this.loggingProvider.Info(
                $"Password extraction complete for {toReturn.Length} " +
                $"{nameof(Instance)}(s).");

            return(toReturn);
        }