Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DevOps Lifecycle
  • DevOps Roadmap
  • Docker Tutorial
  • Kubernetes Tutorials
  • Amazon Web Services [AWS] Tutorial
  • AZURE Tutorials
  • GCP Tutorials
  • Docker Cheat sheet
  • Kubernetes cheat sheet
  • AWS interview questions
  • Docker Interview Questions
  • Ansible Interview Questions
  • Jenkins Interview Questions
Open In App
Next Article:
How to Create AWS S3 Bucket Using Terraform?
Next article icon

How to Push Docker Image to AWS ECS Fargate Using Terraform?

Last Updated : 26 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

ECS helps to manage containers and this service is provided by AWS, it allows users to easily manage and scale docker containers on a cluster of ec2 instances, without having to manage the underlying infrastructure.

What is ECS Fargate?

Fargate provides a way to run containerized applications on a serverless infrastructure, which means you only pay for the resources you use, without having to manage servers or clusters. With Fargate, you can launch and manage containers in a matter of minutes, without worrying about managing the underlying infrastructure or scaling your applications.

Before going to terraform step we need to confirm whether we have IAM account or not.For this search iam in services and click on add users on left-hand side and give administrator access to it and add this user to a group.

This will give you aws access key and secret access key, now configure them to your installed AWS CLI. Now you should have dockerfile for your project, here for example django project is used.

Example Docker file:

# Use an official Python runtime as a parent image  FROM python:3.9-slim-buster    # Set the working directory to /app  WORKDIR /app    # Copy the requirements file into the container  COPY requirements.txt .    # Install any needed packages specified in requirements.txt  RUN pip install --no-cache-dir -r requirements.txt    # Copy the rest of the application code into the container  COPY . .    # Set environment variables  ENV PYTHONUNBUFFERED=1 \      DJANGO_ENV=production    # Expose port 8000  EXPOSE 8000    # Run the command to start the server  CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

You should test your Dockerfile first by building the image and running the conatiner.

Now we can start making terraform file if all these things are working.

Make a terraform file name main.tf inside the same directory where your docker file is and follow the following steps:

Step 1: Add the AWS provider as follows

terraform {    required_providers {      aws = {        source = "hashicorp/aws"        version = "4.45.0"      }    }  }

Step 2: Now you have to provide AWS credentials to allow terraform to connect to AWS.

provider "aws" {    region  = "us-east-1" #The region where the environment     #is going to be deployed # Use your own region here    access_key = "enter_access_key_here" # Enter AWS IAM     secret_key = "enter_secret_key_here" # Enter AWS IAM     token="enter_token_here" # for private repository only  }

Step 3: Now create an ECR repository in terraform

resource "aws_ecr_repository" "app_ecr" {    name = "djangoapp-repo"  }

Step 4: Now start by running terraform init command in terminal. 

terraform init will initialize the configuration files in working directory and it will show Terraform has been successfully initialized!

you will see a this as output in terminal.

 

Step 5: Now run terraform plan command

terraform plan is a Terraform command that is used to create an execution plan for your infrastructure deployment. When you run terraform plan, Terraform examines your infrastructure configuration files (written in HCL) and creates a detailed execution plan that shows what actions Terraform will take to achieve the desired infrastructure state.

 

Step 6: Now run terraform apply command.

terraform apply is a Terraform command that applies the changes required to reach the desired infrastructure state. When you run terraform apply, Terraform examines your infrastructure configuration files (written in HCL) and applies the changes needed to reach the desired infrastructure state.

 

You will be asked to approve the process just enter yes

Step 7: Now open ECR in AWS account and go to public repositories you will find the repository named djangoapp-repo inside it.

Step 8: Click on that repository and on the top right you will see view push commands and you can follow the steps there to push the image to from your local to that repository.

 
 

Step 9:  For launching this image you need a target so we have to make a cluster, it acts as a container target.

resource "aws_ecs_cluster" "your_cluster" {    name = "app-cluster"   }

Step 10: Now again perform terraform apply. You will see a cluster in ECS.

 

Amazon Elastic Container Service (ECS) provides two launch types for deploying containers: EC2 launch type and Fargate launch type.

EC2 Launch Type: With the EC2 launch type, you can launch containers on a cluster of Amazon Elastic Compute Cloud (EC2) instances that you manage yourself. In this mode, you have complete control over the underlying infrastructure, including the ability to choose the instance types, configure the networking and storage, and manage the EC2 instances directly. The EC2 launch type is recommended for users who have existing EC2 infrastructure and need more control over the underlying infrastructure.

Fargate Launch Type: With the Fargate launch type, you can launch containers on a fully-managed infrastructure without the need to manage the underlying EC2 instances. In this mode, you only need to specify the container images and resource requirements, and AWS manages the rest, including provisioning the infrastructure, scaling, and patching. The Fargate launch type is recommended for users who want a serverless experience for running containers and do not want to manage the underlying infrastructure.

Step 11: Here we are using fargate which is serverless

resource "aws_ecs_task_definition" "djangoapp_task" {    family                   = "djangoapp-first-task" # Name your task    container_definitions    = <<DEFINITION    [      {        "name": "app-first-task",        "image": "${aws_ecr_repository.app_ecr.repository_url}",        "essential": true,        "portMappings": [          {            "containerPort": 8000,            "hostPort": 8000          }        ],        "memory": 512,        "cpu": 256      }    ]    DEFINITION    requires_compatibilities = ["FARGATE"] # use Fargate as the launch type    network_mode             = "awsvpc"    # add the AWS VPN network mode as this is required for Fargate    memory                   = 512         # Specify the memory the container requires you can specify yours    cpu                      = 256         # Specify the CPU the container requires    execution_role_arn       = "${aws_iam_role.ecsTaskExecutionRole.arn}"  }

Step 12: Now we have to create a task definition

resource "aws_iam_role" "ecsTaskExecutionRole" {    name               = "ecsTaskExecutionRole"    assume_role_policy = "${data.aws_iam_policy_document.assume_role_policy.json}"  }    data "aws_iam_policy_document" "assume_role_policy" {    statement {      actions = ["sts:AssumeRole"]        principals {        type        = "Service"        identifiers = ["ecs-tasks.amazonaws.com"]      }    }  }    resource "aws_iam_role_policy_attachment" "ecsTaskExecutionRole_policy" {    role       = "${aws_iam_role.ecsTaskExecutionRole.name}"    policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"  }

Step 13: Now perfrom terraform apply, for the private repository you may need to add an internet gateway just add it.

 

Step 14: Now the configurations are done and we need to connect all these things so we need VPC

A Virtual Private Cloud (VPC) is a virtual network infrastructure that allows you to create isolated, private networks within the AWS Cloud. With a VPC, you have complete control over your virtual networking environment, including the IP address range, subnets, routing tables, and network gateways.

# Provide a default VPC  resource "aws_default_vpc" "default_vpc" {  }    # Provide your default subnets  resource "aws_default_subnet" "default_subnet_a" {    # Use your own region here but reference to subnet 1a    availability_zone = "us-east-1a"  }    resource "aws_default_subnet" "default_subnet_b" {    # Use your own region here    availability_zone = "us-east-1b"  }

Step 15 : Implement a Load balancer

resource "aws_alb" "application_load_balancer" {    name               = "load-balancer-django" #name    load_balancer_type = "application"    subnets = [ # giving the default subnets      "${aws_default_subnet.default_subnet_a.id}",      "${aws_default_subnet.default_subnet_b.id}"    ]    # security groups    security_groups = ["${aws_security_group.load_balancer_security_group.id}"]  }

Step 16: Create a Security group for load balancer

resource "aws_security_group" "load_balancer_security_group" {    ingress {      from_port   = 80      to_port     = 80      protocol    = "tcp"      cidr_blocks = ["0.0.0.0/0"] # Allow traffic from all resources    }      egress {      from_port   = 0      to_port     = 0      protocol    = "-1"      cidr_blocks = ["0.0.0.0/0"]    }  }

Step 17:  Configure the load balancer with vpc created earlier.

resource "aws_lb_target_group" "target_group" {    name        = "target-group"    port        = 80    protocol    = "HTTP"    target_type = "ip"    vpc_id      = "${aws_default_vpc.default_vpc.id}" # default VPC  }    resource "aws_lb_listener" "listener" {    load_balancer_arn = "${aws_alb.application_load_balancer.arn}" #  mention load balancer    port              = "80"    protocol          = "HTTP"    default_action {      type             = "forward"      target_group_arn = "${aws_lb_target_group.target_group.arn}" # mention target group    }  }

Step 18: Create an ECS service, this will run cluster, task and fargate.

resource "aws_ecs_service" "app_service" {    name            = "app-first-service"     # Name of the service    cluster         = "${aws_ecs_cluster.your_cluster.id}"   # give the created Cluster    task_definition = "${aws_ecs_task_definition.djangoapp_task.arn}" # give the task that the service will spin up    launch_type     = "FARGATE"    desired_count   = 3 # Set up the number of containers to 3      load_balancer {      target_group_arn = "${aws_lb_target_group.target_group.arn}" # give the target group      container_name   = "${aws_ecs_task_definition.djangoapp_task.family}"      container_port   = 8000 # give the container port    }      network_configuration {      subnets          = ["${aws_default_subnet.default_subnet_a.id}", "${aws_default_subnet.default_subnet_b.id}"]      assign_public_ip = true     # give the containers with public IPs      security_groups  = ["${aws_security_group.service_security_group.id}"] # set up the security group    }  }

Step 19:To ensure access for ecs service with more secure vpc create a aws sercurity group service.

resource "aws_security_group" "service_security_group" {    ingress {      from_port = 0      to_port   = 0      protocol  = "-1"      #allowing the traffic from load balancer security group      security_groups = ["${aws_security_group.load_balancer_security_group.id}"]    }      egress {      from_port   = 0      to_port     = 0      protocol    = "-1"      cidr_blocks = ["0.0.0.0/0"]    }  }

Step 20: The ouput should be in url value like django server runs on localhost 8000

output "app_url" {    value = aws_alb.application_load_balancer.dns_name  }

Now the terraform is set to create and manage infrastructure on AWS.

Now perform following commands:

  • terraform validate: It will validate the syntax.
 
  • terraform plan: It will help us to visualize how terraform perform and create resource.
 
  • terraform apply: It will apply all the provisioned infrastructure
 
  • Give some time after this step and open the output URL

if not in use just run terraform destroy to reduce any cost.


Next Article
How to Create AWS S3 Bucket Using Terraform?

S

shreyanshgupta838
Improve
Article Tags :
  • Amazon Web Services
  • DevOps
  • Terraform

Similar Reads

  • How to Create AWS S3 Bucket Using Terraform?
    S3 stands for Simple Storage Service. S3 buckets are cloud storage services by Amazon Web Service. It is used to store objects, It consists of data in any format like documents, images, videos, and application code. These are highly scalable. Prerequisite: AWS AccountTerraform InstallationAWS CLISte
    3 min read
  • How To Create AWS IAM Roles Using Terraform?
    Terraform is an IAAC tool which is used provision infrastructure . Here in this guide i will first discuss what is terraform . Then i will discuss what is IAM Role and in which scenarios we should use IAM Role . Then i will walk you through the different steps to create an IAM Role for an EC2 servic
    5 min read
  • How To Create SQS In AWS Using Terraform ?
    Amazon Simple Queue Service (SQS) is a completely managed message queuing service provided by AWS, offering scalable and reliable message conveyance between distributed parts of an application. It fills in as a fundamental building block for building event driven, microservice-based models, empoweri
    8 min read
  • How To Create Key Pair In AWS Using Terraform ?
    In cloud infrastructure management, secure admittance to instances is central. While working with Amazon Web Services (AWS) utilizing Terraform, creating key pairs is fundamental for secure access to EC2 instances. Key pairs comprise of a public key and a private key, where the public key is utilize
    6 min read
  • How To Create EMR Cluster In AWS Using Terraform ?
    In today's data-driven world, big data processing has become an integral part of many organizations' workflows. Amazon EMR (Elastic MapReduce) is a cloud-based platform provided by Amazon Web Services (AWS) that simplifies the process of running and scaling Apache Hadoop and Apache Spark clusters fo
    10 min read
  • How To Create Elastic IP In AWS Using Terraform ?
    Using Terraform, creating an Elastic IP (EIP) on AWS entails specifying the resources required in a Terraform configuration file in order to create the EIP. A static IPv4 address intended for dynamic cloud computing is called an elastic IP. It is helpful in situations when you require a public IP ad
    4 min read
  • How To Create ECR Repository In AWS Using Terraform ?
    In a cloud computing and microservice world, we must concentrate on the involvement of the infrastructure resources properly. With Terraform, an open source IaC (infrastructure as code) tool that is widely used for provisioning and managing cloud resources across many cloud service providers such as
    9 min read
  • How to Create AWS EC2 using Terraform?
    AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, cl
    13 min read
  • How To Create AWS VPC Using Terraform ?
    Terraform is an IAAC tool used to automate programmatic infrastructure provisioning. Here in this guide, I will first discuss what is AWS VPC. Then I will discuss terraform. After this, I will walk you through the different steps to write a code using Terraform to create a custom AWS VPC using subne
    6 min read
  • How to Create AWS VPC Peering using Terraform?
    In the dynamic scene of cloud computing, networking is a basic perspective for building vigorous and versatile architectures. AWS Virtual Private Cloud (VPC) offers a dedicated space inside the Amazon Web Services (AWS) cloud, allowing users to define their virtual networking environment with full o
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences