定义内网ip列表池
cat ip_list.txt
192.168.1.1
192.168.1.2
定义脚本安全组id等元数据
SECURITY_GROUP_ID="sg-0f08237289xxxxx"
IFS=' ' read -ra INTERNAL_IPS <<< $(cat ip_list.txt)
for IP in "${INTERNAL_IPS[@]}"
do
INSTANCE_ID=$(aws ec2 describe-instances --filters "Name=private-ip-address,Values=$IP" --query 'Reservations[].Instances[].InstanceId' --output text)
if [ ! -z "$INSTANCE_ID" ]
then
CURRENT_SECURITY_GROUPS=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query 'Reservations[].Instances[].SecurityGroups[].GroupId' --output text)
NEW_SECURITY_GROUPS="$CURRENT_SECURITY_GROUPS $SECURITY_GROUP_ID"
echo "Adding security groups $NEW_SECURITY_GROUPS to instance $INSTANCE_ID"
aws ec2 modify-instance-attribute --instance-id $INSTANCE_ID --groups $NEW_SECURITY_GROUPS
else
echo "No instance found with internal IP $IP"
fi
done