Ejemplo n.º 1
0
def run(params):
    access_key, secret_key = get_aws_credentials(params)
    if (access_key and secret_key):
        con = route53.connect_to_region('universal',
                                        aws_access_key_id=access_key,
                                        aws_secret_access_key=secret_key)
    else:
        con = route53.connect_to_region('universal')
    if (access_key and secret_key):
        cons3 = S3Connection(access_key, secret_key)
    else:
        cons3 = boto.connect_s3()

    zone_name = params['<zone>']
    filename = params['<file>']
    bucketname = params['<bucket>']

    if params['dump']:
        dump(con, zone_name, filename)
    elif params['load']:
        load(con, zone_name, filename)
    elif params['dumps3']:
        dumps3(con, cons3, zone_name, bucketname)
    else:
        return 1
Ejemplo n.º 2
0
    def action(self):
        """Creates the zone"""
        conn = route53.connect_to_region(self.REGION)
        comment = json.dumps(self.get_raw_tags())

        hosted_zones = conn.get_all_hosted_zones()

        for hosted_zone in hosted_zones['ListHostedZonesResponse'][
                'HostedZones']:
            if ('Comment' in hosted_zone['Config']
                    and hosted_zone['Config']['Comment'] == comment):
                self.stack_outputs = {
                    'PrivateHostedZoneId': hosted_zone['Id'].split('/')[-1]
                }
                return

        hosted_zone = conn.create_hosted_zone(
            self.get_input('PrivateHostedZoneName'),
            comment=comment,
            private_zone=True,
            vpc_id=self.get_input('VpcId'),
            vpc_region=self.REGION)
        hosted_zone_id = hosted_zone['CreateHostedZoneResponse']['HostedZone'][
            'Id']
        self.stack_outputs = {
            'PrivateHostedZoneId': hosted_zone_id.split('/')[-1]
        }
Ejemplo n.º 3
0
	def __init__(self, config):		
		conn = route53.connect_to_region(config["region"])
		self.zone = conn.get_zone(config["zone"])
		self.domain = config["zone"]
		self.stack = config["stack"]
		self.our_ip = config["our_ip"]
		self.ttl = config["ttl"]
Ejemplo n.º 4
0
def run(params):
    access_key, secret_key = get_aws_credentials(params)
    con = route53.connect_to_region('universal',
                                    aws_access_key_id=access_key,
                                    aws_secret_access_key=secret_key)
    zone_name = params['<zone>']
    filename = params['<file>']

    vpc = {}
    if params.get('--private'):
        vpc['is_private'] = True
        vpc['region'] = params.get('--vpc-region') or environ.get(
            'AWS_DEFAULT_REGION')
        vpc['id'] = params.get('--vpc-id')
        if not vpc.get('region') or not vpc.get('id'):
            exit_with_error(
                "ERROR: Private zones require associated VPC Region and ID "
                "(--vpc-region, --vpc-id)".format(zone_name))
    else:
        vpc['is_private'] = False

    if params.get('dump'):
        dump(con, zone_name, get_file(filename, 'w'), vpc=vpc)
    elif params.get('load'):
        load(con, zone_name, get_file(filename, 'r'), vpc=vpc)
    else:
        return 1
    def action(self):
        region = self.get_input('Region')

        hosted_zone_name = self.get_input('PublicHostedZoneName')
        app_lb_endpoint = self.get_input('AppServerLoadBalancerEndpoint')
        app_lb_hosted_zone_id = self.get_input('AppServerLoadBalancerHostedZoneNameID')  # NOQA

        backward_compat_hosted_zone_name = self.get_input('BackwardCompatPublicHostedZoneName')  # NOQA
        backward_compat_app_lb_endpoint = self.get_input('BackwardCompatAppServerLoadBalancerEndpoint')
        backward_compat_app_lb_hosted_zone_id = self.get_input('BackwardCompatAppServerLoadBalancerHostedZoneNameID')  # NOQA

        route53_conn = r53.connect_to_region(region,
                                             profile_name=self.aws_profile)

        public_hosted_zone = route53_conn.get_zone(hosted_zone_name)
        record_sets = r53.record.ResourceRecordSets(route53_conn,
                                                    public_hosted_zone.id)
        record_sets.add_change('UPSERT', hosted_zone_name, 'A',
                               alias_hosted_zone_id=app_lb_hosted_zone_id,
                               alias_dns_name=app_lb_endpoint,
                               alias_evaluate_target_health=True,
                               identifier='Primary',
                               failover='PRIMARY')
        record_sets.commit()

        backward_compat_hosted_zone = route53_conn.get_zone(backward_compat_hosted_zone_name)
        backward_compat_record_sets = r53.record.ResourceRecordSets(route53_conn,
                                                                    backward_compat_hosted_zone.id)
        backward_compat_record_sets.add_change('UPSERT', backward_compat_hosted_zone_name, 'A',
                                               alias_hosted_zone_id=backward_compat_app_lb_hosted_zone_id,
                                               alias_dns_name=backward_compat_app_lb_endpoint,
                                               alias_evaluate_target_health=True,
                                               identifier='Primary',
                                               failover='PRIMARY')
        backward_compat_record_sets.commit()
