Exemplo n.º 1
0
    private async Task <DBInstance> GetDBInstanceByIdentifier(string identifier)
    {
        var instanceResponse = await _rdsClient.DescribeDBInstancesAsync();

        DBInstance?instanceChosen = instanceResponse.DBInstances.SingleOrDefault(x => x.DBInstanceIdentifier == identifier);

        if (instanceChosen is null)
        {
            throw new Exception($"RDS instance not found: {identifier}");
        }

        return(instanceChosen);
    }
 public virtual void failover()
 {
     try
     {
         //fail over rds which is in the same AZ
         // Note: This turns the asynchronous call into a synchronous one
         DescribeDBInstancesResponse describeDBInstancesResult = RDS_CLIENT.DescribeDBInstancesAsync().GetAwaiter().GetResult();
         IList <DBInstance>          dbInstances = describeDBInstancesResult.DBInstances;
         string dbInstancedId = null;
         foreach (DBInstance dbInstance in dbInstances)
         {
             if (string.Equals(dbInstance.DBSubnetGroup.VpcId, vpcId, StringComparison.OrdinalIgnoreCase) &&
                 dbInstance.MultiAZ && dbInstance.StatusInfos.Count == 0)
             {
                 dbInstancedId = dbInstance.DBInstanceIdentifier;
             }
         }
         if (!string.IsNullOrEmpty(dbInstancedId))
         {
             RebootDBInstanceRequest rebootDBInstanceRequest = new RebootDBInstanceRequest();
             rebootDBInstanceRequest.DBInstanceIdentifier = dbInstancedId;
             rebootDBInstanceRequest.ForceFailover        = true;
             Console.WriteLine("Rebooting dbInstanceId " + dbInstancedId);
             // Note: This turns the asynchronous call into a synchronous one
             RDS_CLIENT.RebootDBInstanceAsync(rebootDBInstanceRequest).GetAwaiter().GetResult();
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine("Unkown exception occured " + exception.Message);
     }
 }
Exemplo n.º 3
0
        public APIGatewayProxyResponse Status(APIGatewayProxyRequest request, ILambdaContext context)
        {
            // Log entries show up in CloudWatch
            context.Logger.LogLine("Starting Status Function");

            var c               = new AmazonRDSClient();
            var dbs             = new DescribeDBInstancesRequest();
            var tags            = new ListTagsForResourceRequest();
            var RDSResponseList = new List <RDSStatusResponse>();

            try
            {
                var dbresponse = Task.Run(() => c.DescribeDBInstancesAsync(dbs).Result);
                dbresponse.Result.DBInstances.ForEach(instance =>
                {
                    var listtagrequest          = new ListTagsForResourceRequest();
                    listtagrequest.ResourceName = instance.DBInstanceArn;
                    //query tags on instance
                    var tagresponse = Task.Run(() => c.ListTagsForResourceAsync(listtagrequest).Result);
                    //iterate through tags
                    tagresponse.Result.TagList.ForEach(tag =>
                    {
                        //check if tag name is keep-off
                        if (tag.Key == "keep-off")
                        {
                            //set status object for response
                            var RDSstatus             = new RDSStatusResponse();
                            RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                            RDSstatus.TagValue        = tag.Value;
                            RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                            RDSResponseList.Add(RDSstatus);
                        }
                    });
                });


                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(RDSResponseList),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                };

                return(response);
            }catch (Exception ex)
            {
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(ex),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            }
        }
        public async Task <DescribeDBInstancesResponse> GetDatabases()
        {
            using (var amazonRDSClient = new AmazonRDSClient(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonRDSClient.DescribeDBInstancesAsync();

                return(response);
            }
        }
Exemplo n.º 5
0
        public async Task <SA_RdsInstance> GetRDSInstance()
        {
            var response = await client.DescribeDBInstancesAsync();

            var lstInstance = response.DBInstances;

            foreach (var instance in lstInstance)
            {
                if (instance.DBSubnetGroup.DBSubnetGroupName.IndexOf(environment.ToString()) >= 0)
                {
                    SA_RdsInstance objInstance = new SA_RdsInstance
                    {
                        DBInstanceIdentifier = instance.DBInstanceIdentifier,
                        DBInstanceArn        = instance.DBInstanceArn,
                        RdsEnvinronment      = environment,
                        Status  = instance.DBInstanceStatus,
                        MultiAZ = instance.MultiAZ
                    };
                    return(objInstance);
                }
            }
            return(null);
        }
Exemplo n.º 6
0
        public bool IsDBExistis()
        {
            DescribeDBInstancesRequest describeDBInstances = new DescribeDBInstancesRequest();

            describeDBInstances.DBInstanceIdentifier = "jaguar";
            var resp = amazonRDSClient.DescribeDBInstancesAsync(describeDBInstances).Result;

            if (resp.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return(false);
            }

            return(false);
        }
Exemplo n.º 7
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            SkillResponse skillResponse = new SkillResponse();

            skillResponse.Response = new ResponseBody
            {
                ShouldEndSession = false
            };

            IOutputSpeech outputSpeech  = null;
            var           log           = context.Logger;
            var           intentRequest = input.Request as IntentRequest;

            outputSpeech = new PlainTextOutputSpeech();

            if (input.GetRequestType() == typeof(LaunchRequest))
            { // einfacher Aufruf des Skills ohne Aufgabenstellung ( Intent )
                log.LogLine("39: Launch ");

                (outputSpeech as PlainTextOutputSpeech).Text = "Ergebnis der Suche nach Datenbanken: ";
                AmazonRDSClient amazonRDSClient = new AmazonRDSClient(StaticValues.AWS_ACCESS_KEY, StaticValues.AWS_SECRET_KEY, Amazon.RegionEndpoint.EUCentral1);
                try
                {
                    DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
                    // request.DBInstanceIdentifier = "opensandbox";
                    var response = amazonRDSClient.DescribeDBInstancesAsync(request);
                    foreach (var instance in response.Result.DBInstances)
                    {
                        log.LogLine(instance.DBName);
                        (outputSpeech as PlainTextOutputSpeech).Text += instance.DBName;
                        (outputSpeech as PlainTextOutputSpeech).Text += instance.Engine + " Version: " + instance.EngineVersion;
                    }
                }
                catch (Exception e)
                {
                    log.LogLine("58:" + e.Message);
                }
            }

            skillResponse.Response.OutputSpeech = outputSpeech;
            skillResponse.Version = "1.0";
            return(skillResponse);
        }
Exemplo n.º 8
0
        public APIGatewayProxyResponse KeepOff(APIGatewayProxyRequest request, ILambdaContext context)
        {
            // Log entries show up in CloudWatch
            context.Logger.LogLine("Starting KeepOff Function");

            var c               = new AmazonRDSClient();
            var dbs             = new DescribeDBInstancesRequest();
            var tags            = new ListTagsForResourceRequest();
            var RDSResponseList = new List <RDSStatusResponse>();

            try {
                var dbresponse = Task.Run(() => c.DescribeDBInstancesAsync(dbs).Result);
                dbresponse.Result.DBInstances.ForEach(instance =>
                {
                    //log arn on instance
                    //context.Logger.LogLine(instance.DBInstanceArn);
                    var listtagrequest          = new ListTagsForResourceRequest();
                    listtagrequest.ResourceName = instance.DBInstanceArn;
                    //query tags on instance
                    var tagresponse = Task.Run(() => c.ListTagsForResourceAsync(listtagrequest).Result);
                    //iterate through tags
                    tagresponse.Result.TagList.ForEach(tag =>
                    {
                        //check if tag name is keep-off
                        if (tag.Key == "keep-off")
                        {
                            //context.Logger.LogLine(instance.DBInstanceArn);
                            //check if tag value is true
                            if (tag.Value == "true")
                            {
                                //check if instance is on
                                if (instance.DBInstanceStatus == "available")
                                {
                                    //check if instance is on
                                    var RDSstatus             = new RDSStatusResponse();
                                    RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                    RDSstatus.TagValue        = tag.Value;
                                    RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                    RDSstatus.Note            = "Making call to turn off";
                                    RDSResponseList.Add(RDSstatus);


                                    var stopdb = new StopDBInstanceRequest();
                                    stopdb.DBInstanceIdentifier = instance.DBInstanceIdentifier;

                                    var stopresponse = Task.Run(() => c.StopDBInstanceAsync(stopdb));
                                    //Log that db is stopping
                                    context.Logger.LogLine(instance.DBInstanceArn + " has been stopped with status");
                                }
                                else
                                {
                                    var RDSstatus             = new RDSStatusResponse();
                                    RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                    RDSstatus.TagValue        = tag.Value;
                                    RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                    RDSstatus.Note            = "Not in available state";
                                    RDSResponseList.Add(RDSstatus);
                                }
                            }
                            else
                            {
                                var RDSstatus             = new RDSStatusResponse();
                                RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                RDSstatus.TagValue        = tag.Value;
                                RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                RDSstatus.Note            = "Has Tag but Value is not true";
                                RDSResponseList.Add(RDSstatus);
                            }
                        }
                    }

                                                       );
                });


                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(RDSResponseList),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            } catch (Exception ex) {
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(ex),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            }
        }
        public virtual void failover()
        {
            try
            {
                // Modify the autoscaling group to remove the AZ affected which is the AZ passed in the input
                // Find the autoscaling group that this is deployed into
                // Note: This changes the asynchronous call to a synchronous one
                DescribeAutoScalingGroupsResponse autoScalingGroupsResponse = AUTO_SCALING_CLIENT.DescribeAutoScalingGroupsAsync().GetAwaiter().GetResult();

                if (autoScalingGroupsResponse != null && autoScalingGroupsResponse.AutoScalingGroups.Count > 0)
                {
                    // Note: This assumes an Auto Scaling group exists; no error checking for readability
                    AutoScalingGroup autoScalingGroup     = autoScalingGroupsResponse.AutoScalingGroups[0];
                    string           autoScalingGroupName = autoScalingGroup.AutoScalingGroupName;

                    // Find all subnets in the availability zone passed in the input
                    DescribeSubnetsResponse subnetsResult
                        = EC2_CLIENT.DescribeSubnetsAsync(new DescribeSubnetsRequest()
                    {
                        Filters = new List <Amazon.EC2.Model.Filter> {
                            new Amazon.EC2.Model.Filter {
                                Name   = "vpc-id",
                                Values = new List <string> {
                                    vpcId
                                }
                            }
                        }
                    }).GetAwaiter().GetResult();
                    IList <string> desiredSubnetsForASG = new List <string>();
                    foreach (Amazon.EC2.Model.Subnet subnet in subnetsResult.Subnets)
                    {
                        if (!string.Equals(subnet.AvailabilityZone, azId, StringComparison.OrdinalIgnoreCase))
                        {
                            desiredSubnetsForASG.Add(subnet.SubnetId);
                        }
                    }

                    List <string> desiredSubnets = new List <String>(autoScalingGroup.VPCZoneIdentifier.Split(new[] { ',' }, StringSplitOptions.None));

                    var tempList = new List <String>(desiredSubnets);
                    foreach (var subnet in desiredSubnets)
                    {
                        if (!desiredSubnetsForASG.Contains(subnet))
                        {
                            tempList.Remove(subnet);
                        }
                    }
                    desiredSubnets = tempList;

                    Console.WriteLine("Updating the auto scaling group " + autoScalingGroupName + " to remove the subnet in the AZ");

                    // Note: This turns the asynchronous call into a synchronous one
                    UpdateAutoScalingGroupResponse updateAutoScalingGroupResponse
                        = AUTO_SCALING_CLIENT.UpdateAutoScalingGroupAsync(new UpdateAutoScalingGroupRequest
                    {
                        AutoScalingGroupName = autoScalingGroupName,
                        VPCZoneIdentifier    = string.Join(",", desiredSubnets)
                    }).GetAwaiter().GetResult();
                }

                // Find all subnets in the availability zone passed in the input
                // Note: This turns the asynchronous call into a synchronous one
                DescribeSubnetsResponse describeSubnetsResult
                    = EC2_CLIENT.DescribeSubnetsAsync(new DescribeSubnetsRequest
                {
                    Filters = new List <Amazon.EC2.Model.Filter> {
                        new Amazon.EC2.Model.Filter {
                            Name   = "vpc-id",
                            Values = new List <string> {
                                vpcId
                            }
                        },
                        new Amazon.EC2.Model.Filter {
                            Name   = "availabilityZone",
                            Values = new List <string> {
                                azId
                            }
                        }
                    }
                }).GetAwaiter().GetResult();

                IList <string> desiredSubnetsForAddingNewNacl = new List <string>();
                foreach (Amazon.EC2.Model.Subnet subnet in describeSubnetsResult.Subnets)
                {
                    desiredSubnetsForAddingNewNacl.Add(subnet.SubnetId);
                }

                //Find all the network acl associations matching the subnets identified above
                // Note: This turns the asynchronous call into a synchronous one
                DescribeNetworkAclsResponse describeNetworkAclsResult
                    = EC2_CLIENT.DescribeNetworkAclsAsync(new DescribeNetworkAclsRequest()
                {
                    Filters = new List <Amazon.EC2.Model.Filter> {
                        new Amazon.EC2.Model.Filter {
                            Name   = "association.subnet-id",
                            Values = (List <string>)desiredSubnetsForAddingNewNacl
                        }
                    }
                }).GetAwaiter().GetResult();

                IList <NetworkAclAssociation> desiredAclAssociations = new List <NetworkAclAssociation>();
                // Note: This assumes a Network ACL is present for readability
                IList <NetworkAclAssociation> networkAclsAssociatedWithSubnet = describeNetworkAclsResult.NetworkAcls[0].Associations;
                foreach (string subnetId in desiredSubnetsForAddingNewNacl)
                {
                    foreach (NetworkAclAssociation networkAcl in networkAclsAssociatedWithSubnet)
                    {
                        if (string.Equals(networkAcl.SubnetId, subnetId, StringComparison.OrdinalIgnoreCase))
                        {
                            desiredAclAssociations.Add(networkAcl);
                        }
                    }
                }

                //create new network acl association with both ingress and egress denying to all the traffic
                CreateNetworkAclRequest createNetworkAclRequest = new CreateNetworkAclRequest();
                createNetworkAclRequest.VpcId = vpcId;
                // Note: This turns the asynchronous call into a synchronous one
                CreateNetworkAclResponse createNetworkAclResponse = EC2_CLIENT.CreateNetworkAclAsync(createNetworkAclRequest).GetAwaiter().GetResult();
                string networkAclId = createNetworkAclResponse.NetworkAcl.NetworkAclId;
                createNetworkAclEntry(networkAclId, 100, "0.0.0.0/0", true, "-1", createPortRange(0, 65535), RuleAction.Deny);
                createNetworkAclEntry(networkAclId, 101, "0.0.0.0/0", false, "-1", createPortRange(0, 65535), RuleAction.Deny);

                // replace all the network acl associations identified for the above subnets with the new network
                // acl association which will deny all traffic for those subnets in that AZ
                Console.WriteLine("Creating new network ACL associations");
                replaceNetworkAclAssociations(desiredAclAssociations, networkAclId);

                //fail over rds which is in the same AZ
                // Note: This turns the asynchronous call into a synchronous one
                DescribeDBInstancesResponse describeDBInstancesResult = RDS_CLIENT.DescribeDBInstancesAsync().GetAwaiter().GetResult();
                IList <DBInstance>          dbInstances = describeDBInstancesResult.DBInstances;
                string dbInstancedId = null;
                foreach (DBInstance dbInstance in dbInstances)
                {
                    if (string.Equals(dbInstance.DBSubnetGroup.VpcId, vpcId, StringComparison.OrdinalIgnoreCase) &&
                        (string.Equals(dbInstance.AvailabilityZone, azId, StringComparison.OrdinalIgnoreCase)) &&
                        dbInstance.MultiAZ && dbInstance.StatusInfos.Count == 0)
                    {
                        dbInstancedId = dbInstance.DBInstanceIdentifier;
                    }
                }
                // we want to fail over rds if rds is present in the same az where it is affected
                if (!string.IsNullOrEmpty(dbInstancedId))

                {
                    RebootDBInstanceRequest rebootDBInstanceRequest = new RebootDBInstanceRequest();
                    rebootDBInstanceRequest.DBInstanceIdentifier = dbInstancedId;
                    rebootDBInstanceRequest.ForceFailover        = true;
                    Console.WriteLine("Rebooting dbInstanceId to secondary AZ " + dbInstancedId);
                    // Note: This turns the asynchronous call into a synchronous one
                    RDS_CLIENT.RebootDBInstanceAsync(rebootDBInstanceRequest).GetAwaiter().GetResult();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Unkown exception occured " + exception.Message);
            }
        }