Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Requeriments:
- boto
- """
- import time
- from boto.ec2.connection import EC2Connection
- from boto.route53.connection import Route53Connection
- from boto.route53.record import ResourceRecordSets
- from boto.exception import BotoClientError
- AWS_ACCESS_KEY_ID = 'aws access key'
- AWS_SECRET_ACCSESS_KEY = 'aws secret key'
- HOSTED_ZONE = 'route53 hosted zone id'
- DOMAIN_NAME = 'vpn domain name'
- VPC_DOMAIN = 'default vpc'
- LOG_FILE = '/var/log/ip_change.log'
- VPN_INSTANCE_ID = 'instance id'
- get_change_id = lambda response: response['ChangeInfo']['Id'].split('/')[-1]
- get_change_status = lambda response: response['ChangeInfo']['Status']
- def change_ip(new_ip):
- try:
- conn = Route53Connection(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCSESS_KEY)
- zone = conn.get_hosted_zone(HOSTED_ZONE)
- response = conn.get_all_rrsets(HOSTED_ZONE, 'A', DOMAIN_NAME, maxitems=1)[0]
- old_ip = response.resource_records[0]
- # Delete the old record, and create a new one.
- # This code is from route53.py script, the change record command
- changes = ResourceRecordSets(conn, HOSTED_ZONE, '')
- change1 = changes.add_change("DELETE", DOMAIN_NAME, 'A', response.ttl)
- for old_ip in response.resource_records:
- change1.add_value(old_ip)
- change2 = changes.add_change("CREATE", DOMAIN_NAME, 'A', response.ttl)
- change2.add_value(new_ip)
- commit = changes.commit()
- change = conn.get_change(get_change_id(commit['ChangeResourceRecordSetsResponse']))
- while get_change_status(change['GetChangeResponse']) == 'PENDING':
- time.sleep(2)
- change = conn.get_change(get_change_id(change['GetChangeResponse']))
- except BotoClientError:
- logging.exception(BotoClientError)
- def change_elastic_ip(id):
- try:
- conn = EC2Connection(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCSESS_KEY)
- address = conn.allocate_address(domain=VPC_DOMAIN)
- conn.associate_address(instance_id=id, allocation_id=address.allocation_id)
- addresses = conn.get_all_addresses()
- for addr in addresses:
- if addr.instance_id is None:
- conn.release_address(allocation_id=addr.allocation_id)
- # print('%s - %s' % (addr.public_ip, addr.allocation_id))
- logging.info(address.public_ip)
- return address.public_ip
- except BotoClientError:
- logging.exception(BotoClientError)
- if __name__ == '__main__':
- import logging
- import logging.handlers
- FORMAT = "%(asctime)-15s %(message)s"
- logging.basicConfig(format=FORMAT, filename=LOG_FILE, level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
- change_ip(change_elastic_ip(VPN_INSTANCE_ID))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement