1

I am trying to automate some part of my work by creating a bash function that let's me easily ssm into one of our instances. To do that, I only need to know the instance id. Then I run aws ssm start-session with the proper profile. Here's the function:

function ssm_to_cluster() {
  local instance_id=$(aws ec2 describe-instances --filters \
    "Name=tag:Environment,Values=staging" \
    "Name=tag:Name,Values=my-cluster-name" \
    --query 'Reservations[*].Instances[*].[InstanceId]' \
    | grep i- | awk '{print $1}' | tail -1)
  aws ssm start-session --profile AccountProfile --target $instance_id
}

When I run this function, I always get an error like the following:

An error occurred (TargetNotConnected) when calling the StartSession operation: "i-0599385eb144ff93c" is not connected.

However, then I take that instance id and run it from my terminal directly, it works:

aws ssm start-session --profile MyProfile --target i-0599385eb144ff93c

Why is this?

breezymri
  • 3,975
  • 8
  • 31
  • 65

1 Answers1

1

You're sending instance ID as "i-0599385eb144ff93c" instead of i-0599385eb144ff93c.

Modified function that should work -

function ssm_to_cluster() {
  local instance_id=$(aws ec2 describe-instances --filters \
    "Name=tag:Environment,Values=staging" \
    "Name=tag:Name,Values=my-cluster-name" \
    --query 'Reservations[*].Instances[*].[InstanceId]' \
    | grep i- | awk '{print $1}' | tail -1 | tr -d '"')
  aws ssm start-session --profile AccountProfile --target $instance_id
}
Jeechu Deka
  • 354
  • 1
  • 4
  • This works. However, something interesting I noticed was that when I directly run the `aws ssm start-session` command, I can put double quotes (even 2 double quotes) around the instance id string and it works. I guess it probably has something to do with how bash treats the double quotes within a variable vs directly on the command line input. – breezymri Mar 17 '19 at 14:39
  • I've got this same problem and don't quite understand the solution. My error is: An error occurred (InternalServerError) when calling the StartSession operation (reached max retries: 4): java.io.IOException: com.ctc.wstx.exc.WstxUnexpectedCharException: Illegal character ((CTRL-CHAR, code 27)) at [row,col {unknown-source}]: [2,42] – John LaBarge Apr 10 '20 at 19:33