breezymri
breezymri

Reputation: 4353

aws cli: ssm start-session not working with a variable as a parameter value

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?

Upvotes: 1

Views: 7112

Answers (1)

Jeechu Deka
Jeechu Deka

Reputation: 364

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
}

Upvotes: 1

Related Questions