LoginSignup
6
5

More than 5 years have passed since last update.

Global IPを監視してRoute53を更新する

Last updated at Posted at 2017-02-09

背景

自社開発サーバを建てたのは良かったのですが、実はOfficeのGlobal IPが固定されていないことがわかりました。これではやや面倒くさいのと、ISPさんに電話して固定IPの契約をすれば良い話なのですが、インフラのソフトウェア解決の文化を啓蒙したい想いもあって、とりいそぎRoute53を自動更新するShell ScriptをCronに登録しておこうというものです。

こんなShell Scriptを書いたのです

仕組みとしてはGlobal IPをgip.txtというテキストファイルに記録しておいて、今のGlobal IPと比較して更新があればaws-cliでRoute53のRecordの更新をするというものです。

ip_watch.sh
#!/usr/bin/env bash

gip=`curl inet-ip.info` # Global IPを取得
r53_hosted_id="********" # AWS Route53のHosted ID
r53_target_domain="my.host.domain.com" # 更新するドメイン(今回はA record)
gipfile="/path/to/gip.txt" # gip.txt出力先
outfile="/path/to/update.json" # JSON出力先
env_gip=`cat $gipfile` # 旧Global IP

# 以前環境変数に登録していた旧Global IPと現Global IPを比較
if [ "${gip}" != "${env_gip}" ]; then
    # aws-cli route53で渡すJSONファイル(update.json)を作成
    json="{\"Comment\" : \"\", \"Changes\" : [{\"Action\" : \"UPSERT\", \"ResourceRecordSet\" : {\"Name\" : \"${r53_target_domain}\", \"Type\" : \"A\", \"TTL\" : 300, \"ResourceRecords\" : [{\"Value\": \"${gip}\"}]}}]}"
    echo $json > $outfile
    # aws-cliでroute53のrecord set更新
    aws route53 change-resource-record-sets --hosted-zone-id $r53_hosted_id --change-batch file://$outfile
    # Slackにお知らせ。Incoming Webhook URLをご用意ください。
    curl -X POST --data-urlencode "payload={
        \"channel\": \"#infra\",
        \"username\": \"ip監視さん\",
        \"text\": \"updating global IP ${env_gip} -> ${gip}!!\", 
        \"icon_emoji\": \":elevennines:\"
    }" https://hooks.slack.com/services/******/*******/***************
    echo "${gip}" > $gipfile # Global IPをセット
fi

実行結果

コマンドライン上では以下の様になります。

[tokifuji@office ip_watch]$ ./ip_watch.sh 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    15  100    15    0     0     36      0 --:--:-- --:--:-- --:--:--    36
{
    "ChangeInfo": {
        "Status": "PENDING", 
        "Comment": "", 
        "SubmittedAt": "2017-01-30T12:22:21.799Z", 
        "Id": "/change/***********"
    }
}
[tokifuji@office ip_watch]$

その後のステータス確認は以下です。StatusがINSYNCになったらOKです。

[tokifuji@office ip_watch]$ aws route53 get-change --id /change/***********
{
    "ChangeInfo": {
        "Status": "INSYNC", 
        "SubmittedAt": "2017-01-30T12:22:21.799Z", 
        "Id": "/change/***********"
    }
}

Slackにはこんなメッセージが飛びます。

image

CRONTABに設定

自分は5分置きに設定してますが、お好みで…

[tokifuji@office ip_watch]$ crontab -l
*/5 * * * * /path/to/ip_watch.sh

これであなたも快適Route53ライフ(??)をエンジョイしてください。それではまた:raised_hand:

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5