Deploying Grafana with Terraform
![Josh Pollara avatar](/_astro/avatar.7E_hpFOc_ZXR9OF.webp)
Josh Pollara
![Deploying Grafana with Terraform blog post](/_astro/deploying-grafana-with-terraform.9YzOeH-d_2fUf19.webp)
Introduction
Grafana is an open-source analytics and visualization platform used for monitoring and analyzing metrics and logs.
This tutorial provides a step by step guide on how to deploy Grafana to Kubernetes and AWS ECS using Terraform.
Deploying to Kubernetes
- Create a Kubernetes namespace
resource "kubernetes_namespace" "grafana" { metadata { name = "grafana" }}
- Create a Kubernetes deployment
resource "kubernetes_deployment" "grafana" { metadata { name = "grafana" namespace = kubernetes_namespace.grafana.metadata[0].name }
spec { selector { match_labels = { app = "grafana" } }
template { metadata { labels = { app = "grafana" } }
spec { container { image = "grafana/grafana:latest" name = "grafana"
port { container_port = 3000 } } } }
replicas = 1 }}
- Create a Kubernetes service
resource "kubernetes_service" "grafana" { metadata { name = "grafana" namespace = kubernetes_namespace.grafana.metadata[0].name }
spec { selector = { app = "grafana" }
port { name = "http" port = 80 target_port = 3000 }
type = "LoadBalancer" }}
- Apply the Terraform configuration
$ terraform init$ terraform apply
- Access Grafana
Once the apply command has completed, your Grafana service should be up and running on your Kubernetes cluster. You can access it by visiting the external IP of the LoadBalancer created by the service.
Deploying to AWS ECS
- Create an AWS ECS cluster
provider "aws" { region = "us-east-1"}
resource "aws_ecs_cluster" "grafana_cluster" { name = "grafana-cluster"}
- Create an ECS task definition
resource "aws_ecs_task_definition" "grafana" { family = "grafana" requires_compatibilities = ["FARGATE"] network_mode = "awsvpc"
container_definitions = jsonencode([ { name = "grafana" image = "grafana/grafana:latest" cpu = 256 memory = 512 essential = true portMappings = [ { containerPort = 3000 protocol = "tcp" }, ] logConfiguration = { logDriver = "awslogs" options = { "awslogs-group" = "/ecs/grafana" "awslogs-region" = "us-west-2" } } }, ])}
- Create an ECS service
resource "aws_ecs_service" "grafana" { name = "grafana" cluster = aws_ecs_cluster.grafana_cluster.id task_definition = aws_ecs_task_definition.grafana.arn desired_count = 1 launch_type = "FARGATE" network_configuration { subnets = ["subnet-12345678", "subnet-23456789"] security_groups = ["sg-12345678"] assign_public_ip = true }}
- Apply the Terraform configuration
$ terraform init$ terraform apply
- Access Grafana
Once the apply command has completed, you can access Grafana by finding the public IP address of the ECS service. Once you have the public IP address, you can navigate to it in your web browser, specifying port 3000.