update-route53.sh 2.0 KB

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