Ejemplo n.º 6
0
def run(params):
    access_key, secret_key = get_aws_credentials(params)
    con = route53.connect_to_region('universal', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
    con_s3 = connect_s3(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
    zone_name = params['<zone>']
    filename = params['<file>']

    vpc = {}
    if params.get('--private'):
        vpc['is_private'] = True
        vpc['region'] = params.get('--vpc-region') or environ.get('AWS_DEFAULT_REGION')
        vpc['id'] = params.get('--vpc-id')
        if not vpc.get('region') or not vpc.get('id'):
            exit_with_error("ERROR: Private zones require associated VPC Region and ID "
                            "(--vpc-region, --vpc-id)".format(zone_name))
    else:
        vpc['is_private'] = False

    if params.get('dump'):
        dump(con, zone_name, get_file(filename, 'w'), vpc=vpc)
        if params.get('--s3-bucket'):
            up_to_s3(con_s3, params.get('<file>'), params.get('--s3-bucket'))
    elif params.get('load'):
        load(con, zone_name, get_file(filename, 'r'), vpc=vpc)
    else:
        return 1
Ejemplo n.º 7
0
    def action(self):
        region = self.get_input('Region')
        conn = r53.connect_to_region(region, profile_name=self.aws_profile)
        comment = json.dumps(self.get_raw_tags())

        hosted_zones = conn.get_all_hosted_zones()

        for hosted_zone in hosted_zones['ListHostedZonesResponse'][
                'HostedZones']:  # NOQA
            if ('Comment' in hosted_zone['Config']
                    and hosted_zone['Config']['Comment'] == comment):
                self.stack_outputs = {
                    'PrivateHostedZoneId': hosted_zone['Id'].split('/')[-1]
                }
                return

        hosted_zone = conn.create_hosted_zone('{}.'.format(
            self.get_input('PrivateHostedZoneName')),
                                              comment=comment,
                                              private_zone=True,
                                              vpc_id=self.get_input('VpcId'),
                                              vpc_region=region)
        hosted_zone_id = hosted_zone['CreateHostedZoneResponse']['HostedZone'][
            'Id']  # NOQA
        self.stack_outputs = {
            'PrivateHostedZoneId': hosted_zone_id.split('/')[-1]
        }  # NOQA
    def action(self):
        region = self.get_input('Region')
        color = self.get_input('StackColor')

        hosted_zone_name = self.get_input('PublicHostedZoneName')
        app_lb_endpoint = self.get_input('AppServerLoadBalancerEndpoint')
        app_lb_hosted_zone_id = self.get_input(
            'AppServerLoadBalancerHostedZoneNameID')

        backward_compat_hosted_zone_name = self.get_input(
            'BackwardCompatPublicHostedZoneName')
        backward_compat_app_lb_endpoint = self.get_input(
            'BackwardCompatAppServerLoadBalancerEndpoint')
        backward_compat_app_lb_hosted_zone_id = self.get_input(
            'BackwardCompatAppServerLoadBalancerHostedZoneNameID')

        route53_conn = r53.connect_to_region(region,
                                             profile_name=self.aws_profile)

        public_hosted_zone = route53_conn.get_zone(hosted_zone_name)
        record_sets = r53.record.ResourceRecordSets(route53_conn,
                                                    public_hosted_zone.id)
        record_sets.add_change('UPSERT', hosted_zone_name, 'A',
                               alias_hosted_zone_id=app_lb_hosted_zone_id,
                               alias_dns_name=app_lb_endpoint,
                               alias_evaluate_target_health=True,
                               identifier='Primary',
                               failover='PRIMARY')
        record_sets.commit()

        backward_compat_hosted_zone = route53_conn.get_zone(
            backward_compat_hosted_zone_name)
        backward_compat_record_sets = r53.record.ResourceRecordSets(
            route53_conn, backward_compat_hosted_zone.id)
        backward_compat_record_sets.add_change(
            'UPSERT', backward_compat_hosted_zone_name, 'A',
            alias_hosted_zone_id=backward_compat_app_lb_hosted_zone_id,
            alias_dns_name=backward_compat_app_lb_endpoint,
            alias_evaluate_target_health=True, identifier='Primary',
            failover='PRIMARY')
        backward_compat_record_sets.commit()

        s3_conn = s3.connect_to_region(region,
                                       profile_name=self.aws_profile,
                                       calling_format=OrdinaryCallingFormat())

        bucket = s3_conn.get_bucket('tile-cache.{}'.format(hosted_zone_name))

        rules = s3.website.RoutingRules()
        rules.add_rule(s3.website.RoutingRule(
            s3.website.Redirect(
                protocol='https',
                http_redirect_code=302,
                hostname='{}-tiles.{}'.format(color.lower(),
                                              hosted_zone_name)),
            s3.website.Condition(http_error_code=404)))

        bucket.configure_website(suffix='index.html', error_key='error.html',
                                 routing_rules=rules)
Ejemplo n.º 9
0
def create_domain(region, namespace, mappings, parameters, **kwargs):
    conn = connect_to_region(region)
    domain = kwargs.get('domain', parameters.get('BaseDomain'))
    if not domain:
        logger.error("domain argument or BaseDomain parameter not provided.")
        return False
    create_route53_zone(conn, domain)
    return True
Ejemplo n.º 10
0
def run(params):
    access_key, secret_key = get_aws_credentials(params)
    con = route53.connect_to_region('universal', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
    zone_name = params['<zone>']
    filename = params['<file>']

    if params['dump']:
        dump(con, zone_name, get_file(filename, 'w'))
    elif params['load']:
        load(con, zone_name, get_file(filename, 'r'))
    else:
        return 1
Ejemplo n.º 11
0
 def set_service_dns(self, domain_name):
     r53 = route53.connect_to_region(self.region)
     dns_zone = None
     for zone in r53.get_zones():
         if domain_name == zone.name:
             dns_zone = zone
     if not dns_zone:
         raise Exception(
             'DNS Hosting for {0} not setup in Route53'.format(domain_name))
     status = dns_zone.add_record(
         'CNAME', '{0}.{1}'.format(self.app_name.strip(), domain_name),
         self.app_load_balancer.dns_name)
     return status
Ejemplo n.º 12
0
 def set_instance_dns(self, instance_id, host_name, domain_name,
                      ip_address):
     r53 = route53.connect_to_region(self.region)
     dns_zone = None
     for zone in r53.get_zones():
         if domain_name == zone.name:
             dns_zone = zone
     if not dns_zone:
         raise Exception(
             'DNS Hosting for {0} not setup in Route53'.format(domain_name))
     dns_name = "{0}.{1}.{2}".format(instance_id, host_name, domain_name)
     dns_zone.add_record('A', dns_name, ip_address)
     return dns_name
 def run(self, terms, variables=None, **kwargs):
     zoneid = terms[0]
     recordtype = terms[1]
     recordname = terms[2]
     r53conn = route53.connect_to_region('universal',
         aws_access_key_id=AWS_ACCESS_KEY_ID,
         aws_secret_access_key=AWS_SECRET_ACCESS_KEY
     )
     records = r53conn.get_all_rrsets(zoneid,recordtype,recordname,maxitems=1)[0]
     recordvalue = records.resource_records[0]
     if recordvalue:
         return [recordvalue]
     return None
    def create_cache_private_dns_record(self, cache_cluster_node_endpoint):
        """Create or update the private DNS entry for the cache cluster"""
        route53_conn = r53.connect_to_region(self.region,
                                             profile_name=self.aws_profile)
        private_hosted_zone = route53_conn.get_zone(self.hosted_zone_name)
        cache_dns_record_name = 'cache.service.{}.'.format(
            self.hosted_zone_name)
        cache_dns_record = private_hosted_zone.get_cname(cache_dns_record_name)

        if not cache_dns_record:
            private_hosted_zone.add_cname(cache_dns_record_name,
                                          cache_cluster_node_endpoint, ttl=10)
        elif cache_cluster_node_endpoint not in cache_dns_record.resource_records:  # NOQA
            private_hosted_zone.update_cname(cache_dns_record_name,
                                             cache_cluster_node_endpoint,
                                             ttl=10)
 def run(self, terms, variables=None, **kwargs):
     zoneid = terms[0]
     recordtype = terms[1]
     recordname = terms[2]
     r53conn = route53.connect_to_region(
         'universal',
         aws_access_key_id=AWS_ACCESS_KEY_ID,
         aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
     records = r53conn.get_all_rrsets(zoneid,
                                      recordtype,
                                      recordname,
                                      maxitems=1)[0]
     recordvalue = records.resource_records[0]
     if recordvalue:
         return [recordvalue]
     return None
Ejemplo n.º 16
0
 def set_elb_dns(self, domain_name):
     elbo = elb.connect_to_region(self.region)
     lb = elbo.get_all_load_balancers(
         load_balancer_names=self.lb_name).pop()
     r53 = route53.connect_to_region(self.region)
     dns_zone = None
     for zone in r53.get_zones():
         if domain_name == zone.name:
             dns_zone = zone
     if not dns_zone:
         raise Exception(
             'DNS Hosting for {0} not setup in Route53'.format(domain_name))
     status = dns_zone.add_record(
         'CNAME', '{0}.{1}'.format(self.lb_name.strip(), domain_name),
         lb.dns_name)
     return status
    def action(self):
        region = self.get_input('Region')

        hosted_zone_name = self.get_input('PublicHostedZoneName')
        app_lb_endpoint = self.get_input('AppServerLoadBalancerEndpoint')
        app_lb_hosted_zone_id = self.get_input(
            'AppServerLoadBalancerHostedZoneNameID')  # NOQA

        backward_compat_hosted_zone_name = self.get_input(
            'BackwardCompatPublicHostedZoneName')  # NOQA
        backward_compat_app_lb_endpoint = self.get_input(
            'BackwardCompatAppServerLoadBalancerEndpoint')
        backward_compat_app_lb_hosted_zone_id = self.get_input(
            'BackwardCompatAppServerLoadBalancerHostedZoneNameID')  # NOQA

        route53_conn = r53.connect_to_region(region,
                                             profile_name=self.aws_profile)

        public_hosted_zone = route53_conn.get_zone(hosted_zone_name)
        record_sets = r53.record.ResourceRecordSets(route53_conn,
                                                    public_hosted_zone.id)
        record_sets.add_change('UPSERT',
                               hosted_zone_name,
                               'A',
                               alias_hosted_zone_id=app_lb_hosted_zone_id,
                               alias_dns_name=app_lb_endpoint,
                               alias_evaluate_target_health=True,
                               identifier='Primary',
                               failover='PRIMARY')
        record_sets.commit()

        backward_compat_hosted_zone = route53_conn.get_zone(
            backward_compat_hosted_zone_name)
        backward_compat_record_sets = r53.record.ResourceRecordSets(
            route53_conn, backward_compat_hosted_zone.id)
        backward_compat_record_sets.add_change(
            'UPSERT',
            backward_compat_hosted_zone_name,
            'A',
            alias_hosted_zone_id=backward_compat_app_lb_hosted_zone_id,
            alias_dns_name=backward_compat_app_lb_endpoint,
            alias_evaluate_target_health=True,
            identifier='Primary',
            failover='PRIMARY')
        backward_compat_record_sets.commit()
Ejemplo n.º 18
0
def test_new_record():
    node = get_node()
    config = get_config()

    r53 = route53.connect_to_region(node['region'])
    zone = r53.create_zone(
        config['name'],
        private_zone=True,
        vpc_id='1',
        vpc_region=node['region'],
    )

    hosted_zone_module = HostedZone(node, config)
    hostname = 'master0-123'
    fqdn = hosted_zone_module.run(hostname)
    assert fqdn == '.'.join([hostname, zone.name.lower()])
    record = zone.get_a(fqdn)
    assert record.resource_records == [node['metadata']['local-ipv4']]
Ejemplo n.º 19
0
    def action(self):
        """Creates the zone"""
        conn = route53.connect_to_region(self.REGION)
        comment = json.dumps(self.get_raw_tags())

        hosted_zones = conn.get_all_hosted_zones()

        for hosted_zone in hosted_zones['ListHostedZonesResponse']['HostedZones']:
            if ('Comment' in hosted_zone['Config'] and
                    hosted_zone['Config']['Comment'] == comment):
                self.stack_outputs = {'PrivateHostedZoneId': hosted_zone['Id'].split('/')[-1]}
                return

        hosted_zone = conn.create_hosted_zone(self.get_input('PrivateHostedZoneName'),
                                              comment=comment,
                                              private_zone=True,
                                              vpc_id=self.get_input('VpcId'),
                                              vpc_region=self.REGION)
        hosted_zone_id = hosted_zone['CreateHostedZoneResponse']['HostedZone']['Id']
        self.stack_outputs = {'PrivateHostedZoneId': hosted_zone_id.split('/')[-1]}
Ejemplo n.º 20
0
def answer_dns_challenge(client, domain, challenge):
    """
    Compute the required answer and set it in the DNS record
    for the domain.
    """
    authorization = "{}.{}".format(
        base64.urlsafe_b64encode(
            challenge.get("token")).decode("ascii").replace("=", ""),
        base64.urlsafe_b64encode(
            client.key.thumbprint()).decode("ascii").replace("=", ""))

    dns_response = base64.urlsafe_b64encode(
        hashlib.sha256(
            authorization.encode()).digest()).decode("ascii").replace("=", "")

    # Let's update the DNS on our R53 account
    r53 = route53.connect_to_region(exec_region)
    zone = r53.get_zone(domain['r53_zone'])
    if zone == None:
        LOG.error("Cannot find R53 zone {}, are you controling it ?".format(
            domain['r53_zone']))
        exit(1)

    acme_domain = "_acme-challenge.{}".format(domain['name'])
    record = zone.find_records(name=acme_domain, type="TXT")
    if record:
        delete_status = zone.delete_record(record)

    add_status = zone.add_record("TXT", acme_domain, '"' + dns_response + '"')
    dns_updated = wait_until_sync(add_status)

    if dns_updated == False:
        LOG.error(
            "We updated R53 but the servers didn't sync within 10 seconds. Bailing out."
        )
        exit(1)

    ## Now, let's tell the ACME server that we are ready
    challenge_response = challenges.DNS01Response(
        key_authorization=authorization)
    challenge_resource = client.answer_challenge(challenge, challenge_response)
    def action(self):
        region = self.get_input("Region")
        hosted_zone_name = self.get_input("PublicHostedZoneName")
        app_lb_endpoint = self.get_input("AppServerLoadBalancerEndpoint")
        app_lb_hosted_zone_id = self.get_input("AppServerLoadBalancerHostedZoneNameID")  # NOQA

        route53_conn = r53.connect_to_region(region, profile_name=self.aws_profile)
        public_hosted_zone = route53_conn.get_zone(hosted_zone_name)

        record_sets = r53.record.ResourceRecordSets(route53_conn, public_hosted_zone.id)
        record_sets.add_change(
            "UPSERT",
            hosted_zone_name,
            "A",
            alias_hosted_zone_id=app_lb_hosted_zone_id,
            alias_dns_name=app_lb_endpoint,
            alias_evaluate_target_health=True,
            identifier="Primary",
            failover="PRIMARY",
        )
        record_sets.commit()
Ejemplo n.º 22
0
def run(params):
    dryrun = params.get('--dry-run')

    if dryrun:
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s %(levelname)s [[DRY RUN]] %(message)s',
            StreamHandler=sys.stdout)
    else:
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(levelname)s %(message)s',
                            StreamHandler=sys.stdout)

    access_key, secret_key = get_aws_credentials(params)
    con = route53.connect_to_region('universal',
                                    aws_access_key_id=access_key,
                                    aws_secret_access_key=secret_key)
    zone_name = params['<zone>']
    filename = params['<file>']

    vpc = {}
    if params.get('--private'):
        vpc['is_private'] = True
        vpc['region'] = params.get('--vpc-region') or environ.get(
            'AWS_DEFAULT_REGION')
        vpc['id'] = params.get('--vpc-id')
        if not vpc.get('region') or not vpc.get('id'):
            exit_with_error(
                "ERROR: Private zones require associated VPC Region and ID "
                "(--vpc-region, --vpc-id)".format(zone_name))
    else:
        vpc['is_private'] = False

    if params.get('dump'):
        dump(con, zone_name, get_file(filename, 'w'), vpc=vpc)
    elif params.get('load'):
        load(con, zone_name, get_file(filename, 'r'), vpc=vpc, dryrun=dryrun)
    else:
        return 1
    def action(self):
        region = self.get_input('Region')
        conn = r53.connect_to_region(region, profile_name=self.aws_profile)
        comment = json.dumps(self.get_raw_tags())

        hosted_zones = conn.get_all_hosted_zones()

        for hosted_zone in hosted_zones['ListHostedZonesResponse']['HostedZones']:  # NOQA
            if ('Comment' in hosted_zone['Config'] and
                    hosted_zone['Config']['Comment'] == comment):
                self.stack_outputs = {
                    'PrivateHostedZoneId': hosted_zone['Id'].split('/')[-1]
                }
                return

        hosted_zone = conn.create_hosted_zone(
            '{}.'.format(self.get_input('PrivateHostedZoneName')),
            comment=comment, private_zone=True, vpc_id=self.get_input('VpcId'),
            vpc_region=region
        )
        hosted_zone_id = hosted_zone['CreateHostedZoneResponse']['HostedZone']['Id']  # NOQA
        self.stack_outputs = {'PrivateHostedZoneId': hosted_zone_id.split('/')[-1]}  # NOQA
Ejemplo n.º 24
0
 def _get_zone(self) -> route53.zone.Zone:
     r53_connection = route53.connect_to_region(self.node['region'])
     zone = r53_connection.get_zone(self.config['name'])
     if not zone:
         raise Exception('Hosted Zone %s not found' % self.config['name'])
     return zone
def route53_connect():
    return route53.connect_to_region('us-west-2') 
Ejemplo n.º 26
0
 def connect(self):
     self.connection = route53.connect_to_region(region_name=self.aws_region)
Ejemplo n.º 27
0
scalr_instance_index = os.environ.get('SCALR_INSTANCE_INDEX')
aws_dns_name = os.environ.get('AWS_DNS_NAME')
mongoInternalIP = os.environ.get('SCALR_INTERNAL_IP')
mongoReplicaDNSName = os.environ.get('MONGO_DNS_NAME')
mongoEnv = os.environ.get('MONGO_ENV')

def main():

    print mongoReplicaDNSName
    print aws_dns_name
    print region
    print mongoInternalIP
    print mongoReplicaDNSName+"."+mongoEnv+"."+aws_dns_name
    
try:
    conn_eu = route53.connect_to_region(region)
    hostedZone = conn_eu.get_zone(aws_dns_name)    
    change_set = route53.record.ResourceRecordSets(conn_eu, hostedZone.id)
    changes1 = change_set.add_change("UPSERT",mongoReplicaDNSName+"."+mongoEnv+"."+aws_dns_name, type="A",ttl=300)
    changes1.add_value(mongoInternalIP)
    change_set.commit()
##Add dns name to tag    
    conn_inst = ec2.connect_to_region(region,aws_access_key_id=aws_access_key,aws_secret_access_key=aws_secret_key)
    instID=get_instance_metadata()['instance-id']
    conn_inst.create_tags([instID], {"mngDNS": mongoReplicaDNSName+"."+mongoEnv+"."+aws_dns_name})
    
except Exception as e: print(e)
  
if __name__ == "__main__":
    main();
Ejemplo n.º 28
0
        clean_env()
        self.conf = '%s/%s/%s.ini' % (os.getenv('AWS_CRED_DIR'),
                                      acct_name, acct_name)
        try:
            boto.config.load_credential_file(self.conf)
        except IOError, msg:
            print >> sys.stderr, 'ERROR: %s' % msg
            return False
        if service == 's3':
            self.conn = s3.connect_to_region(region)
        if service == 'ec2':
            self.conn = ec2.connect_to_region(region)
        if service == 'rds':
            self.conn = rds.connect_to_region(region)
        if service == 'rds2':
            self.conn = rds2.connect_to_region(region)
        if service == 'elb':
            self.conn = elb.connect_to_region(region)
        if service == 'sqs':
            self.conn = sqs.connect_to_region(region)
        if service == 'emr':
            self.conn = emr.connect_to_region(region)
        if service == 'route53':
            self.conn = route53.connect_to_region(region)
        if service == 'iam':
            self.conn = iam.connect_to_region('universal')
        if not self.conn:
            print >> sys.stderr, 'ERROR: Unknown service'
            return False
        return self.conn
Ejemplo n.º 29
0
def get_public_ip():
   html = urllib2.urlopen(DDWRT_ROUTER_STATUS_PAGE).read()
   p = re.compile(r"IP\: ([0-9\.]*)\</span")
   f = p.search(html)
   if f and len(f.groups()) > 0:
      ip = f.groups()[0]
      return ip
   else:
      print("Could not scrape IP address in router status page")
      sys.exit(1)


wan_ip = get_public_ip()
print("Current WAN IP on Router: {}".format(wan_ip))

r53 = route53.connect_to_region('universal')
rec = r53.get_all_rrsets(AWS_R53_ZONE, 'A', AWS_R53_ZONE_RECORD, maxitems = 1)[0]
cur_ip =  str(rec.resource_records[0])

if cur_ip == wan_ip:
   print("Nothing to update - current IP {} configured for {} is still correct.".format(cur_ip, AWS_R53_ZONE_RECORD))
else:
   print("IP for {} needs to be updated from {} to {} ...".format(AWS_R53_ZONE_RECORD, cur_ip, wan_ip))

   try:
      r53rr = ResourceRecordSets(r53, AWS_R53_ZONE)
      d_record = r53rr.add_change('DELETE', AWS_R53_ZONE_RECORD, "A", 60)
      d_record.add_value(cur_ip)
      c_record = r53rr.add_change('CREATE', AWS_R53_ZONE_RECORD, 'A', 60)
      c_record.add_value(wan_ip)
      r53rr.commit()
    def action(self):
        region = self.get_input('Region')
        color = self.get_input('StackColor')

        hosted_zone_name = self.get_input('PublicHostedZoneName')
        app_lb_endpoint = self.get_input('AppServerLoadBalancerEndpoint')
        app_lb_hosted_zone_id = self.get_input(
            'AppServerLoadBalancerHostedZoneNameID')

        backward_compat_hosted_zone_name = self.get_input(
            'BackwardCompatPublicHostedZoneName')
        backward_compat_app_lb_endpoint = self.get_input(
            'BackwardCompatAppServerLoadBalancerEndpoint')
        backward_compat_app_lb_hosted_zone_id = self.get_input(
            'BackwardCompatAppServerLoadBalancerHostedZoneNameID')

        route53_conn = r53.connect_to_region(region,
                                             profile_name=self.aws_profile)

        public_hosted_zone = route53_conn.get_zone(hosted_zone_name)
        record_sets = r53.record.ResourceRecordSets(route53_conn,
                                                    public_hosted_zone.id)
        record_sets.add_change('UPSERT',
                               hosted_zone_name,
                               'A',
                               alias_hosted_zone_id=app_lb_hosted_zone_id,
                               alias_dns_name=app_lb_endpoint,
                               alias_evaluate_target_health=True,
                               identifier='Primary',
                               failover='PRIMARY')
        record_sets.commit()

        backward_compat_hosted_zone = route53_conn.get_zone(
            backward_compat_hosted_zone_name)
        backward_compat_record_sets = r53.record.ResourceRecordSets(
            route53_conn, backward_compat_hosted_zone.id)
        backward_compat_record_sets.add_change(
            'UPSERT',
            backward_compat_hosted_zone_name,
            'A',
            alias_hosted_zone_id=backward_compat_app_lb_hosted_zone_id,
            alias_dns_name=backward_compat_app_lb_endpoint,
            alias_evaluate_target_health=True,
            identifier='Primary',
            failover='PRIMARY')
        backward_compat_record_sets.commit()

        s3_conn = s3.connect_to_region(region,
                                       profile_name=self.aws_profile,
                                       calling_format=OrdinaryCallingFormat())

        bucket = s3_conn.get_bucket('tile-cache.{}'.format(hosted_zone_name))

        rules = s3.website.RoutingRules()
        rules.add_rule(
            s3.website.RoutingRule(
                s3.website.Redirect(protocol='https',
                                    http_redirect_code=302,
                                    hostname='{}-tiles.{}'.format(
                                        color.lower(), hosted_zone_name)),
                s3.website.Condition(http_error_code=404)))

        bucket.configure_website(suffix='index.html',
                                 error_key='error.html',
                                 routing_rules=rules)
Ejemplo n.º 31
0
def sync(users, groups, route53_zone, hesiod_domain, dry_run):
    conn = r53.connect_to_region("us-east-1")

    record_type = "TXT"
    ttl = "60"

    # suffix of . on zone if not supplied
    if route53_zone[-1:] != ".":
        route53_zone += "."
    if hesiod_domain[-1:] != ".":
        hesiod_domain += "."

    # get existing hosted zones
    zones = {}
    results = conn.get_all_hosted_zones()
    for r53zone in results["ListHostedZonesResponse"]["HostedZones"]:
        zone_id = r53zone["Id"].replace("/hostedzone/", "")
        zones[r53zone["Name"]] = zone_id

    # ensure requested zone is hosted by route53
    if not route53_zone in zones:
        raise Exception("Zone %s does not exist in Route53" % route53_zone)

    sets = conn.get_all_rrsets(zones[route53_zone])

    # existing records
    existing_records = set()
    for rset in sets:
        if rset.type == record_type:
            if (
                rset.name.endswith("group." + hesiod_domain)
                or rset.name.endswith("gid." + hesiod_domain)
                or rset.name.endswith("passwd." + hesiod_domain)
                or rset.name.endswith("uid." + hesiod_domain)
                or rset.name.endswith("grplist." + hesiod_domain)
                or rset.name.endswith("ssh." + hesiod_domain)
            ):
                value = "".join(rset.resource_records).replace('"', "")
                existing_records.add(DNSRecord(str(rset.name), str(value)))

    # new records
    new_records = set()
    for group in groups:
        for record in group.dns_records(hesiod_domain, users):
            new_records.add(record)
    for user in users:
        for record in user.dns_records(hesiod_domain):
            new_records.add(record)

    to_remove = existing_records - new_records
    to_add = new_records - existing_records

    if to_remove:
        print "Deleting:"
        for r in sorted(to_remove):
            print r
        print
    else:
        print "Nothing to delete."

    if to_add:
        print "Adding:"
        for r in sorted(to_add):
            print r
        print
    else:
        print "Nothing to add."

    if dry_run:
        print "Dry run mode. Stopping."
        return

    # stop if nothing to do
    if not to_remove and not to_add:
        return

    changes = ResourceRecordSets(conn, zones[route53_zone])

    for record in to_remove:
        removal = changes.add_change("DELETE", record.fqdn, record_type, ttl)
        removal.add_value(txt_value(record.value))

    for record in to_add:
        addition = changes.add_change("CREATE", record.fqdn, record_type, ttl)
        addition.add_value(txt_value(record.value))

    try:
        result = changes.commit()
        status = Status(conn, result["ChangeResourceRecordSetsResponse"]["ChangeInfo"])
    except r53.exception.DNSServerError, e:
        raise Exception("Could not update DNS records.", e)
Ejemplo n.º 32
0
## JSON Response.
URL = 'http://ip.paddez.com/?json'
response = urllib.urlopen(URL)

data = json.loads(response.read())

REGION = 'eu-west-1'
DOMAIN = 'paddez.ninja'
OSLO = 'oslo.paddez.ninja'
RIGA = 'riga.paddez.ninja'

IP = data.get('ip')

## Route53 Connection and zones
r53 = aws.connect_to_region(REGION)
zone = r53.get_zone(DOMAIN)
apex = zone.get_a(DOMAIN)
oslo = zone.get_a(OSLO)
print oslo
print apex

addrs = ifaddresses('eth0')[AF_INET]
private_ip = addrs[0].get('addr')

# If the current public IP, does not match the record, UPSERT.
if(IP != apex.to_print()):
	print zone.update_a(DOMAIN, IP)

# If the current private IP != the record, UPSERT
if(private_ip != oslo.to_print()):