To run your Python script on AWS Fargate, follow these steps:
-
Containerize Your Python Script:
- Create a Dockerfile: This file defines how your Python script is packaged into a Docker container.
FROM python:3.10-slim
WORKDIR /app
COPY your_script.py .
CMD ["python", "your_script.py"]
- Build the Docker Image:
docker build -t your-python-script .
- Test Locally:
docker run your-python-script
-
Push the Docker Image to Amazon Elastic Container Registry (ECR):
- Create an ECR Repository:
aws ecr create-repository --repository-name your-python-script
- Authenticate Docker to ECR:
aws ecr get-login-password --region your-region | docker login --username AWS --password-stdin your-account-id.dkr.ecr.your-region.amazonaws.com
- Tag and Push the Image:
docker tag your-python-script:latest your-account-id.dkr.ecr.your-region.amazonaws.com/your-python-script:latest
docker push your-account-id.dkr.ecr.your-region.amazonaws.com/your-python-script:latest
-
Set Up AWS Fargate to Run Your Container:
- Create an ECS Cluster:
aws ecs create-cluster --cluster-name your-cluster-name
- Define a Task Definition:
Create a JSON file named
task-definition.json with the following content:
{
"family": "your-task-family",
"networkMode": "awsvpc",
"executionRoleArn": "arn:aws:iam::your-account-id:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "your-container-name",
"image": "your-account-id.dkr.ecr.your-region.amazonaws.com/your-python-script:latest",
"memory": 512,
"cpu": 256,
"essential": true
}
],
"requiresCompatibilities": [
"FARGATE"
],
"cpu": "256",
"memory": "512"
}
Then register the task definition:
aws ecs register-task-definition --cli-input-json file://task-definition.json
- Run the Task on Fargate:
aws ecs run-task --cluster your-cluster-name --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets=[\"your-subnet-id\"],securityGroups=[\"your-security-group-id\"],assignPublicIp=\"ENABLED\"}" --task-definition your-task-family
Note: Ensure that your AWS CLI is configured with the necessary permissions and that you've replaced placeholders like your-script.py, your-account-id, your-region, your-cluster-name, your-task-family, your-container-name, your-subnet-id, and your-security-group-id with your actual AWS resources and script names.
By following these steps, your Python script will run on AWS Fargate without the need to manage the underlying infrastructure.