| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016 Michael Gruener <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: cloudflare_dns |
| 11 |
author: |
| 12 |
- Michael Gruener (@mgruener) |
| 13 |
short_description: Manage Cloudflare DNS records |
| 14 |
description: |
| 15 |
- 'Manages DNS records using the Cloudflare API, see the docs: U(https://api.cloudflare.com/).' |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.general._attributes |
| 18 |
attributes: |
| 19 |
check_mode: |
| 20 |
support: full |
| 21 |
diff_mode: |
| 22 |
support: none |
| 23 |
options: |
| 24 |
api_token: |
| 25 |
description: |
| 26 |
- API token. |
| 27 |
- Required for API token authentication. |
| 28 |
- "You can obtain your API token from the bottom of the Cloudflare 'My Account' page, found here: U(https://dash.cloudflare.com/)." |
| 29 |
- Can be specified in E(CLOUDFLARE_TOKEN) environment variable since community.general 2.0.0. |
| 30 |
type: str |
| 31 |
version_added: '0.2.0' |
| 32 |
account_api_key: |
| 33 |
description: |
| 34 |
- Account API key. |
| 35 |
- Required for API keys authentication. |
| 36 |
- "You can obtain your API key from the bottom of the Cloudflare 'My Account' page, found here: U(https://dash.cloudflare.com/)." |
| 37 |
type: str |
| 38 |
aliases: [account_api_token] |
| 39 |
account_email: |
| 40 |
description: |
| 41 |
- Account email. Required for API keys authentication. |
| 42 |
type: str |
| 43 |
algorithm: |
| 44 |
description: |
| 45 |
- Algorithm number. |
| 46 |
- Required for O(type=DS) and O(type=SSHFP) when O(state=present). |
| 47 |
type: int |
| 48 |
cert_usage: |
| 49 |
description: |
| 50 |
- Certificate usage number. |
| 51 |
- Required for O(type=TLSA) when O(state=present). |
| 52 |
type: int |
| 53 |
choices: [0, 1, 2, 3] |
| 54 |
comment: |
| 55 |
description: |
| 56 |
- Comments or notes about the DNS record. |
| 57 |
type: str |
| 58 |
version_added: 10.1.0 |
| 59 |
flag: |
| 60 |
description: |
| 61 |
- Issuer Critical Flag. |
| 62 |
- Should be set either to V(0) for not critical, or to V(128) for critical. |
| 63 |
- Before community.general 12.3.0, only V(0) and V(1) were valid options. |
| 64 |
The value V(1) is still available for backwards-compatibility reasons. |
| 65 |
- Required for O(type=CAA) when O(state=present). |
| 66 |
type: int |
| 67 |
choices: [0, 1, 128] |
| 68 |
version_added: 8.0.0 |
| 69 |
tag: |
| 70 |
description: |
| 71 |
- CAA issue restriction. |
| 72 |
- Required for O(type=CAA) when O(state=present). |
| 73 |
type: str |
| 74 |
choices: [issue, issuewild, iodef] |
| 75 |
version_added: 8.0.0 |
| 76 |
hash_type: |
| 77 |
description: |
| 78 |
- Hash type number. |
| 79 |
- Required for O(type=DS), O(type=SSHFP) and O(type=TLSA) when O(state=present). |
| 80 |
type: int |
| 81 |
choices: [1, 2] |
| 82 |
key_tag: |
| 83 |
description: |
| 84 |
- DNSSEC key tag. |
| 85 |
- Needed for O(type=DS) when O(state=present). |
| 86 |
type: int |
| 87 |
port: |
| 88 |
description: |
| 89 |
- Service port. |
| 90 |
- Required for O(type=SRV) and O(type=TLSA). |
| 91 |
type: int |
| 92 |
priority: |
| 93 |
description: |
| 94 |
- Record priority. |
| 95 |
- Required for O(type=MX) and O(type=SRV). |
| 96 |
default: 1 |
| 97 |
type: int |
| 98 |
proto: |
| 99 |
description: |
| 100 |
- Service protocol. Required for O(type=SRV) and O(type=TLSA). |
| 101 |
- Common values are TCP and UDP. |
| 102 |
type: str |
| 103 |
proxied: |
| 104 |
description: |
| 105 |
- Proxy through Cloudflare network or just use DNS. |
| 106 |
type: bool |
| 107 |
default: false |
| 108 |
record: |
| 109 |
description: |
| 110 |
- Record to add. |
| 111 |
- Required if O(state=present). |
| 112 |
- Default is V(@) (that is, the zone name). |
| 113 |
type: str |
| 114 |
default: '@' |
| 115 |
aliases: [name] |
| 116 |
selector: |
| 117 |
description: |
| 118 |
- Selector number. |
| 119 |
- Required for O(type=TLSA) when O(state=present). |
| 120 |
choices: [0, 1] |
| 121 |
type: int |
| 122 |
service: |
| 123 |
description: |
| 124 |
- Record service. |
| 125 |
- Required for O(type=SRV). |
| 126 |
type: str |
| 127 |
solo: |
| 128 |
description: |
| 129 |
- Whether the record should be the only one for that record type and record name. |
| 130 |
- Only use with O(state=present). |
| 131 |
- This deletes all other records with the same record name and type. |
| 132 |
type: bool |
| 133 |
state: |
| 134 |
description: |
| 135 |
- Whether the record(s) should exist or not. |
| 136 |
type: str |
| 137 |
choices: [absent, present] |
| 138 |
default: present |
| 139 |
tags: |
| 140 |
description: |
| 141 |
- Custom tags for the DNS record. |
| 142 |
type: list |
| 143 |
elements: str |
| 144 |
version_added: 10.1.0 |
| 145 |
timeout: |
| 146 |
description: |
| 147 |
- Timeout for Cloudflare API calls. |
| 148 |
type: int |
| 149 |
default: 30 |
| 150 |
ttl: |
| 151 |
description: |
| 152 |
- The TTL to give the new record. |
| 153 |
- Must be between V(120) and V(2,147,483,647) seconds, or V(1) for automatic. |
| 154 |
type: int |
| 155 |
default: 1 |
| 156 |
type: |
| 157 |
description: |
| 158 |
- The type of DNS record to create. Required if O(state=present). |
| 159 |
- Support for V(SPF) has been removed from community.general 9.0.0 since that record type is no longer supported by |
| 160 |
CloudFlare. |
| 161 |
- Support for V(PTR) has been added in community.general 11.1.0. |
| 162 |
type: str |
| 163 |
choices: [A, AAAA, CNAME, DS, MX, NS, SRV, SSHFP, TLSA, CAA, TXT, PTR] |
| 164 |
value: |
| 165 |
description: |
| 166 |
- The record value. |
| 167 |
- Required for O(state=present). |
| 168 |
type: str |
| 169 |
aliases: [content] |
| 170 |
weight: |
| 171 |
description: |
| 172 |
- Service weight. |
| 173 |
- Required for O(type=SRV). |
| 174 |
type: int |
| 175 |
default: 1 |
| 176 |
zone: |
| 177 |
description: |
| 178 |
- The name of the Zone to work with (for example V(example.com)). |
| 179 |
- The Zone must already exist. |
| 180 |
type: str |
| 181 |
required: true |
| 182 |
aliases: [domain] |
| 183 |
""" |
| 184 |
|
| 185 |
EXAMPLES = r""" |
| 186 |
- name: Create a test.example.net A record to point to 127.0.0.1 |
| 187 |
community.general.cloudflare_dns: |
| 188 |
zone: example.net |
| 189 |
record: test |
| 190 |
type: A |
| 191 |
value: 127.0.0.1 |
| 192 |
account_email: [email protected] |
| 193 |
account_api_key: dummyapitoken |
| 194 |
register: record |
| 195 |
|
| 196 |
- name: Create a record using api token |
| 197 |
community.general.cloudflare_dns: |
| 198 |
zone: example.net |
| 199 |
record: test |
| 200 |
type: A |
| 201 |
value: 127.0.0.1 |
| 202 |
api_token: dummyapitoken |
| 203 |
|
| 204 |
- name: Create a record with comment and tags |
| 205 |
community.general.cloudflare_dns: |
| 206 |
zone: example.net |
| 207 |
record: test |
| 208 |
type: A |
| 209 |
value: 127.0.0.1 |
| 210 |
comment: Local test website |
| 211 |
tags: |
| 212 |
- test |
| 213 |
- local |
| 214 |
api_token: dummyapitoken |
| 215 |
|
| 216 |
- name: Create a example.net CNAME record to example.com |
| 217 |
community.general.cloudflare_dns: |
| 218 |
zone: example.net |
| 219 |
type: CNAME |
| 220 |
value: example.com |
| 221 |
account_email: [email protected] |
| 222 |
account_api_key: dummyapitoken |
| 223 |
state: present |
| 224 |
|
| 225 |
- name: Change its TTL |
| 226 |
community.general.cloudflare_dns: |
| 227 |
zone: example.net |
| 228 |
type: CNAME |
| 229 |
value: example.com |
| 230 |
ttl: 600 |
| 231 |
account_email: [email protected] |
| 232 |
account_api_key: dummyapitoken |
| 233 |
state: present |
| 234 |
|
| 235 |
- name: Delete the record |
| 236 |
community.general.cloudflare_dns: |
| 237 |
zone: example.net |
| 238 |
type: CNAME |
| 239 |
value: example.com |
| 240 |
account_email: [email protected] |
| 241 |
account_api_key: dummyapitoken |
| 242 |
state: absent |
| 243 |
|
| 244 |
- name: Create a example.net CNAME record to example.com and proxy through Cloudflare's network |
| 245 |
community.general.cloudflare_dns: |
| 246 |
zone: example.net |
| 247 |
type: CNAME |
| 248 |
value: example.com |
| 249 |
proxied: true |
| 250 |
account_email: [email protected] |
| 251 |
account_api_key: dummyapitoken |
| 252 |
state: present |
| 253 |
|
| 254 |
# This deletes all other TXT records named "test.example.net" |
| 255 |
- name: Create TXT record "test.example.net" with value "unique value" |
| 256 |
community.general.cloudflare_dns: |
| 257 |
domain: example.net |
| 258 |
record: test |
| 259 |
type: TXT |
| 260 |
value: unique value |
| 261 |
solo: true |
| 262 |
account_email: [email protected] |
| 263 |
account_api_key: dummyapitoken |
| 264 |
state: present |
| 265 |
|
| 266 |
- name: Create an SRV record _foo._tcp.example.net |
| 267 |
community.general.cloudflare_dns: |
| 268 |
domain: example.net |
| 269 |
service: foo |
| 270 |
proto: tcp |
| 271 |
port: 3500 |
| 272 |
priority: 10 |
| 273 |
weight: 20 |
| 274 |
type: SRV |
| 275 |
value: fooserver.example.net |
| 276 |
|
| 277 |
- name: Create a SSHFP record login.example.com |
| 278 |
community.general.cloudflare_dns: |
| 279 |
zone: example.com |
| 280 |
record: login |
| 281 |
type: SSHFP |
| 282 |
algorithm: 4 |
| 283 |
hash_type: 2 |
| 284 |
value: 9dc1d6742696d2f51ca1f1a78b3d16a840f7d111eb9454239e70db31363f33e1 |
| 285 |
|
| 286 |
- name: Create a TLSA record _25._tcp.mail.example.com |
| 287 |
community.general.cloudflare_dns: |
| 288 |
zone: example.com |
| 289 |
record: mail |
| 290 |
port: 25 |
| 291 |
proto: tcp |
| 292 |
type: TLSA |
| 293 |
cert_usage: 3 |
| 294 |
selector: 1 |
| 295 |
hash_type: 1 |
| 296 |
value: 6b76d034492b493e15a7376fccd08e63befdad0edab8e442562f532338364bf3 |
| 297 |
|
| 298 |
- name: Create a CAA record subdomain.example.com |
| 299 |
community.general.cloudflare_dns: |
| 300 |
zone: example.com |
| 301 |
record: subdomain |
| 302 |
type: CAA |
| 303 |
flag: 0 |
| 304 |
tag: issue |
| 305 |
value: ca.example.com |
| 306 |
|
| 307 |
- name: Create a DS record for subdomain.example.com |
| 308 |
community.general.cloudflare_dns: |
| 309 |
zone: example.com |
| 310 |
record: subdomain |
| 311 |
type: DS |
| 312 |
key_tag: 5464 |
| 313 |
algorithm: 8 |
| 314 |
hash_type: 2 |
| 315 |
value: B4EB5AC4467D2DFB3BAF9FB9961DC1B6FED54A58CDFAA3E465081EC86F89BFAB |
| 316 |
|
| 317 |
- name: Create PTR record "1.2.0.192.in-addr.arpa" with value "test.example.com" |
| 318 |
community.general.cloudflare_dns: |
| 319 |
zone: 2.0.192.in-addr.arpa |
| 320 |
record: 1 |
| 321 |
type: PTR |
| 322 |
value: test.example.com |
| 323 |
state: present |
| 324 |
""" |
| 325 |
|
| 326 |
RETURN = r""" |
| 327 |
record: |
| 328 |
description: A dictionary containing the record data. |
| 329 |
returned: success, except on record deletion |
| 330 |
type: dict |
| 331 |
contains: |
| 332 |
comment: |
| 333 |
description: Comments or notes about the DNS record. |
| 334 |
returned: success |
| 335 |
type: str |
| 336 |
sample: Domain verification record |
| 337 |
version_added: 10.1.0 |
| 338 |
comment_modified_on: |
| 339 |
description: When the record comment was last modified. Omitted if there is no comment. |
| 340 |
returned: success |
| 341 |
type: str |
| 342 |
sample: "2024-01-01T05:20:00.12345Z" |
| 343 |
version_added: 10.1.0 |
| 344 |
content: |
| 345 |
description: The record content (details depend on record type). |
| 346 |
returned: success |
| 347 |
type: str |
| 348 |
sample: 192.0.2.91 |
| 349 |
created_on: |
| 350 |
description: The record creation date. |
| 351 |
returned: success |
| 352 |
type: str |
| 353 |
sample: "2016-03-25T19:09:42.516553Z" |
| 354 |
data: |
| 355 |
description: Additional record data. |
| 356 |
returned: success, if type is SRV, DS, SSHFP TLSA or CAA |
| 357 |
type: dict |
| 358 |
sample: |
| 359 |
{ |
| 360 |
"name": "jabber", |
| 361 |
"port": 8080, |
| 362 |
"priority": 10, |
| 363 |
"proto": "_tcp", |
| 364 |
"service": "_xmpp", |
| 365 |
"target": "jabberhost.sample.com", |
| 366 |
"weight": 5 |
| 367 |
} |
| 368 |
id: |
| 369 |
description: The record ID. |
| 370 |
returned: success |
| 371 |
type: str |
| 372 |
sample: f9efb0549e96abcb750de63b38c9576e |
| 373 |
locked: |
| 374 |
description: No documentation available. |
| 375 |
returned: success |
| 376 |
type: bool |
| 377 |
sample: false |
| 378 |
meta: |
| 379 |
description: Extra Cloudflare-specific information about the record. |
| 380 |
returned: success |
| 381 |
type: dict |
| 382 |
sample: {"auto_added": false} |
| 383 |
modified_on: |
| 384 |
description: Record modification date. |
| 385 |
returned: success |
| 386 |
type: str |
| 387 |
sample: "2016-03-25T19:09:42.516553Z" |
| 388 |
name: |
| 389 |
description: The record name as FQDN (including _service and _proto for SRV). |
| 390 |
returned: success |
| 391 |
type: str |
| 392 |
sample: www.sample.com |
| 393 |
priority: |
| 394 |
description: Priority of the MX record. |
| 395 |
returned: success, if type is MX |
| 396 |
type: int |
| 397 |
sample: 10 |
| 398 |
proxiable: |
| 399 |
description: Whether this record can be proxied through Cloudflare. |
| 400 |
returned: success |
| 401 |
type: bool |
| 402 |
sample: false |
| 403 |
proxied: |
| 404 |
description: Whether the record is proxied through Cloudflare. |
| 405 |
returned: success |
| 406 |
type: bool |
| 407 |
sample: false |
| 408 |
tags: |
| 409 |
description: Custom tags for the DNS record. |
| 410 |
returned: success |
| 411 |
type: list |
| 412 |
elements: str |
| 413 |
sample: ["production", "app"] |
| 414 |
version_added: 10.1.0 |
| 415 |
tags_modified_on: |
| 416 |
description: When the record tags were last modified. Omitted if there are no tags. |
| 417 |
returned: success |
| 418 |
type: str |
| 419 |
sample: "2025-01-01T05:20:00.12345Z" |
| 420 |
version_added: 10.1.0 |
| 421 |
ttl: |
| 422 |
description: The time-to-live for the record. |
| 423 |
returned: success |
| 424 |
type: int |
| 425 |
sample: 300 |
| 426 |
type: |
| 427 |
description: The record type. |
| 428 |
returned: success |
| 429 |
type: str |
| 430 |
sample: A |
| 431 |
zone_id: |
| 432 |
description: The ID of the zone containing the record. |
| 433 |
returned: success |
| 434 |
type: str |
| 435 |
sample: abcede0bf9f0066f94029d2e6b73856a |
| 436 |
zone_name: |
| 437 |
description: The name of the zone containing the record. |
| 438 |
returned: success |
| 439 |
type: str |
| 440 |
sample: sample.com |
| 441 |
""" |
| 442 |
|
| 443 |
import json |
| 444 |
from urllib.parse import urlencode |
| 445 |
|
| 446 |
from ansible.module_utils.basic import AnsibleModule, env_fallback |
| 447 |
from ansible.module_utils.common.text.converters import to_text |
| 448 |
from ansible.module_utils.urls import fetch_url |
| 449 |
|
| 450 |
|
| 451 |
def lowercase_string(param): |
| 452 |
return param.lower() if isinstance(param, str) else param |
| 453 |
|
| 454 |
|
| 455 |
def join_str(sep, *args): |
| 456 |
return sep.join([str(arg) for arg in args]) |
| 457 |
|
| 458 |
|
| 459 |
class CloudflareAPI: |
| 460 |
cf_api_endpoint = "https://api.cloudflare.com/client/v4" |
| 461 |
changed = False |
| 462 |
|
| 463 |
def __init__(self, module): |
| 464 |
self.module = module |
| 465 |
self.api_token = module.params["api_token"] |
| 466 |
self.account_api_key = module.params["account_api_key"] |
| 467 |
self.account_email = module.params["account_email"] |
| 468 |
self.algorithm = module.params["algorithm"] |
| 469 |
self.cert_usage = module.params["cert_usage"] |
| 470 |
self.comment = module.params["comment"] |
| 471 |
self.hash_type = module.params["hash_type"] |
| 472 |
self.flag = module.params["flag"] |
| 473 |
self.tag = module.params["tag"] |
| 474 |
self.tags = module.params["tags"] |
| 475 |
self.key_tag = module.params["key_tag"] |
| 476 |
self.port = module.params["port"] |
| 477 |
self.priority = module.params["priority"] |
| 478 |
self.proto = lowercase_string(module.params["proto"]) |
| 479 |
self.proxied = module.params["proxied"] |
| 480 |
self.selector = module.params["selector"] |
| 481 |
self.record = lowercase_string(module.params["record"]) |
| 482 |
self.service = lowercase_string(module.params["service"]) |
| 483 |
self.is_solo = module.params["solo"] |
| 484 |
self.state = module.params["state"] |
| 485 |
self.timeout = module.params["timeout"] |
| 486 |
self.ttl = module.params["ttl"] |
| 487 |
self.type = module.params["type"] |
| 488 |
self.value = module.params["value"] |
| 489 |
self.weight = module.params["weight"] |
| 490 |
self.zone = lowercase_string(module.params["zone"]) |
| 491 |
|
| 492 |
if self.record == "@": |
| 493 |
self.record = self.zone |
| 494 |
|
| 495 |
if (self.type in ["CNAME", "NS", "MX", "SRV"]) and (self.value is not None): |
| 496 |
self.value = self.value.rstrip(".").lower() |
| 497 |
|
| 498 |
if (self.type == "AAAA") and (self.value is not None): |
| 499 |
self.value = self.value.lower() |
| 500 |
|
| 501 |
if self.type == "SRV": |
| 502 |
if (self.proto is not None) and (not self.proto.startswith("_")): |
| 503 |
self.proto = f"_{self.proto}" |
| 504 |
if (self.service is not None) and (not self.service.startswith("_")): |
| 505 |
self.service = f"_{self.service}" |
| 506 |
|
| 507 |
if self.type == "TLSA": |
| 508 |
if (self.proto is not None) and (not self.proto.startswith("_")): |
| 509 |
self.proto = f"_{self.proto}" |
| 510 |
if self.port is not None: |
| 511 |
self.port = f"_{self.port}" |
| 512 |
|
| 513 |
if not self.record.endswith(self.zone): |
| 514 |
self.record = join_str(".", self.record, self.zone) |
| 515 |
|
| 516 |
if self.type == "DS": |
| 517 |
if self.record == self.zone: |
| 518 |
self.module.fail_json(msg="DS records only apply to subdomains.") |
| 519 |
|
| 520 |
def _cf_simple_api_call(self, api_call, method="GET", payload=None): |
| 521 |
if self.api_token: |
| 522 |
headers = { |
| 523 |
"Authorization": f"Bearer {self.api_token}", |
| 524 |
"Content-Type": "application/json", |
| 525 |
} |
| 526 |
else: |
| 527 |
headers = { |
| 528 |
"X-Auth-Email": self.account_email, |
| 529 |
"X-Auth-Key": self.account_api_key, |
| 530 |
"Content-Type": "application/json", |
| 531 |
} |
| 532 |
data = None |
| 533 |
if payload: |
| 534 |
try: |
| 535 |
data = json.dumps(payload) |
| 536 |
except Exception as e: |
| 537 |
self.module.fail_json(msg=f"Failed to encode payload as JSON: {e} ") |
| 538 |
|
| 539 |
resp, info = fetch_url( |
| 540 |
self.module, |
| 541 |
self.cf_api_endpoint + api_call, |
| 542 |
headers=headers, |
| 543 |
data=data, |
| 544 |
method=method, |
| 545 |
timeout=self.timeout, |
| 546 |
) |
| 547 |
|
| 548 |
if info["status"] not in [200, 304, 400, 401, 403, 429, 405, 415]: |
| 549 |
self.module.fail_json( |
| 550 |
msg=f"Failed API call {api_call}; got unexpected HTTP code {info['status']}: {info.get('msg')}" |
| 551 |
) |
| 552 |
|
| 553 |
error_msg = "" |
| 554 |
if info["status"] == 401: |
| 555 |
# Unauthorized |
| 556 |
error_msg = ( |
| 557 |
f"API user does not have permission; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 558 |
) |
| 559 |
elif info["status"] == 403: |
| 560 |
# Forbidden |
| 561 |
error_msg = f"API request not authenticated; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 562 |
elif info["status"] == 429: |
| 563 |
# Too many requests |
| 564 |
error_msg = f"API client is rate limited; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 565 |
elif info["status"] == 405: |
| 566 |
# Method not allowed |
| 567 |
error_msg = ( |
| 568 |
f"API incorrect HTTP method provided; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 569 |
) |
| 570 |
elif info["status"] == 415: |
| 571 |
# Unsupported Media Type |
| 572 |
error_msg = f"API request is not valid JSON; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 573 |
elif info["status"] == 400: |
| 574 |
# Bad Request |
| 575 |
error_msg = f"API bad request; Status: {info['status']}; Method: {method}: Call: {api_call}" |
| 576 |
|
| 577 |
result = None |
| 578 |
try: |
| 579 |
content = resp.read() |
| 580 |
except AttributeError: |
| 581 |
content = None |
| 582 |
|
| 583 |
if not content: |
| 584 |
if info["body"]: |
| 585 |
content = info["body"] |
| 586 |
else: |
| 587 |
error_msg += "; The API response was empty" |
| 588 |
|
| 589 |
if content: |
| 590 |
try: |
| 591 |
result = json.loads(to_text(content, errors="surrogate_or_strict")) |
| 592 |
except getattr(json, "JSONDecodeError", ValueError) as e: |
| 593 |
error_msg += f"; Failed to parse API response with error {e}: {content}" |
| 594 |
|
| 595 |
# Without a valid/parsed JSON response no more error processing can be done |
| 596 |
if result is None: |
| 597 |
self.module.fail_json(msg=error_msg) |
| 598 |
|
| 599 |
if "success" not in result: |
| 600 |
error_msg += f"; Unexpected error details: {result.get('error')}" |
| 601 |
self.module.fail_json(msg=error_msg) |
| 602 |
|
| 603 |
if not result["success"]: |
| 604 |
error_msg += "; Error details: " |
| 605 |
for error in result["errors"]: |
| 606 |
error_msg += f"code: {error['code']}, error: {error['message']}; " |
| 607 |
if "error_chain" in error: |
| 608 |
for chain_error in error["error_chain"]: |
| 609 |
error_msg += f"code: {chain_error['code']}, error: {chain_error['message']}; " |
| 610 |
self.module.fail_json(msg=error_msg) |
| 611 |
|
| 612 |
return result, info["status"] |
| 613 |
|
| 614 |
def _cf_api_call(self, api_call, method="GET", payload=None): |
| 615 |
result, status = self._cf_simple_api_call(api_call, method, payload) |
| 616 |
|
| 617 |
data = result["result"] |
| 618 |
|
| 619 |
if "result_info" in result: |
| 620 |
pagination = result["result_info"] |
| 621 |
if pagination["total_pages"] > 1: |
| 622 |
next_page = int(pagination["page"]) + 1 |
| 623 |
parameters = [f"page={next_page}"] |
| 624 |
# strip "page" parameter from call parameters (if there are any) |
| 625 |
if "?" in api_call: |
| 626 |
raw_api_call, query = api_call.split("?", 1) |
| 627 |
parameters += [param for param in query.split("&") if not param.startswith("page")] |
| 628 |
else: |
| 629 |
raw_api_call = api_call |
| 630 |
while next_page <= pagination["total_pages"]: |
| 631 |
raw_api_call += f"?{'&'.join(parameters)}" |
| 632 |
result, status = self._cf_simple_api_call(raw_api_call, method, payload) |
| 633 |
data += result["result"] |
| 634 |
next_page += 1 |
| 635 |
|
| 636 |
return data, status |
| 637 |
|
| 638 |
def _get_zone_id(self, zone=None): |
| 639 |
if not zone: |
| 640 |
zone = self.zone |
| 641 |
|
| 642 |
zones = self.get_zones(zone) |
| 643 |
if len(zones) > 1: |
| 644 |
self.module.fail_json(msg=f"More than one zone matches {zone}") |
| 645 |
|
| 646 |
if len(zones) < 1: |
| 647 |
self.module.fail_json(msg=f"No zone found with name {zone}") |
| 648 |
|
| 649 |
return zones[0]["id"] |
| 650 |
|
| 651 |
def get_zones(self, name=None): |
| 652 |
if not name: |
| 653 |
name = self.zone |
| 654 |
param = "" |
| 655 |
if name: |
| 656 |
param = f"?{urlencode({'name': name})}" |
| 657 |
zones, status = self._cf_api_call(f"/zones{param}") |
| 658 |
return zones |
| 659 |
|
| 660 |
def get_dns_records(self, zone_name=None, type=None, record=None, value=""): |
| 661 |
if not zone_name: |
| 662 |
zone_name = self.zone |
| 663 |
if not type: |
| 664 |
type = self.type |
| 665 |
if not record: |
| 666 |
record = self.record |
| 667 |
# necessary because None as value means to override user |
| 668 |
# set module value |
| 669 |
if (not value) and (value is not None): |
| 670 |
value = self.value |
| 671 |
|
| 672 |
zone_id = self._get_zone_id() |
| 673 |
api_call = f"/zones/{zone_id}/dns_records" |
| 674 |
query = {} |
| 675 |
if type: |
| 676 |
query["type"] = type |
| 677 |
if record: |
| 678 |
query["name"] = record |
| 679 |
if value: |
| 680 |
query["content"] = value |
| 681 |
if query: |
| 682 |
api_call += f"?{urlencode(query)}" |
| 683 |
|
| 684 |
records, status = self._cf_api_call(api_call) |
| 685 |
return records |
| 686 |
|
| 687 |
def delete_dns_records(self, solo): |
| 688 |
records = [] |
| 689 |
content = self.value |
| 690 |
search_record = self.record |
| 691 |
if self.type == "SRV": |
| 692 |
if not (self.value is None or self.value == ""): |
| 693 |
content = join_str("\t", self.weight, self.port, self.value) |
| 694 |
search_record = join_str(".", self.service, self.proto, self.record) |
| 695 |
elif self.type == "DS": |
| 696 |
if not (self.value is None or self.value == ""): |
| 697 |
content = join_str("\t", self.key_tag, self.algorithm, self.hash_type, self.value) |
| 698 |
elif self.type == "SSHFP": |
| 699 |
if not (self.value is None or self.value == ""): |
| 700 |
content = join_str(" ", self.algorithm, self.hash_type, self.value.upper()) |
| 701 |
elif self.type == "TLSA": |
| 702 |
if not (self.value is None or self.value == ""): |
| 703 |
content = join_str("\t", self.cert_usage, self.selector, self.hash_type, self.value) |
| 704 |
search_record = join_str(".", self.port, self.proto, self.record) |
| 705 |
if solo: |
| 706 |
search_value = None |
| 707 |
else: |
| 708 |
search_value = content |
| 709 |
|
| 710 |
zone_id = self._get_zone_id(self.zone) |
| 711 |
records = self.get_dns_records(self.zone, self.type, search_record, search_value) |
| 712 |
|
| 713 |
for rr in records: |
| 714 |
if solo: |
| 715 |
if not ((rr["type"] == self.type) and (rr["name"] == search_record) and (rr["content"] == content)): |
| 716 |
self.changed = True |
| 717 |
if not self.module.check_mode: |
| 718 |
result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records/{rr['id']}", "DELETE") |
| 719 |
else: |
| 720 |
self.changed = True |
| 721 |
if not self.module.check_mode: |
| 722 |
result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records/{rr['id']}", "DELETE") |
| 723 |
return self.changed |
| 724 |
|
| 725 |
def ensure_dns_record(self): |
| 726 |
search_value = self.value |
| 727 |
search_record = self.record |
| 728 |
new_record = None |
| 729 |
|
| 730 |
if self.type in ["A", "AAAA", "CNAME", "TXT", "MX", "NS", "PTR"]: |
| 731 |
if not self.value: |
| 732 |
self.module.fail_json(msg="You must provide a non-empty value to create this record type") |
| 733 |
|
| 734 |
# there can only be one CNAME per record |
| 735 |
# ignoring the value when searching for existing |
| 736 |
# CNAME records allows us to update the value if it |
| 737 |
# changes |
| 738 |
if self.type == "CNAME": |
| 739 |
search_value = None |
| 740 |
|
| 741 |
new_record = {"type": self.type, "name": self.record, "content": self.value, "ttl": self.ttl} |
| 742 |
|
| 743 |
if self.type in ["A", "AAAA", "CNAME"]: |
| 744 |
new_record["proxied"] = self.proxied |
| 745 |
|
| 746 |
if self.type == "MX": |
| 747 |
for attr in [self.priority, self.value]: |
| 748 |
if (attr is None) or (attr == ""): |
| 749 |
self.module.fail_json(msg="You must provide priority and a value to create this record type") |
| 750 |
new_record = { |
| 751 |
"type": self.type, |
| 752 |
"name": self.record, |
| 753 |
"content": self.value, |
| 754 |
"priority": self.priority, |
| 755 |
"ttl": self.ttl, |
| 756 |
} |
| 757 |
|
| 758 |
if self.type == "SRV": |
| 759 |
for attr in [self.port, self.priority, self.proto, self.service, self.weight, self.value]: |
| 760 |
if (attr is None) or (attr == ""): |
| 761 |
self.module.fail_json( |
| 762 |
msg="You must provide port, priority, proto, service, weight and a value to create this record type" |
| 763 |
) |
| 764 |
srv_data = { |
| 765 |
"target": self.value, |
| 766 |
"port": self.port, |
| 767 |
"weight": self.weight, |
| 768 |
"priority": self.priority, |
| 769 |
} |
| 770 |
|
| 771 |
new_record = { |
| 772 |
"type": self.type, |
| 773 |
"name": join_str(".", self.service, self.proto, self.record), |
| 774 |
"ttl": self.ttl, |
| 775 |
"data": srv_data, |
| 776 |
} |
| 777 |
search_value = join_str("\t", self.weight, self.port, self.value) |
| 778 |
search_record = join_str(".", self.service, self.proto, self.record) |
| 779 |
|
| 780 |
if self.type == "DS": |
| 781 |
for attr in [self.key_tag, self.algorithm, self.hash_type, self.value]: |
| 782 |
if (attr is None) or (attr == ""): |
| 783 |
self.module.fail_json( |
| 784 |
msg="You must provide key_tag, algorithm, hash_type and a value to create this record type" |
| 785 |
) |
| 786 |
ds_data = { |
| 787 |
"key_tag": self.key_tag, |
| 788 |
"algorithm": self.algorithm, |
| 789 |
"digest_type": self.hash_type, |
| 790 |
"digest": self.value, |
| 791 |
} |
| 792 |
new_record = { |
| 793 |
"type": self.type, |
| 794 |
"name": self.record, |
| 795 |
"data": ds_data, |
| 796 |
"ttl": self.ttl, |
| 797 |
} |
| 798 |
search_value = join_str("\t", self.key_tag, self.algorithm, self.hash_type, self.value) |
| 799 |
|
| 800 |
if self.type == "SSHFP": |
| 801 |
for attr in [self.algorithm, self.hash_type, self.value]: |
| 802 |
if (attr is None) or (attr == ""): |
| 803 |
self.module.fail_json( |
| 804 |
msg="You must provide algorithm, hash_type and a value to create this record type" |
| 805 |
) |
| 806 |
sshfp_data = { |
| 807 |
"fingerprint": self.value.upper(), |
| 808 |
"type": self.hash_type, |
| 809 |
"algorithm": self.algorithm, |
| 810 |
} |
| 811 |
new_record = { |
| 812 |
"type": self.type, |
| 813 |
"name": self.record, |
| 814 |
"data": sshfp_data, |
| 815 |
"ttl": self.ttl, |
| 816 |
} |
| 817 |
search_value = join_str(" ", self.algorithm, self.hash_type, self.value) |
| 818 |
|
| 819 |
if self.type == "TLSA": |
| 820 |
for attr in [self.port, self.proto, self.cert_usage, self.selector, self.hash_type, self.value]: |
| 821 |
if (attr is None) or (attr == ""): |
| 822 |
self.module.fail_json( |
| 823 |
msg="You must provide port, proto, cert_usage, selector, hash_type and a value to create this record type" |
| 824 |
) |
| 825 |
search_record = join_str(".", self.port, self.proto, self.record) |
| 826 |
tlsa_data = { |
| 827 |
"usage": self.cert_usage, |
| 828 |
"selector": self.selector, |
| 829 |
"matching_type": self.hash_type, |
| 830 |
"certificate": self.value, |
| 831 |
} |
| 832 |
new_record = { |
| 833 |
"type": self.type, |
| 834 |
"name": search_record, |
| 835 |
"data": tlsa_data, |
| 836 |
"ttl": self.ttl, |
| 837 |
} |
| 838 |
search_value = join_str("\t", self.cert_usage, self.selector, self.hash_type, self.value) |
| 839 |
|
| 840 |
if self.type == "CAA": |
| 841 |
for attr in [self.flag, self.tag, self.value]: |
| 842 |
if attr == "": |
| 843 |
self.module.fail_json(msg="You must provide flag, tag and a value to create this record type") |
| 844 |
caa_data = { |
| 845 |
"flags": self.flag, |
| 846 |
"tag": self.tag, |
| 847 |
"value": self.value, |
| 848 |
} |
| 849 |
new_record = { |
| 850 |
"type": self.type, |
| 851 |
"name": self.record, |
| 852 |
"data": caa_data, |
| 853 |
"ttl": self.ttl, |
| 854 |
} |
| 855 |
search_value = None |
| 856 |
|
| 857 |
new_record["comment"] = self.comment or None |
| 858 |
new_record["tags"] = self.tags or [] |
| 859 |
|
| 860 |
zone_id = self._get_zone_id(self.zone) |
| 861 |
records = self.get_dns_records(self.zone, self.type, search_record, search_value) |
| 862 |
# in theory this should be impossible as cloudflare does not allow |
| 863 |
# the creation of duplicate records but lets cover it anyways |
| 864 |
if len(records) > 1: |
| 865 |
# As Cloudflare API cannot filter record containing quotes |
| 866 |
# CAA records must be compared locally |
| 867 |
if self.type == "CAA": |
| 868 |
for rr in records: |
| 869 |
if ( |
| 870 |
rr["data"]["flags"] == caa_data["flags"] |
| 871 |
and rr["data"]["tag"] == caa_data["tag"] |
| 872 |
and rr["data"]["value"] == caa_data["value"] |
| 873 |
): |
| 874 |
return rr, self.changed |
| 875 |
else: |
| 876 |
self.module.fail_json( |
| 877 |
msg="More than one record already exists for the given attributes. That should be impossible, please open an issue!" |
| 878 |
) |
| 879 |
# record already exists, check if it must be updated |
| 880 |
if len(records) == 1: |
| 881 |
cur_record = records[0] |
| 882 |
do_update = False |
| 883 |
if (self.ttl is not None) and (cur_record["ttl"] != self.ttl): |
| 884 |
do_update = True |
| 885 |
if (self.priority is not None) and ("priority" in cur_record) and (cur_record["priority"] != self.priority): |
| 886 |
do_update = True |
| 887 |
if ("proxied" in new_record) and ("proxied" in cur_record) and (cur_record["proxied"] != self.proxied): |
| 888 |
do_update = True |
| 889 |
if ("data" in new_record) and ("data" in cur_record): |
| 890 |
if cur_record["data"] != new_record["data"]: |
| 891 |
do_update = True |
| 892 |
if (self.type == "CNAME") and (cur_record["content"] != new_record["content"]): |
| 893 |
do_update = True |
| 894 |
if cur_record["comment"] != new_record["comment"]: |
| 895 |
do_update = True |
| 896 |
if sorted(cur_record["tags"]) != sorted(new_record["tags"]): |
| 897 |
do_update = True |
| 898 |
if do_update: |
| 899 |
if self.module.check_mode: |
| 900 |
result = new_record |
| 901 |
else: |
| 902 |
result, info = self._cf_api_call( |
| 903 |
f"/zones/{zone_id}/dns_records/{records[0]['id']}", "PUT", new_record |
| 904 |
) |
| 905 |
self.changed = True |
| 906 |
return result, self.changed |
| 907 |
else: |
| 908 |
return records, self.changed |
| 909 |
if self.module.check_mode: |
| 910 |
result = new_record |
| 911 |
else: |
| 912 |
result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records", "POST", new_record) |
| 913 |
self.changed = True |
| 914 |
return result, self.changed |
| 915 |
|
| 916 |
|
| 917 |
def main(): |
| 918 |
module = AnsibleModule( |
| 919 |
argument_spec=dict( |
| 920 |
api_token=dict(type="str", no_log=True, fallback=(env_fallback, ["CLOUDFLARE_TOKEN"])), |
| 921 |
account_api_key=dict(type="str", no_log=True, aliases=["account_api_token"]), |
| 922 |
account_email=dict(type="str"), |
| 923 |
algorithm=dict(type="int"), |
| 924 |
cert_usage=dict(type="int", choices=[0, 1, 2, 3]), |
| 925 |
comment=dict(type="str"), |
| 926 |
hash_type=dict(type="int", choices=[1, 2]), |
| 927 |
key_tag=dict(type="int", no_log=False), |
| 928 |
port=dict(type="int"), |
| 929 |
flag=dict(type="int", choices=[0, 1, 128]), |
| 930 |
tag=dict(type="str", choices=["issue", "issuewild", "iodef"]), |
| 931 |
tags=dict(type="list", elements="str"), |
| 932 |
priority=dict(type="int", default=1), |
| 933 |
proto=dict(type="str"), |
| 934 |
proxied=dict(type="bool", default=False), |
| 935 |
record=dict(type="str", default="@", aliases=["name"]), |
| 936 |
selector=dict(type="int", choices=[0, 1]), |
| 937 |
service=dict(type="str"), |
| 938 |
solo=dict(type="bool"), |
| 939 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 940 |
timeout=dict(type="int", default=30), |
| 941 |
ttl=dict(type="int", default=1), |
| 942 |
type=dict( |
| 943 |
type="str", |
| 944 |
choices=["A", "AAAA", "CNAME", "DS", "MX", "NS", "SRV", "SSHFP", "TLSA", "CAA", "TXT", "PTR"], |
| 945 |
), |
| 946 |
value=dict(type="str", aliases=["content"]), |
| 947 |
weight=dict(type="int", default=1), |
| 948 |
zone=dict(type="str", required=True, aliases=["domain"]), |
| 949 |
), |
| 950 |
supports_check_mode=True, |
| 951 |
required_if=[ |
| 952 |
("state", "present", ["record", "type", "value"]), |
| 953 |
("state", "absent", ["record"]), |
| 954 |
("type", "SRV", ["proto", "service"]), |
| 955 |
("type", "TLSA", ["proto", "port"]), |
| 956 |
("type", "CAA", ["flag", "tag"]), |
| 957 |
], |
| 958 |
required_together=[ |
| 959 |
("account_api_key", "account_email"), |
| 960 |
], |
| 961 |
required_one_of=[ |
| 962 |
["api_token", "account_api_key"], |
| 963 |
], |
| 964 |
) |
| 965 |
|
| 966 |
if module.params["type"] == "SRV": |
| 967 |
if not ( |
| 968 |
( |
| 969 |
module.params["weight"] is not None |
| 970 |
and module.params["port"] is not None |
| 971 |
and not (module.params["value"] is None or module.params["value"] == "") |
| 972 |
) |
| 973 |
or ( |
| 974 |
module.params["weight"] is None |
| 975 |
and module.params["port"] is None |
| 976 |
and (module.params["value"] is None or module.params["value"] == "") |
| 977 |
) |
| 978 |
): |
| 979 |
module.fail_json( |
| 980 |
msg="For SRV records the params weight, port and value all need to be defined, or not at all." |
| 981 |
) |
| 982 |
|
| 983 |
if module.params["type"] == "SSHFP": |
| 984 |
if not ( |
| 985 |
( |
| 986 |
module.params["algorithm"] is not None |
| 987 |
and module.params["hash_type"] is not None |
| 988 |
and not (module.params["value"] is None or module.params["value"] == "") |
| 989 |
) |
| 990 |
or ( |
| 991 |
module.params["algorithm"] is None |
| 992 |
and module.params["hash_type"] is None |
| 993 |
and (module.params["value"] is None or module.params["value"] == "") |
| 994 |
) |
| 995 |
): |
| 996 |
module.fail_json( |
| 997 |
msg="For SSHFP records the params algorithm, hash_type and value all need to be defined, or not at all." |
| 998 |
) |
| 999 |
|
| 1000 |
if module.params["type"] == "TLSA": |
| 1001 |
if not ( |
| 1002 |
( |
| 1003 |
module.params["cert_usage"] is not None |
| 1004 |
and module.params["selector"] is not None |
| 1005 |
and module.params["hash_type"] is not None |
| 1006 |
and not (module.params["value"] is None or module.params["value"] == "") |
| 1007 |
) |
| 1008 |
or ( |
| 1009 |
module.params["cert_usage"] is None |
| 1010 |
and module.params["selector"] is None |
| 1011 |
and module.params["hash_type"] is None |
| 1012 |
and (module.params["value"] is None or module.params["value"] == "") |
| 1013 |
) |
| 1014 |
): |
| 1015 |
module.fail_json( |
| 1016 |
msg="For TLSA records the params cert_usage, selector, hash_type and value all need to be defined, or not at all." |
| 1017 |
) |
| 1018 |
|
| 1019 |
if module.params["type"] == "CAA": |
| 1020 |
if not ( |
| 1021 |
( |
| 1022 |
module.params["flag"] is not None |
| 1023 |
and module.params["tag"] is not None |
| 1024 |
and not (module.params["value"] is None or module.params["value"] == "") |
| 1025 |
) |
| 1026 |
or ( |
| 1027 |
module.params["flag"] is None |
| 1028 |
and module.params["tag"] is None |
| 1029 |
and (module.params["value"] is None or module.params["value"] == "") |
| 1030 |
) |
| 1031 |
): |
| 1032 |
module.fail_json( |
| 1033 |
msg="For CAA records the params flag, tag and value all need to be defined, or not at all." |
| 1034 |
) |
| 1035 |
|
| 1036 |
if module.params["type"] == "DS": |
| 1037 |
if not ( |
| 1038 |
( |
| 1039 |
module.params["key_tag"] is not None |
| 1040 |
and module.params["algorithm"] is not None |
| 1041 |
and module.params["hash_type"] is not None |
| 1042 |
and not (module.params["value"] is None or module.params["value"] == "") |
| 1043 |
) |
| 1044 |
or ( |
| 1045 |
module.params["key_tag"] is None |
| 1046 |
and module.params["algorithm"] is None |
| 1047 |
and module.params["hash_type"] is None |
| 1048 |
and (module.params["value"] is None or module.params["value"] == "") |
| 1049 |
) |
| 1050 |
): |
| 1051 |
module.fail_json( |
| 1052 |
msg="For DS records the params key_tag, algorithm, hash_type and value all need to be defined, or not at all." |
| 1053 |
) |
| 1054 |
|
| 1055 |
changed = False |
| 1056 |
cf_api = CloudflareAPI(module) |
| 1057 |
|
| 1058 |
# sanity checks |
| 1059 |
if cf_api.is_solo and cf_api.state == "absent": |
| 1060 |
module.fail_json(msg="solo=true can only be used with state=present") |
| 1061 |
|
| 1062 |
# perform add, delete or update (only the TTL can be updated) of one or |
| 1063 |
# more records |
| 1064 |
if cf_api.state == "present": |
| 1065 |
# delete all records matching record name + type |
| 1066 |
if cf_api.is_solo: |
| 1067 |
changed = cf_api.delete_dns_records(solo=cf_api.is_solo) |
| 1068 |
result, changed = cf_api.ensure_dns_record() |
| 1069 |
if isinstance(result, list): |
| 1070 |
module.exit_json(changed=changed, result={"record": result[0]}) |
| 1071 |
|
| 1072 |
module.exit_json(changed=changed, result={"record": result}) |
| 1073 |
else: |
| 1074 |
# force solo to False, just to be sure |
| 1075 |
changed = cf_api.delete_dns_records(solo=False) |
| 1076 |
module.exit_json(changed=changed) |
| 1077 |
|
| 1078 |
|
| 1079 |
if __name__ == "__main__": |
| 1080 |
main() |