private async Task <HostedZone> ResolveMatchingZone(DnsRecord request)
        {
            try
            {
                if (!string.IsNullOrEmpty(request.ZoneId))
                {
                    var zone = await _route53Client.GetHostedZoneAsync(new GetHostedZoneRequest { Id = request.ZoneId });

                    return(zone.HostedZone);
                }
                else
                {
                    var zones = await _route53Client.ListHostedZonesAsync();

                    var zone = zones.HostedZones.Where(z => z.Name.Contains(request.TargetDomainName)).FirstOrDefault();
                    return(zone);
                }
            }
            catch (Exception)
            {
                //TODO: return error in result
                return(null);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieve a list of your hosted zones.
        /// </summary>
        /// <param name="settings">The <see cref="Route53Settings"/> required to connect to Route53.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <IList <HostedZone> > GetHostedZones(Route53Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            ListHostedZonesRequest request = new ListHostedZonesRequest();

            AmazonRoute53Client     client   = this.GetClient(settings);
            ListHostedZonesResponse response = await client.ListHostedZonesAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Listing hosted zones");
                return(response.HostedZones);
            }
            else
            {
                _Log.Error("Could not list hosted zones");
                return(null);
            }
        }
Exemplo n.º 3
0
        public async Task <HostedZone[]> ListHostedZonesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            ListHostedZonesResponse response = null;
            var results = new List <HostedZone>();

            while ((response = await _locker.Lock(() => _client.ListHostedZonesAsync(new ListHostedZonesRequest()
            {
                Marker = response?.NextMarker,
            }, cancellationToken: cancellationToken).EnsureSuccessAsync())) != null)
            {
                if (!response.HostedZones.IsNullOrEmpty())
                {
                    results.AddRange(response.HostedZones);
                }

                if (!response.IsTruncated)
                {
                    break;
                }
            }

            return(results.ToArray());
        }
        /// <summary>
        /// Used to modify recordset with value from api gateway code deploy in another account.
        /// </summary>
        /// <param name="jobEvent">CodePipeline event.</param>
        /// <param name="context">Lambda Context</param>
        /// <returns>Job success of the Lambda</returns>
        public async Task <AmazonWebServiceResponse> UpdateApiGatewayAliasRecordSet(CodePipelineJobEvent jobEvent, ILambdaContext context)
        {
            var jobId = jobEvent.CodePipelineJob.Id;

            context.Logger.LogLine($"JobId: {jobId}");

            using (var codePipelineClient = new AmazonCodePipelineClient())
                using (var s3Client = new AmazonS3Client())
                    using (var dnsClient = new AmazonRoute53Client())
                    {
                        // Prep the user parameters
                        var userParameters = jobEvent.CodePipelineJob.Data.ActionConfiguration.Configuration["UserParameters"];
                        context.Logger.LogLine("UserParameters:");
                        context.Logger.LogLine(userParameters);
                        var paramDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(userParameters);

                        try
                        {
                            DnsSettings dnsSettings = null;

                            // Get the first (only) input artifact
                            var artifact           = jobEvent.CodePipelineJob.Data.InputArtifacts.First();
                            var artifactBucketName = artifact.Location.S3Location.BucketName;
                            var artifactBucketKey  = artifact.Location.S3Location.ObjectKey;

                            // Unzip and get json
                            using (var getResponse = await s3Client.GetObjectAsync(artifactBucketName, artifactBucketKey))
                            {
                                var memoryStream = new MemoryStream();
                                using (var objectStream = getResponse.ResponseStream)
                                {
                                    objectStream.CopyTo(memoryStream);
                                }


                                var searchFile = paramDict["DnsJson"];
                                context.Logger.LogLine("Unziping artifact");
                                context.Logger.LogLine($"Searching for {searchFile}");
                                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Read))
                                {
                                    foreach (var entry in archive.Entries)
                                    {
                                        var fileName = entry.Name;
                                        context.Logger.LogLine("Checking File: " + entry.Name);

                                        if (searchFile == fileName)
                                        {
                                            using (var fileStream = entry.Open())
                                                using (var streamReader = new StreamReader(fileStream))
                                                {
                                                    var dnsJson = await streamReader.ReadToEndAsync();

                                                    dnsSettings = JsonConvert.DeserializeObject <DnsSettings>(dnsJson);
                                                }

                                            break;
                                        }
                                    }
                                }
                            }

                            // Get the hosted zones in the tools region
                            context.Logger.LogLine($"Searching for {dnsSettings.HostedZoneLookupDomainName}");
                            var hostedZones = await dnsClient.ListHostedZonesAsync();

                            var myHostedZone = hostedZones.HostedZones.FirstOrDefault(z => z.Name == dnsSettings.HostedZoneLookupDomainName);
                            if (myHostedZone == null)
                            {
                                var noZoneMessage = $"Hosted Zone {dnsSettings.HostedZoneLookupDomainName} could not be found";
                                context.Logger.LogLine(noZoneMessage);
                                var failureDetails = new FailureDetails
                                {
                                    Message = noZoneMessage,
                                    Type    = FailureType.ConfigurationError
                                };
                                return(await codePipelineClient.PutJobFailureResultAsync(jobId, failureDetails));
                            }

                            // The record set we need to create
                            var recordSet = new ResourceRecordSet
                            {
                                Name            = dnsSettings.WebApiDnsDomain,
                                Type            = RRType.A,
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = $"ALIAS {dnsSettings.RegionalDomainName}"
                                    }
                                }
                            };
                            var rsChange = new Change
                            {
                                Action            = ChangeAction.UPSERT,
                                ResourceRecordSet = recordSet
                            };
                            var rsChangeBatch = new ChangeBatch
                            {
                                Changes = new List <Change> {
                                    rsChange
                                }
                            };


                            // Create/Update the recordset
                            var changeDnsRequest = new ChangeResourceRecordSetsRequest
                            {
                                ChangeBatch  = rsChangeBatch,
                                HostedZoneId = myHostedZone.Id
                            };
                            var changeResponse = await dnsClient.ChangeResourceRecordSetsAsync(changeDnsRequest);

                            // Log and send the success response
                            context.Logger.LogLine($"Request Id {changeResponse.ChangeInfo.Id} submitted");
                            context.Logger.LogLine($"{dnsSettings.WebApiDnsDomain} => A ALIAS {dnsSettings.RegionalDomainName}");
                            var successResultRequest = new PutJobSuccessResultRequest
                            {
                                JobId = jobId
                            };
                            return(await codePipelineClient.PutJobSuccessResultAsync(successResultRequest));
                        }
                        catch (Exception ex)
                        {
                            // Send the failure response and log
                            return(await DoException(codePipelineClient, ex, jobId, context));
                        }
                    }
        }