Skip to content

Instantly share code, notes, and snippets.

@groundcat
Last active December 8, 2023 01:11
Show Gist options
  • Select an option

  • Save groundcat/f004eb3af285a1f3cf8dc22f029e7351 to your computer and use it in GitHub Desktop.

Select an option

Save groundcat/f004eb3af285a1f3cf8dc22f029e7351 to your computer and use it in GitHub Desktop.
Change static IP for Lightsail instances with AWS-CLI

Dependency

Install jq

wget https://github.com/jqlang/jq/releases/download/jq-1.7/jq-linux64 -O /usr/local/bin/jq
chmod +x /usr/local/bin/jq

Create LightsailFullAccessGroup IAM user following this instruction

Configure AWS-CLI

$ aws configure

Usage

bash changeip.sh us-east-1

Install crontab

crontab -e

Then add the following:

# Rotate IP
5 9 * * * bash ~/changeip.sh us-east-1

Reference

https://github.com/angelsky11/change-lightsail-ip

#!/bin/bash
REGION=$1
readonly REGION
echo -e '*****************************************************************'
echo -e '***************************** START *****************************'
echo -e '*****************************************************************'
#定义主进程
function main {
#获取静态ip列表
local ipjson=$(aws lightsail --region $REGION get-static-ips)
#获取静态ip数量
local NUM_IP=$(echo $ipjson | jq -r '.|length')
for (( i = 0 ; i < $NUM_IP ; i++ ))
do
echo -e '=========================seq '$i' start========================='
#获取ip各项信息
local OLD_IP=$(echo $ipjson | jq -r '.[]['$i'].ipAddress')
local INSTANCE_NAME=$(echo $ipjson | jq -r '.[]['$i'].attachedTo')
local STATIC_IP_NAME=$(echo $ipjson | jq -r '.[]['$i'].name')
echo -e "1. checking vps "$OLD_IP
#删除原静态ip
aws lightsail --region $REGION release-static-ip --static-ip-name $STATIC_IP_NAME
#新建静态ip
aws lightsail --region $REGION allocate-static-ip --static-ip-name $STATIC_IP_NAME
#绑定静态ip
aws lightsail --region $REGION attach-static-ip --static-ip-name $STATIC_IP_NAME --instance-name $INSTANCE_NAME
#获取新ip
local instancejson=$(aws lightsail --region $REGION get-instance --instance-name $INSTANCE_NAME)
local NEW_IP=$(echo $instancejson | jq -r '.[].publicIpAddress')
rm -rf temp.$OLD_IP.txt
done
}
main $REGION
echo -e '*****************************************************************'
echo -e '****************************** END ******************************'
echo -e '*****************************************************************'
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment