Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Created April 21, 2025 06:19
Show Gist options
  • Save huynhbaoan/6cb1edfe1ba3481d0a0e8d90ed91c417 to your computer and use it in GitHub Desktop.
Save huynhbaoan/6cb1edfe1ba3481d0a0e8d90ed91c417 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# runscript.sh
# Usage: ./runscript.sh <ip-address>
set -euo pipefail
IP_ADDRESS=${1:-}
if [[ -z $IP_ADDRESS ]]; then
echo "Usage: $0 <ip-address>"
exit 1
fi
# 1) lookup ENI
eni=$(aws ec2 describe-network-interfaces \
--filters "Name=private-ip-address,Values=$IP_ADDRESS" \
--query 'NetworkInterfaces[0]' \
--output json 2>/dev/null) || eni="null"
if [[ -z $eni || $eni == "null" ]]; then
echo "IP $IP_ADDRESS → not found"
exit 0
fi
# extract helpers
interface_type=$(jq -r '.InterfaceType // ""' <<<"$eni")
description =$(jq -r '.Description // ""' <<<"$eni")
attach_id =$(jq -r '.Attachment.InstanceId // ""' <<<"$eni")
# 2) classify
## 2.1 Lambda
if [[ $interface_type == "lambda" ]]; then
# drop prefix
lambda_full=${description#AWS Lambda VPC ENI-}
# remove trailing UUID (8-4-4-4-12 hex) + anything after (e.g. colon)
lambda_name=$(printf '%s' "$lambda_full" |
sed -E 's/-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}.*$//')
echo "Lambda $lambda_name"
exit 0
fi
## 2.2 NLB
if [[ $interface_type == "network_load_balancer" ]]; then
# "ELB net/<NLB-name>/…"
nlb_full=${description#ELB net/}
nlb_name=${nlb_full%%/*}
echo "NLB $nlb_name"
exit 0
fi
## 2.3 ALB
if [[ $description == ELB\ app/* ]]; then
# "ELB app/<ALB-name>/…"
alb_full=${description#ELB app/}
alb_name=${alb_full%%/*}
echo "ALB $alb_name"
exit 0
fi
## 2.4 Classic ELB
if [[ $interface_type == "interface" && $description == ELB\ * ]]; then
# "ELB <ELB-name>"
elb_name=${description#ELB }
echo "ELB $elb_name"
exit 0
fi
## 2.5 ECS
ecs_arn=$(jq -r '.TagSet[]? | select(.Key=="aws:ecs:taskArn") | .Value' <<<"$eni")
if [[ -n $ecs_arn ]]; then
echo "ECS $ecs_arn"
exit 0
fi
## 2.6 EKS branch
if [[ $interface_type == "branch" ]]; then
echo "EKS branch"
exit 0
fi
## 2.7 EKS trunk
eks_node=$(jq -r '.TagSet[]? | select(.Key=="node.k8s.amazonaws.com/instance_id") | .Value' <<<"$eni")
if [[ -n $eks_node ]]; then
node_name=$(aws ec2 describe-instances \
--instance-ids "$eks_node" \
--query 'Reservations[0].Instances[0].Tags[?Key==`Name`].Value|[0]' \
--output text 2>/dev/null || echo "")
echo "EKS ${node_name:-$eks_node}"
exit 0
fi
## 2.8 EC2
if [[ -n $attach_id ]]; then
inst_name=$(aws ec2 describe-instances \
--instance-ids "$attach_id" \
--query 'Reservations[0].Instances[0].Tags[?Key==`Name`].Value|[0]' \
--output text 2>/dev/null || echo "")
echo "EC2 ${inst_name:-$attach_id}"
exit 0
fi
# 2.9 fallback
echo "Other"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment