update-route53.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/bin/bash
  2. # More advanced options below
  3. # The Time-To-Live of this recordset
  4. TTL=300
  5. # Change this if you want
  6. COMMENT="Auto updating @ `date`"
  7. # Change to AAAA if using an IPv6 address
  8. TYPE="A"
  9. # Get the external IP address
  10. IP=`curl -ss http://ipv4.icanhazip.com/`
  11. function valid_ip()
  12. {
  13. local ip=$1
  14. local stat=1
  15. if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
  16. OIFS=$IFS
  17. IFS='.'
  18. ip=($ip)
  19. IFS=$OIFS
  20. [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
  21. && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
  22. stat=$?
  23. fi
  24. return $stat
  25. }
  26. DIR=/scratch/
  27. LOGFILE="$DIR/update-route53.log"
  28. IPFILE="$DIR/update-route53.ip"
  29. if ! valid_ip $IP; then
  30. echo "Invalid IP address: $IP" | tee -a "$LOGFILE"
  31. exit 1
  32. fi
  33. # Check if the IP has changed
  34. if [ ! -f "$IPFILE" ]
  35. then
  36. touch "$IPFILE"
  37. fi
  38. if grep -Fxq "$IP" "$IPFILE"; then
  39. # code if found
  40. echo "IP is still $IP. Exiting" | tee -a "$LOGFILE"
  41. exit 0
  42. else
  43. echo "IP has changed to $IP" | tee -a "$LOGFILE"
  44. # Fill a temp file with valid JSON
  45. TMPFILE=$(mktemp /tmp/temporary-file.XXXXXXXX)
  46. cat > ${TMPFILE} << EOF
  47. {
  48. "Comment":"$COMMENT",
  49. "Changes":[
  50. {
  51. "Action":"UPSERT",
  52. "ResourceRecordSet":{
  53. "ResourceRecords":[
  54. {
  55. "Value":"$IP"
  56. }
  57. ],
  58. "Name":"$RECORDSET",
  59. "Type":"$TYPE",
  60. "TTL":$TTL
  61. }
  62. }
  63. ]
  64. }
  65. EOF
  66. # Update the Hosted Zone record
  67. aws route53 change-resource-record-sets \
  68. --hosted-zone-id $ZONEID \
  69. --change-batch file://"$TMPFILE" | tee -a "$LOGFILE"
  70. echo "" | tee -a "$LOGFILE"
  71. # Clean up
  72. rm $TMPFILE
  73. fi
  74. # All Done - cache the IP address for next time
  75. echo "$IP" > "$IPFILE"