Skip to content

Instantly share code, notes, and snippets.

@marcusramberg
Created October 5, 2014 23:18
Show Gist options
  • Save marcusramberg/1ba1ecdc8fe2a3870602 to your computer and use it in GitHub Desktop.
Save marcusramberg/1ba1ecdc8fe2a3870602 to your computer and use it in GitHub Desktop.
Ansible cloudflare module
#!/usr/bin/env perl
# WANT_JSON
use strict;
#use warnings;
use Mojo::Cloudflare;
use Mojo::JSON;
use Mojo::Util qw/slurp/;
my $json = Mojo::JSON->new;
my $args = $json->decode(slurp($ARGV[0]));
for (qw/email api_key zone name/) {
fail("$_ is a required argument") unless exists $args->{$_};
}
my $cf = Mojo::Cloudflare->new(
email => $args->{email},
key => $args->{api_key},
zone => $args->{zone}
);
my $current;
my $changed = 0;
for my $record ($cf->records->all) {
if ($record->name eq ($args->{name} . '.' . $args->{zone})) {
if ($args->{state} && $args->{state} eq 'absent') {
$record->delete();
$changed = 1;
}
elsif ($record->type eq $args->{type}) {
$current = $record;
last;
}
# Matches an exclusive type, but not the one we want
elsif ($record->type =~ m/^(cname|a|aaaa)$/i) {
$record->delete();
}
}
}
if (!$changed && !$args->{state} || $args->{state} ne 'absent' ) {
for (qw/email api_key zone name/) {
fail("$_ is a required argument") unless exists $args->{$_};
}
if (!$current) {
$current = $cf->record($args);
}
else {
foreach my $t (qw/type content ttl priority service_mode/) {
if (exists $args->{$t} && $args->{$t} ne $current->$t) {
$current->$t($args->{$t});
$changed = 1;
}
}
}
eval { $current->save(); };
fail("$@ for " . $current->id) if $@; #$json->encode($current->data)) if $@;
}
print $json->encode({changed => \$changed, record => $current ? $current->id : 'none'});
exit 0;
sub fail {
my $msg = shift;
print $json->encode({failed => 1, message => $msg});
exit 1;
}
@norbu09
Copy link

norbu09 commented Oct 13, 2014

L:29 will cause you problems if you want to update the apex domain.

@marcusramberg
Copy link
Author

@norbu09 That is true. Will try to address that in an update soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment