I tried to run the execute-command AWS Command Line Interface (AWS CLI) command in Amazon Elastic Container Service (Amazon ECS). But, I receive the "An error occurred (TargetNotConnectedException) when calling the ExecuteCommand operation: The execute command failed due to an internal error. Try again later" error message.
Short description
You get the "ExecuteCommand" error message for the following reasons:
- The Amazon ECS task role doesn't have the required permissions to run execute-command.
- The AWS Identity and Access Management (IAM) role or user that runs the command doesn't have the required permissions.
Resolution
Note: If you receive errors when you run AWS CLI commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.
Update the Amazon ECS task role permissions
Complete the following steps:
- Create the following IAM policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel"
],
"Resource": "*"
}
]
}
Note: Make sure that your configuration doesn't block the preceding permissions at the AWS Organizations level.
- Attach the policy to the Amazon ECS task role.
There might be delays when you update the task role permissions. Wait for a few minutes after you attach the policy to the task role, and then run the execute-command command.
Check the IAM user or role permissions
To check the IAM user ID and role that you're signed in as, run the following command:
aws sts get-caller-identity
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/*"
}
]
}
Attach a new policy or update the existing policy for the user or role to include the preceding permissions.
Check whether you set pidMode to task in the task definition
You can have only one ECS Exec session for each process ID (PID) namespace. If you share a PID namespace in a task, then you can start ECS Exec sessions in only one container.
Check whether you set readonlyRootFilesystem to true in the task definition
To create the required directories and files, SSM Agent requires a writeable container file system. You can't use the readonlyRootFilesystem task definition parameter or any other method to make the root file system read only.
If you still get the error after you update the task definition, then run amazon-ecs-exec-checker from the GitHub website. The amazon-ecs-exec-checker script validates your AWS CLI environment and the Amazon ECS cluster or task. The script also notifies you if you don't meet a prerequisite.
Related information
Using ECS Exec