pslaboが試したことの記録

はてなダイヤリーからはてなブログに引っ越してきました

この日記は現在実行中の減量記録を含む個人的なメモとして始めましたが、最近はコンピュータやガジェット、ハック、セキュリティネタのほうがメインになっております。

はてなダイヤリー時代はカテゴリ分けが適当だったのですが、これはそのうち直します。


AWS の IP アドレスを対話的な操作で抽出するスクリプト

AWS ではサービスが使用する IP アドレスが公開されていて、特定のサービスとの通信だけを通したい場合に、この情報を用いてフィルタリングする設定を作る際に利用できます。

docs.aws.amazon.com

そしてこのページでは抽出方法も示されていますが、なんとなく、ノリと勢いだけで対話的なUIで抽出できるスクリプトを書いてみました。

なお、実行の際は peco と jq が必要です。 対話的な操作に peco を使用しており、JSON データの操作には jq を用いています。

また出力結果には curl + jq で同じ結果を取得する際のコマンド実行例も含めています。後日に同じ条件で最新の情報を取得したい場合には、対話的な操作を行わなくても容易に抽出が行えるようにしています。

#!/bin/bash

interactive_helper=peco
aws_ip_address_url="https://ip-ranges.amazonaws.com/ip-ranges.json"
ip_ranges=$( curl -s "${aws_ip_address_url}" )

service=$(
    echo ${ip_ranges} | jq ".prefixes[].service" -r | sort | uniq | ${interactive_helper}
)

region=$(
    (
        echo "ALL"
        echo ${ip_ranges} | jq ".prefixes[] | select (.service == \"${service}\") | .region" -r | sort | uniq
    ) | ${interactive_helper}
)

if [ "${region}" == "ALL" ]; then
    condition=".service == \"${service}\""
else
    condition=".service == \"${service}\" and .region == \"${region}\""
fi

echo "# service=${service}"
echo "# region=${region}"
echo "#"
echo "# curl -s ${aws_ip_address_url} | jq '.prefixes[] | select( ${condition} ) | .ip_prefix' -r | sort -n"
echo "# curl -s ${aws_ip_address_url} | jq '.ipv6_prefixes[] | select( ${condition} ) | .ipv6_prefix' -r | sort -n"
echo ${ip_ranges} | jq ".prefixes[] | select( ${condition} ) | .ip_prefix" -r | sort -n
echo ${ip_ranges} | jq ".ipv6_prefixes[] | select( ${condition} ) | .ipv6_prefix" -r | sort -n

例えば、S3 が使用する IP アドレスを大阪リージョンの分だけ出力させてみると次のようになります。

$ get_aws_iprange.sh 

# service=S3
# region=ap-northeast-3
#
# curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq '.prefixes[] | select( .service == "S3" and .region == "ap-northeast-3" ) | .ip_prefix' -r | sort -n
# curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq '.ipv6_prefixes[] | select( .service == "S3" and .region == "ap-northeast-3" ) | .ipv6_prefix' -r | sort -n
3.5.240.0/22
52.95.157.0/24
52.95.158.0/23
52.95.181.0/24
52.95.182.0/23
2406:daa0:6000::/40
2406:daf0:6000::/40
2406:daf8:6000::/40
2406:daf9:6000::/40
2406:dafa:6000::/40