Skip to content

Instantly share code, notes, and snippets.

@j-thepac
Last active December 22, 2024 10:41
Show Gist options
  • Save j-thepac/e837155bee50e3bcce04a64876ba35ac to your computer and use it in GitHub Desktop.
Save j-thepac/e837155bee50e3bcce04a64876ba35ac to your computer and use it in GitHub Desktop.

TerraForm

  1. Create "n" nos of clould apps ,Online Apps , Link and Configure
  2. InfraStructure as Code (IAC)

Files Structure :

Pre-Req :

  • main.tf - Main File
  • dependencies.tf (depends_on) - Pre-Req
  • required_providers.tf - Download Interface communicate to target
  • providers.tf - Configure required_providers

Declaration :

  • variables.tf - Declare input paramters

  • terraform.auto.tfvars - Pass values to variables.tf

  • locals.tf - Local variables for internal Calculations

  • data.tf - Used to read from File

  • outputs.tf - Print Output

Operations

  1. data : get information from existing resources
  2. resource : Smallest operation which can be performed
  3. module : Function Call

Sample Code

Pre-Req: Docker is running locally

# Terraform Interface for Docker
terraform {
  required_providers {
    docker = { source = "kreuzwerker/docker" }
  }
}

# Use Default Config for above docker
provider "docker" {}

# Download nginx Image
resource "docker_image" "nginx" {
  name = "nginx"
}

# Define a map of container configurations
locals {
  containers = {
    c1 = { external_port = 8001 },
    c2 = { external_port = 8002 }
  }
}

# Create Nginx containers using a map
resource "docker_container" "nginx" {
  for_each = local.containers

  image = docker_image.nginx.image_id
  name  = each.key  # Unique name for each container

  ports {
    internal = 80
    external = each.value.external_port  # Use the external port from the map
  }
}

# Outputs
output "container_names" {
  value = [for c in docker_container.nginx : c.name]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment