Created
February 26, 2025 18:22
-
-
Save atheiman/9d45b04353edfaf511ac0d005e73103f to your computer and use it in GitHub Desktop.
Run an ECS Fargate task running `sleep` and exec into the task. This can be used to get a Linux shell in a subnet without launching an EC2 instance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Prerequisites: | |
# - ECS Fargate cluster | |
# - ECS task IAM role: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html | |
# Be sure to include ECS exec permissions: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html#ecs-exec-required-iam-permissions | |
# - (optional) ECS task execution IAM role: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html | |
aws ecs list-task-definitions | |
# Register a task definition for alpine image running "sleep 600" so you can exec into the container for 10 min | |
aws ecs register-task-definition --cli-input-json '{ | |
"family": "alpine-sleep", | |
"cpu": "1024", | |
"memory": "2048", | |
"containerDefinitions": [{ | |
"name": "alpine", | |
"image": "public.ecr.aws/docker/library/alpine", | |
"cpu": 512, | |
"memory": 1024, | |
"command": ["sleep", "600"] | |
}], | |
"taskRoleArn": "arn:aws:iam::111111111111:role/ecs-task", | |
"executionRoleArn": "arn:aws:iam::111111111111:role/ecs-task-execution", | |
"networkMode": "awsvpc", | |
"runtimePlatform": { | |
"cpuArchitecture": "X86_64", | |
"operatingSystemFamily": "LINUX" | |
}, | |
"requiresCompatibilities": [ | |
"EC2", | |
"FARGATE" | |
] | |
}' | |
# Run a task referencing the task definition created above | |
aws ecs run-task \ | |
--cluster cluster-name \ | |
--task-definition alpine-sleep \ | |
--network-configuration '{ | |
"awsvpcConfiguration": { | |
"subnets": ["subnet-aaaaaaaa", "subnet-bbbbbbbb"], | |
"securityGroups": ["sg-cccccccc"], | |
"assignPublicIp": "DISABLED" | |
} | |
}' \ | |
--capacity-provider-strategy 'capacityProvider=FARGATE_SPOT' \ | |
--enable-ecs-managed-tags \ | |
--enable-execute-command | |
# Note the task id, or find the new running task in ECS console | |
aws ecs execute-command \ | |
--cluster cluster-name \ | |
--task '<taskid>' \ | |
--interactive \ | |
--command /bin/sh | |
# A shell will open on the task container, and you can run commands here. The task will die after 10 min as specified in the task definition |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment