示例#1
0
        private static ChangeResourceRecordSetsResponse SetARecord(AmazonRoute53Client route53Client, string publicIp, AppSettings appConfig)
        {
            var ret = route53Client.ChangeResourceRecordSetsAsync(new ChangeResourceRecordSetsRequest()
            {
                HostedZoneId = appConfig.HostedZoneId,
                ChangeBatch  = new ChangeBatch()
                {
                    Changes = new List <Change>()
                    {
                        new Change()
                        {
                            Action            = ChangeAction.UPSERT,
                            ResourceRecordSet = new ResourceRecordSet()
                            {
                                Name            = appConfig.RecordName,
                                Type            = appConfig.Type,
                                TTL             = appConfig.TTL,
                                ResourceRecords = new List <ResourceRecord>()
                                {
                                    new ResourceRecord()
                                    {
                                        Value = publicIp
                                    }
                                }
                            }
                        }
                    }
                }
            }).Result;

            return(ret);
        }
示例#2
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-an-alias-resource-record-set-1484348404062

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                AliasTarget = new AliasTarget {
                                    DNSName = "d123rk29d0stfj.cloudfront.net",
                                    EvaluateTargetHealth = false,
                                    HostedZoneId         = "Z2FDTNDATAQYW2"
                                },
                                Name = "example.com",
                                Type = "A"
                            }
                        }
                    },
                    Comment = "CloudFront distribution for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#3
0
        private void InitConfig()
        {
            AddLog("Loading configuration values...");

            _configHandler = new AppConfigHandler();
            _config        = _configHandler.GetConfig();
            _ipChecker     = _config.IPChecker;

            var _amazonClient = new AmazonRoute53Client(_config.Route53AccessKey, _config.Route53SecretKey, RegionEndpoint.USEast1);

            _dnsUpdater = new DnsUpdater(_amazonClient);

            AddLog($"Found {_config.DomainList.Count} domain(s)");
            foreach (HostedDomainInfo domainInfo in _config.DomainList)
            {
                AddLog($"{domainInfo.DomainName}");
            }

            if (_timer != null)
            {
                // Stop to avoid multiple timer_Tick invocations
                _timer.Stop();
            }

            int interval = _config.UpdateInterval;

            _timer          = new System.Windows.Threading.DispatcherTimer();
            _timer.Tick    += timer_Tick;
            _timer.Interval = new TimeSpan(0, 0, interval);
            _timer.Start();

            AddLog($"Time set to update domains every {interval} seconds");

            SetAutoStart();
        }
示例#4
0
        public async Task <bool> UpdateIpAddressForSubdomain(string hostedZoneId, string fqdn, string newIpAddress)
        {
            using (AmazonRoute53Client route53Client = GetAmazonRoute53Client())
            {
                ListResourceRecordSetsResponse records = await route53Client.ListResourceRecordSetsAsync(new ListResourceRecordSetsRequest(hostedZoneId));

                // Look for an A record matching the FQDN that was passed in
                ResourceRecordSet matchingRecordSet = records?.ResourceRecordSets.FirstOrDefault(prop => prop.Name == fqdn && prop.Type == RRType.A);

                if (matchingRecordSet != null && matchingRecordSet.ResourceRecords.Any())
                {
                    if (matchingRecordSet.ResourceRecords.First().Value != newIpAddress)
                    {
                        matchingRecordSet.ResourceRecords.First().Value = newIpAddress;
                        ChangeBatch change = new ChangeBatch();
                        change.Changes.Add(new Change(ChangeAction.UPSERT, matchingRecordSet));

                        ChangeResourceRecordSetsResponse changeRequest = await route53Client.ChangeResourceRecordSetsAsync(new ChangeResourceRecordSetsRequest(hostedZoneId, change));

                        Log.Information("[Runtime = {StartTime}] Change request submitted to change subdomain {Subdomain} IP address to {IPAddress}.", Settings.StartTime, fqdn, newIpAddress);

                        return(changeRequest.HttpStatusCode == System.Net.HttpStatusCode.OK);
                    }
                    else
                    {
                        Log.Information("[Runtime = {StartTime}] Subdomain {Subdomain} found, but the IP address was already {IPAddress}.", Settings.StartTime, fqdn, newIpAddress);
                    }
                }

                return(false);
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            var configHandler = new AppConfigHandler();
            var config        = configHandler.GetConfig();
            var ipChecker     = config.IPChecker;
            var route53Client = new AmazonRoute53Client(config.Route53AccessKey, config.Route53SecretKey, RegionEndpoint.EUWest1);
            var dnsUpdater    = new DnsUpdater(route53Client);

            HostFactory.Run(x =>
            {
                x.Service <IScheduledTaskService>(s =>
                {
                    s.ConstructUsing(name => new DnsUpdateService(new SchedulerRegistry(new ScheduledTaskWorker(dnsUpdater, ipChecker, config.DomainList))));
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();

                x.SetDisplayName("DynDns53 Service");
                x.SetServiceName("DynDns53");
                x.SetDescription("Updates AWS Route53 records with the current external IP of the system");

                x.StartAutomatically();

                x.EnableServiceRecovery(s =>
                {
                    s.RestartService(1);
                    s.RestartService(2);
                    s.RestartService(5);
                });
            });
        }
示例#6
0
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("Settings.json", true)
                                .AddEnvironmentVariables()
                                .AddCommandLine(args)
                                .Build();

            var manualResetEvent = new ManualResetEvent(false);

            var settings = configuration.GetSection("App").Get <AppSettings>();

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                manualResetEvent.Set();
            };

            client = new AmazonRoute53Client(new BasicAWSCredentials(settings.AccessKey, settings.SecretKey), RegionEndpoint.GetBySystemName(settings.Region));

            var timer = new Timer(Update, settings, 1000, settings.Interval);

            Console.WriteLine("Application started. Press Ctrl+C to shut down.");

            manualResetEvent.WaitOne();
        }
示例#7
0
        /// <summary>
        /// To retrieve a list of record sets for a particular hosted zone.
        /// </summary>
        /// <param name="hostedZoneId">The ID of the hosted zone whos record sets you want to list</param>
        /// <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 <ResourceRecordSet> > GetResourceRecordSets(string hostedZoneId, Route53Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(hostedZoneId))
            {
                throw new ArgumentNullException("hostedZoneId");
            }



            ListResourceRecordSetsRequest request = new ListResourceRecordSetsRequest(hostedZoneId);

            AmazonRoute53Client            client   = this.GetClient(settings);
            ListResourceRecordSetsResponse response = await client.ListResourceRecordSetsAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Listing record sets");
                return(response.ResourceRecordSets);
            }
            else
            {
                _Log.Error("Could not list record sets");
                return(null);
            }
        }
示例#8
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-update-or-delete-resource-record-sets-1484344703668

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                Name            = "example.com",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.44"
                                    }
                                },
                                TTL  = 60,
                                Type = "A"
                            }
                        }
                    },
                    Comment = "Web server for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE"
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#9
0
        /// <summary>
        /// Delete a hosted zone.
        /// </summary>
        /// <param name="hostedZoneId">The ID of the hosted zone that contains the resource record sets that you want to delete</param>
        /// <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 <bool> DeleteHostedZone(string hostedZoneId, Route53Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(hostedZoneId))
            {
                throw new ArgumentNullException("hostedZoneId");
            }



            DeleteHostedZoneRequest request = new DeleteHostedZoneRequest(hostedZoneId);

            AmazonRoute53Client      client   = this.GetClient(settings);
            DeleteHostedZoneResponse response = await client.DeleteHostedZoneAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                await this.WaitForChange(client, response.ChangeInfo.Id, 10000, 60);

                _Log.Verbose("deleted hosted zone");
                return(true);
            }
            else
            {
                _Log.Error("Could not delete hosted zone");
                return(false);
            }
        }
示例#10
0
        public void Route53ChangeTagsForResource()
        {
            #region to-add-or-remove-tags-from-a-hosted-zone-or-health-check-1484084752409

            var client   = new AmazonRoute53Client();
            var response = client.ChangeTagsForResource(new ChangeTagsForResourceRequest
            {
                AddTags = new List <Tag> {
                    new Tag {
                        Key   = "apex",
                        Value = "3874"
                    },
                    new Tag {
                        Key   = "acme",
                        Value = "4938"
                    }
                },
                RemoveTagKeys = new List <string> {
                    "Nadir"
                },
                ResourceId   = "Z3M3LMPEXAMPLE",
                ResourceType = "hostedzone" // Valid values are healthcheck and hostedzone.
            });


            #endregion
        }
示例#11
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonRoute53Config config = new AmazonRoute53Config();

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

            ListQueryLoggingConfigsResponse resp = new ListQueryLoggingConfigsResponse();

            do
            {
                ListQueryLoggingConfigsRequest req = new ListQueryLoggingConfigsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems.ToString()
                };

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

                foreach (var obj in resp.QueryLoggingConfigs)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
示例#12
0
        //[Fact]
        public async Task TestS3EventLambdaFunction()
        {
            var            reg = RegionEndpoint.USEast1;
            IAmazonEC2     ec2 = new AmazonEC2Client(reg);
            IAmazonRoute53 r53 = new AmazonRoute53Client(reg);
            IAmazonS3      s3  = new AmazonS3Client(reg);

            var bucketName = "lambda-VMBot-".ToLower() + DateTime.Now.Ticks;
            var key        = "text.txt";

            // Create a bucket an object to setup a test data.
            await s3.PutBucketAsync(bucketName);

            try
            {
                await s3.PutObjectAsync(new PutObjectRequest
                {
                    BucketName  = bucketName,
                    Key         = key,
                    ContentBody = "sample data"
                });

                // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function.
                var s3Event = new S3Event
                {
                    Records = new List <S3EventNotification.S3EventNotificationRecord>
                    {
                        new S3EventNotification.S3EventNotificationRecord
                        {
                            S3 = new S3EventNotification.S3Entity
                            {
                                Bucket = new S3EventNotification.S3BucketEntity {
                                    Name = bucketName
                                },
                                Object = new S3EventNotification.S3ObjectEntity {
                                    Key = key
                                }
                            }
                        }
                    }
                };

                var ec2StateChange = new EC2StateChangeEvent
                {
                };

                // Invoke the lambda function and confirm the content type was returned.
                var function = new Function(ec2, r53, s3);
                // var contentType = await function.FunctionHandler(s3Event, null);
                var contentType = await function.FunctionHandler(ec2StateChange, null);

                Assert.Equal("text/plain", contentType);
            }
            finally
            {
                // Clean up the test data
                await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3, bucketName);
            }
        }
示例#13
0
        public async Task <ListHostedZonesResponse> GetHostedZones()
        {
            using (var amazonRoute53Client = new AmazonRoute53Client(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonRoute53Client.ListHostedZonesAsync();

                return(response);
            }
        }
示例#14
0
        public AmazonRoute53Client GetAmazonRoute53Client()
        {
            AmazonRoute53Config config = new AmazonRoute53Config()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(Settings.AWSRegion) // TODO: inject
            };

            AmazonRoute53Client route53Client = new AmazonRoute53Client(Settings.AWSAccessKeyId, Settings.AWSAccessKeySecret, config);

            return(route53Client);
        }
示例#15
0
        private AmazonRoute53Client TheRoute53Client()
        {
            if (client == null)
            {
                logger.LogInformation("Creating Route53 client...");
                client = new AmazonRoute53Client(awsProfileCredentials, regionEndPoint);
            }

            logger.LogInformation("Returning Route53 client...");
            return(client);
        }
示例#16
0
        /// <summary>
        /// Create or change a DNS record for a hosted zone.
        /// </summary>
        /// <param name="hostedZoneId">The ID of the hosted zone that contains the resource record sets that you want to change</param>
        /// <param name="name">The name of the DNS record set.</param>
        /// <param name="type">The type of the DNS record set.</param>
        /// <param name="value">The value of the record set.</param>
        /// <param name="ttl">The time to live of the record set.</param>
        /// <param name="settings">The <see cref="Route53Settings"/> required to upload to Amazon S3.</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 <string> CreateResourceRecordSet(string hostedZoneId, string name, RRType type, string value, long ttl, Route53Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            var recordSet = new ResourceRecordSet()
            {
                Name            = name,
                TTL             = ttl,
                Type            = type,
                ResourceRecords = new List <ResourceRecord>
                {
                    new ResourceRecord {
                        Value = value
                    }
                }
            };

            var change1 = new Change()
            {
                ResourceRecordSet = recordSet,
                Action            = ChangeAction.UPSERT
            };

            var changeBatch = new ChangeBatch()
            {
                Changes = new List <Change> {
                    change1
                }
            };

            var recordsetRequest = new ChangeResourceRecordSetsRequest()
            {
                HostedZoneId = hostedZoneId,
                ChangeBatch  = changeBatch
            };



            AmazonRoute53Client client = this.GetClient(settings);
            ChangeResourceRecordSetsResponse response = await client.ChangeResourceRecordSetsAsync(recordsetRequest);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                await this.WaitForChange(client, response.ChangeInfo.Id, 10000, 60);

                _Log.Verbose("Updated record set");
                return(response.ChangeInfo.Id);
            }
            else
            {
                _Log.Error("Could not change resource records");
                return("");
            }
        }
示例#17
0
        private static void Main()
        {
            // Init the client
            var r53Client = new AmazonRoute53Client(AwsAccessKeyId, AwsSecretAccessKey, EndPoint);

            CreateHostedZone(r53Client, "kdh.blake.ly");
            CreateRecordSet(r53Client);
            var objGetHostedZones     = GetHostedZones(r53Client);
            var objResourceRecordSets = GetResourceRecordSets(r53Client);

            Console.WriteLine(objGetHostedZones);
            Console.WriteLine(objResourceRecordSets);
        }
示例#18
0
        public async Task <string> GetHostedZoneIdByName(string hostedZoneName)
        {
            using (AmazonRoute53Client route53Client = GetAmazonRoute53Client())
            {
                ListHostedZonesByNameResponse zones = await route53Client.ListHostedZonesByNameAsync(new ListHostedZonesByNameRequest()
                {
                    DNSName = hostedZoneName
                });

                HostedZone matchingZone = zones?.HostedZones.FirstOrDefault(zone => zone.Name == hostedZoneName);
                return(matchingZone?.Id);
            }
        }
示例#19
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-weighted-resource-record-sets-1484348208522

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                HealthCheckId   = "abcdef11-2222-3333-4444-555555fedcba",
                                Name            = "example.com",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.44"
                                    }
                                },
                                SetIdentifier = "Seattle data center",
                                TTL           = 60,
                                Type          = "A",
                                Weight        = 100
                            }
                        },
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                HealthCheckId   = "abcdef66-7777-8888-9999-000000fedcba",
                                Name            = "example.com",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.45"
                                    }
                                },
                                SetIdentifier = "Portland data center",
                                TTL           = 60,
                                Type          = "A",
                                Weight        = 200
                            }
                        }
                    },
                    Comment = "Web servers for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE"
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#20
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-failover-resource-record-sets-1484604541740

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                Failover        = "PRIMARY",
                                HealthCheckId   = "abcdef11-2222-3333-4444-555555fedcba",
                                Name            = "example.com",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.44"
                                    }
                                },
                                SetIdentifier = "Ohio region",
                                TTL           = 60,
                                Type          = "A"
                            }
                        },
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                Failover        = "SECONDARY",
                                HealthCheckId   = "abcdef66-7777-8888-9999-000000fedcba",
                                Name            = "example.com",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.45"
                                    }
                                },
                                SetIdentifier = "Oregon region",
                                TTL           = 60,
                                Type          = "A"
                            }
                        }
                    },
                    Comment = "Failover configuration for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE"
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#21
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-latency-resource-record-sets-1484350219917

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                HealthCheckId   = "abcdef11-2222-3333-4444-555555fedcba",
                                Name            = "example.com",
                                Region          = "us-east-2",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.44"
                                    }
                                },
                                SetIdentifier = "Ohio region",
                                TTL           = 60,
                                Type          = "A"
                            }
                        },
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                HealthCheckId   = "abcdef66-7777-8888-9999-000000fedcba",
                                Name            = "example.com",
                                Region          = "us-west-2",
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = "192.0.2.45"
                                    }
                                },
                                SetIdentifier = "Oregon region",
                                TTL           = 60,
                                Type          = "A"
                            }
                        }
                    },
                    Comment = "EC2 instances for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE"
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#22
0
        protected IAmazonRoute53 CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonRoute53Config {
                RegionEndpoint = region
            };

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

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
示例#23
0
        public void Route53GetHostedZone()
        {
            #region to-get-information-about-a-hosted-zone-1481752361124

            var client   = new AmazonRoute53Client();
            var response = client.GetHostedZone(new GetHostedZoneRequest
            {
                Id = "Z3M3LMPEXAMPLE"
            });

            DelegationSet delegationSet = response.DelegationSet;
            HostedZone    hostedZone    = response.HostedZone;

            #endregion
        }
示例#24
0
        public async Task <bool> InitProvider(Dictionary <string, string> credentials, Dictionary <string, string> parameters, ILog log = null)
        {
            _log = log;

            _route53Client = new AmazonRoute53Client(credentials["accesskey"], credentials["secretaccesskey"], Amazon.RegionEndpoint.USEast1);

            if (parameters?.ContainsKey("propagationdelay") == true)
            {
                if (int.TryParse(parameters["propagationdelay"], out int customPropDelay))
                {
                    _customPropagationDelay = customPropDelay;
                }
            }

            return(await Task.FromResult(true));
        }
示例#25
0
        public void Route53ChangeResourceRecordSets()
        {
            #region to-create-failover-alias-resource-record-sets-1484607497724

            var client   = new AmazonRoute53Client();
            var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest
            {
                ChangeBatch = new ChangeBatch {
                    Changes = new List <Change> {
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                AliasTarget = new AliasTarget {
                                    DNSName = "example-com-123456789.us-east-2.elb.amazonaws.com ",
                                    EvaluateTargetHealth = true,
                                    HostedZoneId         = "Z3AADJGX6KTTL2"
                                },
                                Failover      = "PRIMARY",
                                Name          = "example.com",
                                SetIdentifier = "Ohio region",
                                Type          = "A"
                            }
                        },
                        new Change {
                            Action            = "CREATE",
                            ResourceRecordSet = new ResourceRecordSet {
                                AliasTarget = new AliasTarget {
                                    DNSName = "example-com-987654321.us-west-2.elb.amazonaws.com ",
                                    EvaluateTargetHealth = true,
                                    HostedZoneId         = "Z1H1FL5HABSF5"
                                },
                                Failover      = "SECONDARY",
                                Name          = "example.com",
                                SetIdentifier = "Oregon region",
                                Type          = "A"
                            }
                        }
                    },
                    Comment = "Failover alias configuration for example.com"
                },
                HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#26
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);
            }
        }
示例#27
0
        private async static Task <string> GetHostedZoneIdByName(string hostedZoneName)
        {
            AmazonRoute53Config config = new AmazonRoute53Config()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(Settings.AWSRegion) // TODO: inject
            };

            using (AmazonRoute53Client route53Client = new AmazonRoute53Client(Settings.AWSAccessKeyId, Settings.AWSAccessKeySecret, config))
            {
                ListHostedZonesByNameResponse zones = await route53Client.ListHostedZonesByNameAsync(new ListHostedZonesByNameRequest()
                {
                    DNSName = hostedZoneName
                });

                HostedZone matchingZone = zones?.HostedZones.FirstOrDefault(zone => zone.Name == hostedZoneName);
                return(matchingZone?.Id);
            }
        }
示例#28
0
        public void Route53AssociateVPCWithHostedZone()
        {
            #region to-associate-a-vpc-with-a-hosted-zone-1484069228699

            var client   = new AmazonRoute53Client();
            var response = client.AssociateVPCWithHostedZone(new AssociateVPCWithHostedZoneRequest
            {
                Comment      = "",
                HostedZoneId = "Z3M3LMPEXAMPLE",
                VPC          = new VPC {
                    VPCId     = "vpc-1a2b3c4d",
                    VPCRegion = "us-east-2"
                }
            });

            ChangeInfo changeInfo = response.ChangeInfo;

            #endregion
        }
示例#29
0
        private async Task <bool> WaitForChange(AmazonRoute53Client client, string id, int interval = 10000, int maxIterations = 60)
        {
            bool pending = true;
            bool timeout = (maxIterations > 0);
            int  count   = 0;

            while (pending && !timeout)
            {
                //Check Status
                GetChangeResponse response = await client.GetChangeAsync(new GetChangeRequest(id));

                if ((response != null) && (response.HttpStatusCode == HttpStatusCode.OK))
                {
                    if (ChangeStatus.INSYNC == response.ChangeInfo.Status)
                    {
                        pending = false;
                    }
                }
                else
                {
                    timeout = true;
                }



                //Sleep
                if (count < maxIterations)
                {
                    Console.WriteLine("Change is pending...");
                    Thread.Sleep(interval);
                }
                else
                {
                    timeout = true;
                }

                count++;
            }

            return(timeout);
        }
示例#30
0
        private async static Task <bool> UpdateIpAddressForSubdomain(string hostedZoneId, string fqdn, string newIpAddress)
        {
            AmazonRoute53Config config = new AmazonRoute53Config()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(Settings.AWSRegion) // TODO: inject
            };

            using (AmazonRoute53Client route53Client = new AmazonRoute53Client(Settings.AWSAccessKeyId, Settings.AWSAccessKeySecret, config))
            {
                ListResourceRecordSetsResponse records = await route53Client.ListResourceRecordSetsAsync(new ListResourceRecordSetsRequest(hostedZoneId));

                ResourceRecordSet matchingRecordSet = records?.ResourceRecordSets.FirstOrDefault(prop => prop.Name == fqdn && prop.Type == RRType.A);

                if (matchingRecordSet != null && matchingRecordSet.ResourceRecords.FirstOrDefault() != null)
                {
                    if (matchingRecordSet.ResourceRecords.FirstOrDefault().Value != newIpAddress)
                    {
                        matchingRecordSet.ResourceRecords.FirstOrDefault().Value = newIpAddress;
                        ChangeBatch change = new ChangeBatch();
                        change.Changes.Add(new Change(ChangeAction.UPSERT, matchingRecordSet));

                        ChangeResourceRecordSetsResponse changeRequest = await route53Client.ChangeResourceRecordSetsAsync(new ChangeResourceRecordSetsRequest(hostedZoneId, change));

                        Log.Information("[Runtime = {StartTime}] Change request submitted to change subdomain {Subdomain} IP address to {IPAddress}.", startTime, fqdn, newIpAddress);

                        return(changeRequest.HttpStatusCode == System.Net.HttpStatusCode.OK);
                    }
                    else
                    {
                        Log.Information("[Runtime = {StartTime}] Subdomain {Subdomain} found, but the IP address was already {IPAddress}.", startTime, fqdn, newIpAddress);
                    }
                }
                else
                {
                    // New subdomain
                    Log.Information("[Runtime = {StartTime}] Subdomain {Subdomain} record not found.", startTime, fqdn);
                }

                return(false);
            }
        }