понедельник, 13 мая 2024 г.

Bash script for bashrc to user AWS CLI to connect to EC2 (standalone or K8s) over Session Menager from the terminal

 

0) Add to ~/.bashrc

function get-instance-id-by-private-dns-name () {
    aws ec2 describe-instances -- filters "Name=private-dns-name, Values=$1" -- query 'Reservations [] . Instances [] . InstanceId' -- output text
}

function connect-to-ec2-instance () {
    aws ssm start-session -- target $1
}

function connect-to-k8s-node () {
    instance_id=$(get-instance-id-by-private-dns-name $1)
    if [ -z "$instance id" ]; then
        echo "Could not find instance with name $1"
        return 1
    fi
        echo "Instance ID: $instance_id"
        connect-to-ec2-instance $instance_id
}

1) Export AWS Keys to ENV

2) Get the nodes
$ kubectl get nodes
NAME
ip-10-10-10-20.ec2.internal
ip-10-10-10-21.ec2.internal

3) Connect to a node
$ connect-to-k8s-node ip-10-10-10-20.ec2.internal

sh-4.4$