TerraformPilot

Terraform

Install Terraform in Docker Containers

Run Terraform in Docker containers for consistent CI/CD environments. Official HashiCorp image, custom Dockerfiles, and Docker Compose workflows.

LLuca Berton1 min read

Quick Answer

#
docker run --rm -v $(pwd):/workspace -w /workspace hashicorp/terraform:1.8 init
docker run --rm -v $(pwd):/workspace -w /workspace hashicorp/terraform:1.8 plan
docker run --rm -v $(pwd):/workspace -w /workspace hashicorp/terraform:1.8 apply -auto-approve

Official HashiCorp Image

#
# Pull specific version
docker pull hashicorp/terraform:1.8
 
# Run with AWS credentials
docker run --rm \
  -v $(pwd):/workspace \
  -w /workspace \
  -e AWS_ACCESS_KEY_ID \
  -e AWS_SECRET_ACCESS_KEY \
  -e AWS_DEFAULT_REGION \
  hashicorp/terraform:1.8 plan

Custom Dockerfile

#
FROM hashicorp/terraform:1.8
 
# Add common tools
RUN apk add --no-cache \
    bash \
    curl \
    jq \
    python3 \
    py3-pip
 
# Install AWS CLI
RUN pip3 install awscli --break-system-packages
 
# Install tflint
RUN curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | bash
 
WORKDIR /workspace
ENTRYPOINT ["/bin/bash"]
docker build -t terraform-toolkit .
docker run --rm -it -v $(pwd):/workspace terraform-toolkit

Docker Compose Workflow

#
# docker-compose.yml
services:
  terraform:
    image: hashicorp/terraform:1.8
    working_dir: /workspace
    volumes:
      - .:/workspace
      - ~/.aws:/root/.aws:ro
    environment:
      - TF_LOG=${TF_LOG:-}
      - AWS_PROFILE=${AWS_PROFILE:-default}
    entrypoint: [""]
    command: ["sh", "-c", "terraform init && terraform plan"]
# Run specific commands
docker compose run --rm terraform terraform init
docker compose run --rm terraform terraform plan
docker compose run --rm terraform terraform apply

Multi-Cloud Dockerfile

#
FROM hashicorp/terraform:1.8 AS terraform
 
FROM python:3.12-alpine
COPY --from=terraform /bin/terraform /usr/local/bin/
 
RUN pip install \
    awscli \
    azure-cli && \
    apk add --no-cache bash curl jq
 
# Install gcloud CLI
RUN curl -sSL https://sdk.cloud.google.com | bash -s -- --disable-prompts
 
WORKDIR /workspace

CI/CD Usage (GitHub Actions)

#
jobs:
  terraform:
    runs-on: ubuntu-latest
    container:
      image: hashicorp/terraform:1.8
    steps:
      - uses: actions/checkout@v4
      - run: terraform init
      - run: terraform plan

Image Tags

#
TagDescription
hashicorp/terraform:1.8Specific minor version
hashicorp/terraform:1.8.5Specific patch version
hashicorp/terraform:latestLatest version
hashicorp/terraform:lightMinimal image
#

Conclusion

#

Docker provides consistent Terraform environments across local dev and CI/CD. Use the official hashicorp/terraform image with version pinning, mount your workspace and credentials, and build custom images when you need additional tools like AWS CLI or tflint.

#Terraform#Docker#DevOps#CI/CD#Install

Share this article