# Terraform Configuration: Docker Service Deployment # =================================================== # This configuration manages Docker containers on localhost. # Designed for Tier 1+ agents to deploy services. # # For Tier 0 agents: Plan only (terraform plan) # # Usage: # terraform init # terraform plan -var="service_name=myapp" -var="image=nginx:alpine" # terraform apply # Tier 1+ only terraform { required_providers { docker = { source = "kreuzwerker/docker" version = "~> 3.0" } } } provider "docker" { host = "unix:///var/run/docker.sock" } # Variables variable "service_name" { description = "Name of the service/container" type = string default = "tf-managed-service" } variable "image" { description = "Docker image to deploy" type = string default = "nginx:alpine" } variable "internal_port" { description = "Container internal port" type = number default = 80 } variable "external_port" { description = "Host external port" type = number default = 8090 } variable "network_name" { description = "Docker network to attach" type = string default = "spark-net" } variable "environment" { description = "Environment variables for the container" type = map(string) default = {} } variable "labels" { description = "Labels to apply to the container" type = map(string) default = { "managed-by" = "terraform" "agent-tier" = "1" } } # Data source to reference existing network data "docker_network" "main" { name = var.network_name } # Pull the image resource "docker_image" "service" { name = var.image keep_locally = true } # Create the container resource "docker_container" "service" { name = var.service_name image = docker_image.service.image_id ports { internal = var.internal_port external = var.external_port } networks_advanced { name = data.docker_network.main.name } restart = "unless-stopped" dynamic "env" { for_each = var.environment content { key = env.key value = env.value } } labels { label = "managed-by" value = "terraform" } labels { label = "service-name" value = var.service_name } # Health check healthcheck { test = ["CMD", "wget", "-q", "--spider", "http://localhost:${var.internal_port}/"] interval = "30s" timeout = "10s" retries = 3 start_period = "10s" } lifecycle { create_before_destroy = true } } # Outputs output "container_id" { description = "The ID of the deployed container" value = docker_container.service.id } output "container_name" { description = "The name of the deployed container" value = docker_container.service.name } output "service_url" { description = "URL to access the service" value = "http://localhost:${var.external_port}" } output "network" { description = "Network the container is attached to" value = var.network_name }