I'm trying to get the current aws ssm sessionId after starting a session. I can see that when I start it it gets printed, like this
Starting session with SessionId: test@test.com-0ftz59d2285d67fb5
But I don't know where this comes from.
I can also see that I can grab it from the ssm-session worker but I'm trying to get it in a cleaner way:
[ssm-user@ip-100-66-11-11 bin]$ sudo systemctl status amazon-ssm-agent
● amazon-ssm-agent.service - amazon-ssm-agent
Loaded: loaded (/usr/lib/systemd/system/amazon-ssm-agent.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-03-08 09:54:44 UTC; 2h 48min ago
Main PID: 3092 (amazon-ssm-agen)
CGroup: /system.slice/amazon-ssm-agent.service
├─ 875 /usr/bin/ssm-session-worker test@test.com-0ftz59d2285d67fb5 i-0a7bb9a9064ccc96
├─ 886 bash -l
├─3092 /usr/bin/amazon-ssm-agent
└─3272 /usr/bin/ssm-agent-worker
I found two solutions for this. The first one is to use what the agent writes on the /var/lib
path, since it writes the names of the channels there, which matches the ssm session id. We can retrieve it like this:
# gets the EC2 instance ID
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
# the most recent channel matches the current ssm session id
sudo ls -t /var/lib/amazon/ssm/${INSTANCE_ID}/channels | head -1
The other option was provided to me by the AWS support and it is based on the logon shell's PID. If you run this directly in the session shell it will be the SSM Session Worker's PID. The loop runs until it finds the SSM Session Worker and then extracts the Session Id from the arguments or until no parent process exists. To run this you would need sudo access and run this using sudo. It will still work even when using sudo su. $PPID is the id of the parent process of the current process.
#!/bin/bash
PROCESSID=$PPID
while [ $PROCESSID ]
do
SESSIONWORKERPID=$(ps -o ppid= -o args= -p $PROCESSID 2> null)
if [[ "$SESSIONWORKERPID" =~ .*ssm-session-worker.* ]]; then
if [[ "$SESSIONWORKERPID" =~ .*?[[:space:]](.*?)[[:space:]].* ]]; then
echo ${BASH_REMATCH[1]}
fi
break;
fi
PROCESSID=$(ps -o ppid= -p $PROCESSID 2> null)
if [[ ! $PROCESSID ]]; then
echo "Session Id Not Found"
fi
done