logo
5
0
WeChat Login

Terraform Hello World Example

In this example, you'll use Cloud Native Build (CNB) to implement infrastructure management with Terraform and Docker.

Prerequisites

  1. Basic knowledge of Terraform including concepts and commands like:
    • terraform init
    • terraform plan
    • terraform apply
    • terraform destroy
  2. Use Cloud Native Build (CNB) to manage your Terraform configurations for version control and collaborative development.

Example Configuration Review

The main.tf file in the root directory defines Docker container resources:

  1. Pulls the nginx:latest image
  2. Creates a container exposing port 8000 mapped to port 80
terraform {
  required_providers {
    docker = {
      source = "kreuzwerker/docker"
      version = "~> 3.0.1"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name         = "nginx:latest"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "tutorial"
  ports {
    internal = 80
    external = 8000
  }
}

Infrastructure Creation

Using Cloud Native Build for Terraform Deployment

master:
  push:
    - name: Terraform by Example
      services:
        - docker
      docker:
        image: hashicorp/terraform
      stages:
        - name: docker image ls
          script: docker image ls
        - name: docker ps
          script: docker ps
        - name: init
          script: terraform init
        - name: plan
          script: terraform plan
        - name: apply
          script: terraform apply -auto-approve
        - name: docker image ls
          script: docker image ls
        - name: docker ps
          script: docker ps

Pipeline execution results: Execution Example 1 Execution Example 2 Created Container

Cloud Native Development Environment

Create a Terraform-ready development environment with .ide/Dockerfile:

FROM hashicorp/terraform as tf

FROM node:20

# Install vscode and extensions
RUN curl -fsSL https://code-server.dev/install.sh | sh &&\
    code-server --install-extension hashicorp.terraform &&\
    echo done

COPY --from=tf /bin/terraform /usr/local/bin/terraform

Click "Cloud Native Development" to create a web-based development environment:

Cloud Dev Environment

Execute Terraform commands directly in the environment:

Terraform Commands

About

通过云原生构建实现,使用 terraform 来管理你的 Docker 容器。

terraformexample
Language
Markdown74.9%
gitignore13.1%
Terraform8.5%
Dockerfile3.5%