How do I resolve the error "An error occurred (TargetNotConnectedException) when calling the ExecuteCommand operation" in Amazon ECS?

2 minute read
1

When I try to run the AWS Command Line Interface (AWS CLI) command execute-command in Amazon Elastic Container Service (Amazon ECS), I get the following error: "An error occurred (TargetNotConnectedException) when calling the ExecuteCommand operation: The execute command failed due to an internal error. Try again later"

Short description

You might get this error due to the following reasons:

  • The Amazon ECS task role doesn't have the required permissions to run the execute-command command.
  • The AWS Identity and Access Management (IAM) role or user that's running the command doesn't have the required permissions.

Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.

Resolution

Check the Amazon ECS task role permissions

You get this error when the Amazon ECS task role doesn't have the required permissions. You might resolve this error by creating an IAM policy with the required permissions and then attaching the policy to the Amazon ECS task role.

1.    Create the following IAM policy:

{
   "Version": "2012-10-17",
   "Statement": [
       {
       "Effect": "Allow",
       "Action": [
            "ssmmessages:CreateControlChannel",
            "ssmmessages:CreateDataChannel",
            "ssmmessages:OpenControlChannel",
            "ssmmessages:OpenDataChannel"
       ],
      "Resource": "*"
      }
   ]
}

Note: Be sure that these permissions are not denied at the AWS Organizations level.

2.    Attach the policy to the Amazon ECS task role.

There might be delays in propagating these changes at the task level. Therefore, wait for some time after attaching the policy to the task role, and then try running the execute-command command.

Check the IAM user or role permissions

Be sure that the IAM user or role that's running the execute-command command has the following permissions:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ecs:ExecuteCommand",
            "Resource": "arn:aws:ecs:example-region:example-arn:cluster/example-cluster/*"
        }
    ]
}

If you're still getting the error, run the amazon-ecs-exec-checker script. This script allows you to check and validate your AWS CLI environment and the Amazon ECS cluster or task. The script also notifies you about the prerequisite that's not met.


Related information

Enabling and using ECS Exec

AWS OFFICIAL
AWS OFFICIALUpdated 2 years ago