route53 8.3 KB
Newer Older
Bruce Pennypacker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
19 20
module: route53
version_added: "1.3"
Bruce Pennypacker committed
21
short_description: add or delete entries in Amazons Route53 DNS service
Bruce Pennypacker committed
22
description:
Bruce Pennypacker committed
23
     - Creates and deletes DNS records in Amazons Route53 service
Bruce Pennypacker committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
options:
  command:
    description:
      - Specifies the action to take.  
    required: true
    default: null
    aliases: []
    choices: [ 'get', 'create', 'delete' ]
  zone:
    description:
      - The DNS zone to modify
    required: true
    default: null
    aliases: []
  record:
    description:
      - The full DNS record to create or delete
    required: true
    default: null
    aliases: []
  ttl:
    description:
      - The TTL to give the new record
    required: false
    default: 3600 (one hour)
    aliases: []
  type:
    description:
      - The type of DNS record to create
    required: true
    default: null
    aliases: []
    choices: [ 'A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'NS' ]
  value:
    description:
      - The new value when creating a DNS record.  Multiple comma-spaced values are allowed.  When deleting a record all values for the record must be specified or Route53 will not delete it.
    required: false
    default: null
    aliases: []
Bruce Pennypacker committed
63
  aws_secret_key:
Bruce Pennypacker committed
64
    description:
Bruce Pennypacker committed
65
      - AWS secret key. 
Bruce Pennypacker committed
66 67
    required: false
    default: null
Bruce Pennypacker committed
68 69
    aliases: ['ec2_secret_key', 'secret_key']
  aws_access_key:
Bruce Pennypacker committed
70
    description:
Bruce Pennypacker committed
71
      - AWS access key. 
Bruce Pennypacker committed
72 73
    required: false
    default: null
Bruce Pennypacker committed
74
    aliases: ['ec2_access_key', 'access_key']
75 76 77 78 79 80
  overwrite:
    description:
      - Whether an existing record should be overwritten on create if values do not match
    required: false
    default: null
    aliases: []
Bruce Pennypacker committed
81 82 83 84 85
requirements: [ "boto" ]
author: Bruce Pennypacker
'''

EXAMPLES = '''
Bruce Pennypacker committed
86
# Add new.foo.com as an A record with 3 IPs
Bruce Pennypacker committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
- route53: >
      command=create
      zone=foo.com
      record=new.foo.com
      type=A
      ttl=7200
      value=1.1.1.1,2.2.2.2,3.3.3.3

# Retrieve the details for new.foo.com
- route53: >
      command=get
      zone=foo.com
      record=new.foo.com
      type=A
  register: rec

Bruce Pennypacker committed
103
# Delete new.foo.com A record using the results from the get command
Bruce Pennypacker committed
104 105 106
- route53: >
      command=delete
      zone=foo.com
Bruce Pennypacker committed
107 108 109
      record={{ rec.set.record }}
      type={{ rec.set.type }}
      value={{ rec.set.value }}
Bruce Pennypacker committed
110 111 112 113

# Add an AAAA record.  Note that because there are colons in the value
# that the entire parameter list must be quoted:
- route53: >
114
      command=create
Bruce Pennypacker committed
115 116 117 118
      zone=foo.com
      record=localhost.foo.com
      type=AAAA
      ttl=7200
119
      value="::1"
120 121 122 123 124 125 126 127 128 129 130 131

# Add a TXT record. Note that TXT and SPF records must be surrounded
# by quotes when sent to Route 53:
- route53: >
      command=create
      zone=foo.com
      record=localhost.foo.com
      type=TXT
      ttl=7200
      value="\"bar\""


Bruce Pennypacker committed
132
'''
Bruce Pennypacker committed
133 134

import sys
135
import time
Bruce Pennypacker committed
136 137 138 139 140 141 142 143 144

try:
    import boto
    from boto import route53
    from boto.route53.record import ResourceRecordSets
except ImportError:
    print "failed=True msg='boto required for this module'"
    sys.exit(1)

145 146 147 148 149 150 151 152 153 154 155 156 157 158
def commit(changes):
    """Commit changes, but retry PriorRequestNotComplete errors."""
    retry = 10
    while True:
        try:
            retry -= 1
            return changes.commit()
        except boto.route53.exception.DNSServerError, e:
            code = e.body.split("<Code>")[1]
            code = code.split("</Code>")[0]
            if code != 'PriorRequestNotComplete' or retry < 0:
                raise e
            time.sleep(500)

Bruce Pennypacker committed
159
def main():
160
    argument_spec = ec2_argument_spec()
161
    argument_spec.update(dict(
Bruce Pennypacker committed
162 163 164 165 166 167
            command         = dict(choices=['get', 'create', 'delete'], required=True),
            zone            = dict(required=True),
            record          = dict(required=True),
            ttl             = dict(required=False, default=3600),
            type            = dict(choices=['A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'NS'], required=True),
            value           = dict(required=False), 
168
            overwrite       = dict(required=False, type='bool')
Bruce Pennypacker committed
169 170
        )
    )
171
    module = AnsibleModule(argument_spec=argument_spec)
Bruce Pennypacker committed
172 173

    command_in            = module.params.get('command')
174 175 176 177 178
    zone_in               = module.params.get('zone')
    ttl_in                = module.params.get('ttl')
    record_in             = module.params.get('record')
    type_in               = module.params.get('type')
    value_in              = module.params.get('value')
179 180

    ec2_url, aws_access_key, aws_secret_key, region = get_ec2_creds(module)
Bruce Pennypacker committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

    value_list = ()

    if type(value_in) is str:
        if value_in:
            value_list = sorted(value_in.split(','))
    elif type(value_in)  is list:
        value_list = sorted(value_in)

    if zone_in[-1:] != '.':
        zone_in += "."

    if record_in[-1:] != '.':
        record_in += "."

    if command_in == 'create' or command_in == 'delete':
        if not value_in:
            module.fail_json(msg = "parameter 'value' required for create/delete")

    # connect to the route53 endpoint 
    try:
Bruce Pennypacker committed
202
        conn = boto.route53.connection.Route53Connection(aws_access_key, aws_secret_key)
Bruce Pennypacker committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    except boto.exception.BotoServerError, e:
        module.fail_json(msg = e.error_message)

    # Get all the existing hosted zones and save their ID's
    zones = {}
    results = conn.get_all_hosted_zones()
    for r53zone in results['ListHostedZonesResponse']['HostedZones']:
        zone_id = r53zone['Id'].replace('/hostedzone/', '')
        zones[r53zone['Name']] = zone_id

    # Verify that the requested zone is already defined in Route53
    if not zone_in in zones:
        errmsg = "Zone %s does not exist in Route53" % zone_in
        module.fail_json(msg = errmsg)

    record = {}
    
    found_record = False
    sets = conn.get_all_rrsets(zones[zone_in])
    for rset in sets:
223 224 225
        # Due to a bug in either AWS or Boto, "special" characters are returned as octals, preventing round
        # tripping of things like * and @.
        decoded_name = rset.name.replace(r'\052', '*')
226
        decoded_name = decoded_name.replace(r'\100', '@')
227 228

        if rset.type == type_in and decoded_name == record_in:
Bruce Pennypacker committed
229 230 231
            found_record = True
            record['zone'] = zone_in
            record['type'] = rset.type
232
            record['record'] = decoded_name
Bruce Pennypacker committed
233 234 235
            record['ttl'] = rset.ttl
            record['value'] = ','.join(sorted(rset.resource_records))
            record['values'] = sorted(rset.resource_records)
236
            if value_list == sorted(rset.resource_records) and record['ttl'] == ttl_in and command_in == 'create':
Bruce Pennypacker committed
237 238 239 240 241 242 243 244 245 246
                module.exit_json(changed=False)

    if command_in == 'get':
        module.exit_json(changed=False, set=record)

    if command_in == 'delete' and not found_record:
        module.exit_json(changed=False)

    changes = ResourceRecordSets(conn, zones[zone_in])

247 248 249 250
    if command_in == 'create' and found_record:
        if not module.params['overwrite']:
            module.fail_json(msg = "Record already exists with different value. Set 'overwrite' to replace it")
        else:
251
            change = changes.add_change("DELETE", record_in, type_in, record['ttl'])
252 253 254
        for v in record['values']:
            change.add_value(v)

Bruce Pennypacker committed
255 256 257 258 259 260
    if command_in == 'create' or command_in == 'delete':
        change = changes.add_change(command_in.upper(), record_in, type_in, ttl_in)
        for v in value_list:
            change.add_value(v)

    try:
261
        result = commit(changes)
Bruce Pennypacker committed
262 263 264 265 266 267 268
    except boto.route53.exception.DNSServerError, e:
        txt = e.body.split("<Message>")[1]
        txt = txt.split("</Message>")[0]
        module.fail_json(msg = txt)

    module.exit_json(changed=True)

269 270 271
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
Bruce Pennypacker committed
272 273

main()