Automated DNS Record Creation with AWS Route 53 and Bash Script
This is an useful script for automating the process of creating DNS records using the AWS Route 53 service.
First, there's a list of items in the format "name, domain, IP, hosted zone ID". Each item represents a DNS record to be created.
firewall,acme.com.br,10.1.1.1,00000000000000
gitlab,acme.com.br,10.1.1.163,00000000000000
hyoga,acme.com.br,10.1.1.17,00000000000000
ikki,acme.com.br,10.1.1.98,00000000000000
marin,acme.com.br,10.1.1.163,00000000000000
milo,acme.com.br,10.1.1.193,00000000000000
proxy,acme.com.br,10.1.1.82,00000000000000
saga,acme.com.br,10.1.1.6,00000000000000
seiya,tex.com.br,10.1.1.76,11111111111111
shaka,tex.com.br,10.1.1.2,11111111111111
shina,tex.com.br,10.1.1.4,11111111111111
shion,tex.com.br,10.1.1.9,11111111111111
shun,tex.com.br,10.1.1.94,11111111111111
shura,tex.com.br,10.1.1.8 ,11111111111111
storage,tex.com.br,10.1.1.5,11111111111111
wiki,tex.com.br,10.1.1.88,11111111111111
/tmp/list
Bash Script:
#!/bin/bash
for I in `cat /tmp/list`; do
aws route53 change-resource-record-sets \
--hosted-zone-id $(echo $I | cut -d ',' -f4) \
--change-batch '
{
"Comment": "Testing creating a record set"
,"Changes": [{
"Action" : "CREATE"
,"ResourceRecordSet" : {
"Name" : "'$(echo $I | cut -d ',' -f1).$(echo $I | cut -d ',' -f2)'"
,"Type" : "CNAME"
,"TTL" : 120
,"ResourceRecords" : [{
"Value" : "'$(echo $I | cut -d ',' -f3)'"
}]
}
}]
}
'
done
tmp/createRecord.sh
Let me break it down for you:
- Then, there's a Bash script starting with
#!/bin/bash
, indicating it's a Bash script. - Inside the script, there's a
for
loop iterating over each line of the file/tmp/list
. It's using backticks to execute thecat /tmp/list
command and iterate over its output. - For each line in the list, it's executing the AWS CLI command
aws route53 change-resource-record-sets
to create a DNS record. - The
aws route53 change-resource-record-sets
command is being supplied with parameters:--hosted-zone-id
: The hosted zone ID extracted from the input line.--change-batch
: A JSON string specifying the changes to be made. This JSON includes:- A comment.
- An array of changes, each containing:
- The action (in this case, "CREATE").
- Details of the resource record set to be created, including:
- Name: Constructed from the name and domain fields of the input line.
- Type: Always "CNAME" in this script.
- TTL: Time to Live for the DNS record.
- ResourceRecords: An array containing the IP address extracted from the input line.
- Inside the JSON, the values for name, type, TTL, and IP address are extracted from the input line using
cut
commands. - The script repeats this process for each line in the list, effectively creating a DNS record for each item in the list.
This script essentially automates the creation of DNS records based on the information provided in the list file.