-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate-dns.sh
63 lines (51 loc) · 1.36 KB
/
update-dns.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
#!/bin/bash
source /etc/environment
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}
# Fetch current IP address
IP=$(curl -s http://checkip.amazonaws.com/)
# Validate IP address
if [[ ! $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
log "Invalid IP address: $IP"
exit 1
fi
# Get current Route 53 record value
CURRENT_IP=$(aws route53 list-resource-record-sets --hosted-zone-id "$AWS_HOSTED_ZONE_ID" | \
jq -r '.ResourceRecordSets[] | select(.Name == "'"$AWS_RECORD_NAME"'.") | select(.Type == "'"A"'") | .ResourceRecords[0].Value')
log "Current IP from Route 53: $CURRENT_IP"
# Check if IP is different from Route 53
if [ "$IP" == "$CURRENT_IP" ]; then
log "IP has not changed, exiting."
exit 0
fi
log "IP has changed, updating records."
ROUTE53_PAYLOAD=$(cat << EOF
{
"Comment": "Updated from DDNS shell script",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "$AWS_RECORD_NAME",
"Type": "A",
"TTL": 300,
"ResourceRecords": [
{
"Value": "$IP"
}
]
}
}
]
}
EOF
)
# Update records
aws route53 change-resource-record-sets --hosted-zone-id "$AWS_HOSTED_ZONE_ID" --change-batch "$ROUTE53_PAYLOAD" >> /dev/null
if [ $? -eq 0 ]; then
log "DNS record updated successfully."
else
log "Failed to update DNS record."
exit 1
fi