I have been working with AWS toolkit for some time in last week. I prepared some tools to automate our infra team tasks and for our internal development and testing purpose.
Here I will show you how to register/de-register EC2 instances with Elastic Load Balancer programmatically using AWS .NET toolkit.
First get your awsSecretAccessKey and awsAccessKey,
Note: The user account you use here for Secret Key and Access Key must have full access to EC2 service of AWS
Create EC2 Client,
Make sure you specify correct RegionEndPoint where your EC2 instances exist. Here I have used USWest2 region end point.
Now lets check whether the instance you want to register/de-register already exist under the given ELB.
If the instance already exist under ELB then let's de-register it,
If the instance does not exist under ELB then let's register it,
Here is the full code for registering/de-registering EC2 instances with an elastic load balancer. The idea here is to attach a single server at a time.
Hope you like it. More coming soon.
Happy programming :)
Here I will show you how to register/de-register EC2 instances with Elastic Load Balancer programmatically using AWS .NET toolkit.
First get your awsSecretAccessKey and awsAccessKey,
1 2 | string awsSecretAccessKey = ConfigurationManager.AppSettings["awsSecretAccessKey"]; string awsAccessKey = ConfigurationManager.AppSettings["awsAccessKey"]; |
Note: The user account you use here for Secret Key and Access Key must have full access to EC2 service of AWS
Create EC2 Client,
1 | var client = AWSClientFactory.CreateAmazonElasticLoadBalancingClient(awsAccessKey, awsSecretAccessKey, RegionEndpoint.USWest2);
|
Make sure you specify correct RegionEndPoint where your EC2 instances exist. Here I have used USWest2 region end point.
Now lets check whether the instance you want to register/de-register already exist under the given ELB.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | DescribeLoadBalancersResponse loadBalancers = client.DescribeLoadBalancers(new DescribeLoadBalancersRequest { LoadBalancerNames = new List<string>() { ELBName } }); if (loadBalancers != null && loadBalancers.LoadBalancerDescriptions.Count > 0) { //Instance to add in ELB Amazon.ElasticLoadBalancing.Model.Instance EC2Instance = new Amazon.ElasticLoadBalancing.Model.Instance(InstanceId); List<Amazon.ElasticLoadBalancing.Model.Instance> registeredInstances = loadBalancers.LoadBalancerDescriptions.FirstOrDefault().Instances; if (registeredInstances == null) registeredInstances = new List<Amazon.ElasticLoadBalancing.Model.Instance>(); //Check if the current instance to be added exists in already registered instances of elb if (registeredInstances.Any(instance => instance.InstanceId == EC2Instance.InstanceId)) { InstanceExists = true; } } |
If the instance already exist under ELB then let's de-register it,
1 2 3 4 5 6 7 8 | if(InstanceExists) { client.DeregisterInstancesFromLoadBalancer(new DeregisterInstancesFromLoadBalancerRequest { Instances = new List<Amazon.ElasticLoadBalancing.Model.Instance> { EC2Instance }, LoadBalancerName = ELBName }); } |
If the instance does not exist under ELB then let's register it,
1 2 3 4 5 6 7 8 | if (!InstanceExists) { client.RegisterInstancesWithLoadBalancer(new RegisterInstancesWithLoadBalancerRequest { Instances = new List<Amazon.ElasticLoadBalancing.Model.Instance> { EC2Instance }, LoadBalancerName = ELBName }); } |
Here is the full code for registering/de-registering EC2 instances with an elastic load balancer. The idea here is to attach a single server at a time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon; using Amazon.EC2.Model; using Amazon.ElasticLoadBalancing.Model; using System.Web.Services; using System.Configuration; public string RegisterServerToLoadBalancer(string ELBName, string InstanceName) { try { string message = string.Empty; string awsSecretAccessKey = ConfigurationManager.AppSettings["awsSecretAccessKey"]; string awsAccessKey = ConfigurationManager.AppSettings["awsAccessKey"]; if (!string.IsNullOrEmpty(ELBName) && !string.IsNullOrEmpty(InstanceName)) { //Check If the InstanceName is valid Amazon.EC2.IAmazonEC2 Ec2Client = AWSClientFactory.CreateAmazonEC2Client(awsAccessKey, awsSecretAccessKey, RegionEndpoint.USWest2); var lstInstances = Ec2Client.DescribeInstances(); String InstanceId = lstInstances.Reservations.SelectMany(c => c.Instances.Where(p => p.Tags.Any(d => d.Value.Equals(InstanceName, StringComparison.OrdinalIgnoreCase))).Select(k => k.InstanceId)).FirstOrDefault(); if (!string.IsNullOrEmpty(InstanceId)) { bool InstanceExists = false; var client = AWSClientFactory.CreateAmazonElasticLoadBalancingClient(awsAccessKey, awsSecretAccessKey, RegionEndpoint.USWest2); DescribeLoadBalancersResponse loadBalancers = client.DescribeLoadBalancers(new DescribeLoadBalancersRequest { LoadBalancerNames = new List<string>() { ELBName } }); if (loadBalancers != null && loadBalancers.LoadBalancerDescriptions.Count > 0) { //Instance to add in ELB Amazon.ElasticLoadBalancing.Model.Instance EC2Instance = new Amazon.ElasticLoadBalancing.Model.Instance(InstanceId); List<Amazon.ElasticLoadBalancing.Model.Instance> registeredInstances = loadBalancers.LoadBalancerDescriptions.FirstOrDefault().Instances; if (registeredInstances == null) registeredInstances = new List<Amazon.ElasticLoadBalancing.Model.Instance>(); //Check if the current instance to be added exists in already registered instances of elb if (registeredInstances.Any(instance => instance.InstanceId == EC2Instance.InstanceId)) { InstanceExists = true; registeredInstances = registeredInstances.Where(c => c.InstanceId != EC2Instance.InstanceId).ToList(); } //Remove all registered instances from ELB except current instance to be attached if (registeredInstances.Count > 0) { client.DeregisterInstancesFromLoadBalancer(new DeregisterInstancesFromLoadBalancerRequest { Instances = registeredInstances, LoadBalancerName = ELBName }); //Console.WriteLine("Instances Detached:"); //foreach (Amazon.ElasticLoadBalancing.Model.Instance instance in registeredInstances) //{ // Console.WriteLine(instance.InstanceId); //} } if (!InstanceExists) { //Attach current instance client.RegisterInstancesWithLoadBalancer(new RegisterInstancesWithLoadBalancerRequest { Instances = new List<Amazon.ElasticLoadBalancing.Model.Instance> { EC2Instance }, LoadBalancerName = ELBName }); //Console.WriteLine("Instance Attached, ID : " + EC2Instance.InstanceId); } message = "Success"; } else { message = "Invalid Load Balancer Name"; } } else { message = "Invalid Instance Name"; } } else { message = "Specify Elastic Load Balancer Name and Instance Name to Register"; } return message; } catch(Exception ex) { return ex.Message; } } |
Hope you like it. More coming soon.
Happy programming :)
No comments:
Post a Comment