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 for 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 you run AWS CLI commands, then see Troubleshoot AWS CLI errors. Also, make sure that you're using the most recent AWS CLI version.

Resolution

Check the Amazon ECS task role permissions

You get this error when the Amazon ECS task role doesn't have the required permissions. To resolve this error, create an IAM policy with the required permissions, and then attach 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 aren't denied at the AWS Organizations level.
  2. Attach the policy to the Amazon ECS task role.

There might be delays in making these changes at the task level. Therefore, wait for some time after you attach the policy to the task role, and then run the execute-command command.

Check the IAM user or role permissions

The IAM user or role that runs the execute-command command must have 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 still get the error, run the amazon-ecs-exec-checker script from the GitHub website. 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 wasn't met.

Related information

Using ECS Exec

AWS OFFICIAL
AWS OFFICIALUpdated 17 days ago