Testing aws ecs execute-command
This Terraform recipe creates a full, minimal infrastructure to test the aws ecs execute-command
feature recently announced. You can test it cloning this gist repo:
git clone https://gist.github.com/2b3364fa18ce74f39b43b6ce8f31cccc.git tf-ecsexectest
The recipe creates the following elements:
- VPC and related objects
- A bastion EC2 instance, with nginx, just for testing
- A load balancer
- ECS cluster
- ECS task definition, using the mendhak/http-https-echo image, and the corresponding task role and execution role
- ECS service running in Fargate, with 2 tasks, published in the path
/echo/
in the Load Balancer
After cloning, create the infrastructure (the variable key_pair
is optional, just to access the EC2 bastion instance):
terraform init
terraform apply -auto-approve -var key_pair=mykeypair
The key point in Terraform is the parameter enable_execute_command
in the aws_ecs_service
resource definition. Also, the task role has to have the permissions needed for communication between the managed SSM agent and the SSM service.
Wait for the ECS service and load balancer to be ready…
SERVICE_ADDR="http://$(terraform output -raw lb_addr)/echo/"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' ${SERVICE_ADDR})" != "200" ]]; do sleep 5; done
And get some outputs:
CLUSTER_NAME=$(terraform output -raw cluster_name)
SERVICE_NAME=$(terraform output -raw service_name)
FIRST_TASK_ARN=$(aws ecs list-tasks --cluster ${CLUSTER_NAME} --service-name ${SERVICE_NAME} --query 'taskArns[0]' --output text)
Finally, we can access the ECS tasks as if we were running docker exec
:
aws ecs execute-command --cluster ${CLUSTER_NAME} --task ${FIRST_TASK_ARN} --interactive --command "cat /etc/os-release"
aws ecs execute-command --cluster ${CLUSTER_NAME} --task ${FIRST_TASK_ARN} --interactive --command sh
Finally, you can destroy the infrastructure:
terraform destroy -auto-approve