Created
August 15, 2014 19:54
-
-
Save jtopjian/bb9f9a41a942a59e3c01 to your computer and use it in GitHub Desktop.
Ruby script to update or create DNS A record in Rackspace DNS service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'json' | |
| username = ENV['OS_USERNAME'] | |
| tenant = ENV['OS_TENANT_NAME'] | |
| password = ENV['OS_PASSWORD'] | |
| # Get the fqdn of the server | |
| fqdn = `facter fqdn`.strip | |
| puts fqdn | |
| # Get the IP address of eth0 | |
| ip_address = `facter ipaddress_eth0`.strip | |
| puts ip_address | |
| # Get the domain name | |
| domain = fqdn.split('.')[-2..-1].join('.') | |
| puts domain | |
| # Get an auth token | |
| token = `curl -s -I -H "X-Auth-Key: #{password}" -H "X-Auth-User: #{username}" https://auth.api.rackspacecloud.com/v1.0 | grep ^X-Auth-Token | cut -d: -f2`.strip | |
| # Get the records for domain | |
| domains = JSON.parse(`curl -s -H "X-Auth-Token: #{token}" https://dns.api.rackspacecloud.com/v1.0/#{tenant}/domains`) | |
| domain_id = nil | |
| domains['domains'].each do |d| | |
| if d['name'] == domain | |
| domain_id = d['id'] | |
| end | |
| end | |
| # Get the records for the domain | |
| records = JSON.parse(`curl -s -H "X-Auth-Token: #{token}" https://dns.api.rackspacecloud.com/v1.0/#{tenant}/domains/#{domain_id}`) | |
| found = nil | |
| records['recordsList']['records'].each do |r| | |
| if r['name'] == fqdn | |
| # Record found | |
| found = r['id'] | |
| end | |
| end | |
| if found | |
| data = { :name => fqdn, :data => ip_address } | |
| data = data.to_json | |
| result = `curl -D - -X PUT -d '#{data}' -H "Content-Type: application/json" -H "X-Auth-Token: #{token}" https://dns.api.rackspacecloud.com/v1.0/#{tenant}/domains/#{domain_id}/records/#{found}` | |
| else | |
| data = { :records => [ { :name => fqdn, :data => ip_address, :type => 'A' } ] } | |
| data = data.to_json | |
| result = `curl -D - -X POST -d '#{data}' -H "Content-Type: application/json" -H "X-Auth-Token: #{token}" https://dns.api.rackspacecloud.com/v1.0/#{tenant}/domains/#{domain_id}/records` | |
| end | |
| puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment