SSM at the Speed of Thought

At work I have to deal with dozens of AWS accounts spread across many organizations. I often have to ssm into an instance to debug and fix issues. It's obviously not ideal but that's where we are at a work :/. These .bashrc snippets help me find the instance I'm looking with as little effort as possible.

Note these snippets do require you to have your $AWS_CONFIG_FILE properly configured.

The first snippet allows me to establish an SSO session with the organization I'm working in.

aws-sso() {
    sso_session=$(grep sso-session ~/.aws/config | tr -d '][' | cut -d ' ' -f 2 | sort | fzf)
    if [ -z "$sso_session" ]; then
        return
    fi

    aws sso login --sso-session "$sso_session"
}

This next allows me to quickly choose an account (or profile) in the organization and then ssm into an ec2 instance running in that account.

read -r -d '' SSM_EC2_QUERY << 'EOF' || true
Reservations[].Instances[].{
    ID: InstanceId,
    Name: Tags[?Key==`Name`].Value | [0],
    State: State.Name,
    LaunchTime: LaunchTime
}
EOF

ssm-ec2() {
    profile=$(aws configure list-profiles | sort | fzf)
    if [ -z $profile ]; then
        return
    fi

    instance_id=$(aws ec2 describe-instances --query "$SSM_EC2_QUERY" \
        --profile "$profile" \
        --filters Name=instance-state-name,Values=running \
        --output json | jq -r '.[] | [.ID, .Name, .LaunchTime] | @tsv' | fzf | awk '{print $1}' | tr -d '\n')

    if [ -n "$instance_id" ]; then
        aws ssm start-session --target "$instance_id" --profile "$profile"
    fi
}

If you are feeling more adventurous you can even spawn a tmux session and connect directly to it. I have commands defined in json files that do more complicated things like opening + naming tmux windows and panes, each tailing a log file or running a systemctl status ... command.

ssm-tmux() {
    profile=$(aws configure list-profiles | sort | fzf)
    if [ -z $profile ]; then
        return
    fi

    instance_id=$(aws ec2 describe-instances --query "$SSM_EC2_QUERY" \
        --profile "$profile" \
        --filters Name=instance-state-name,Values=running \
        --output json | jq -r '.[] | [.ID, .Name, .LaunchTime] | @tsv' | fzf | awk '{print $1}' | tr -d '\n')

    cmd="{\"command\": [\"sudo su -c 'tmux attach-session -t 0 || tmux'\"]}"
    if [ -n "$instance_id" ]; then
        aws ssm start-session \
            --target "$instance_id" \
            --profile "$profile" \
            --document-name 'AWS-StartInteractiveCommand' \
            --parameters "$cmd"
    fi
}