Skip to content

Instantly share code, notes, and snippets.

@yaasita
Created December 21, 2025 16:12
Show Gist options
  • Select an option

  • Save yaasita/050bb4d1e548896578f46f4d223a1164 to your computer and use it in GitHub Desktop.

Select an option

Save yaasita/050bb4d1e548896578f46f4d223a1164 to your computer and use it in GitHub Desktop.
#!/bin/bash
export AWS_USE_DUALSTACK_ENDPOINT=true
export AWS_DEFAULT_OUTPUT=json
function help_eip {
echo "Usage: eip on|off|status"
echo "on [hours]: EIPを指定した時間だけ割り当て (デフォルトは1時間)"
echo "off : EIPを解放"
echo "status : EIPの状態を表示"
}
function eip {
local region="us-east-1"
local token=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
local instance_id=$(curl -s -H "X-aws-ec2-metadata-token: $token" http://169.254.169.254/latest/meta-data/instance-id)
local assoc=$(aws ec2 describe-addresses --region "$region" --filters "Name=instance-id,Values=$instance_id")
local action=$1
local eip_keep_hours=${2:-1}
if [[ "$action" == "on" ]]; then
if [[ $(echo "$assoc" | jq '.Addresses | length') -gt 0 ]]; then
echo "既にEIPが割り当たっています"
return 1
fi
local alloc=$(aws ec2 allocate-address --domain vpc --region "$region")
local alloc_id=$(echo "$alloc" | jq -r '.AllocationId')
local pub_ip=$(echo "$alloc" | jq -r '.PublicIp')
aws ec2 associate-address --instance-id "$instance_id" --allocation-id "$alloc_id" --region "$region"
echo "EIPを割り当てました: $pub_ip (保持時間: ${eip_keep_hours}時間)"
echo $eip_keep_hours > /root/tmp/eip_keep_hours.txt
elif [[ "$action" == "off" ]]; then
if [[ $(echo "$assoc" | jq '.Addresses | length') -eq 0 ]]; then
echo "EIPが割り当たっていません"
return 1
fi
local assoc_id=$(echo "$assoc" | jq -r '.Addresses[0].AssociationId')
local alloc_id=$(echo "$assoc" | jq -r '.Addresses[0].AllocationId')
aws ec2 disassociate-address --association-id "$assoc_id" --region "$region"
aws ec2 release-address --allocation-id "$alloc_id" --region "$region"
echo "EIPを解放しました"
elif [[ "$action" == "status" ]]; then
if [[ $(echo "$assoc" | jq '.Addresses | length') -gt 0 ]]; then
local pub_ip=$(echo "$assoc" | jq -r '.Addresses[0].PublicIp')
echo "EIPが割り当たっています: $pub_ip"
else
echo "EIPが割り当たっていません"
fi
else
help_eip
return 1
fi
}
eip status
#!/bin/bash
set -euxo pipefail
file_age_hours() {
local file="$1"
if [[ ! -e "$file" ]]; then
echo "ファイルが存在しません" >&2
return 1
fi
# ファイルの最終更新時刻(epoch秒)
local mtime
mtime=$(stat -c %Y "$file")
# 現在時刻(epoch秒)
local now
now=$(date +%s)
# 経過時間(秒)
local diff=$(( now - mtime ))
# 時間に換算(小数切り捨て)
echo $(( diff / 3600 ))
}
eip_create=/root/tmp/eip_keep_hours.txt
if [[ -r $eip_create && $(file_age_hours $eip_create) -ge $(cat $eip_create) ]];then
echo "EIPの保持時間が経過しました。EIPを解放します"
source /etc/profile.d/aws-ec2-eip.sh
eip off
rm $eip_create
else
echo "EIPはまだ保持時間内です"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment