Terraform Format in CI

Install git and make in your terraform docker image:

# ------------------------------------------------------------------------------
# Packages

RUN set -exo pipefail             && \
                                     \
    echo 'Installing packages'    && \
    apk add --update --no-cache \
      git                       \
      make

Create a Makefile in your terraform directory containing:

.PHONY: init
init:
	@terraform init

.PHONY: fmt
fmt:
	@terraform fmt

.PHONY: validate
validate:
	@terraform validate

Set up your main Makefile with:

# Change this to your specific Terraform version, don't leave it `latest`!
TERRAFORM_VERSION := "latest"

# Running a docker container in the current directory.
DOCKER_HERE := docker run --rm -it -u `id -u`:`id -g` -v "$(PWD)":/here -w /here

.PHONY: ci/terraform
ci/terraform:
	@$(DOCKER_HERE) sdwolfz/terraform:$(TERRAFORM_VERSION) make lint/terraform

.PHONY: lint/terraform
lint/terraform:
	@make -C terraform --no-print-directory init fmt validate
	@git diff --exit-code

Now you can call it in your CI pipeline:

# ------------------------------------------------------------------------------
# CI
# ------------------------------------------------------------------------------

terraform:
  image: sdwolfz/terraform:latest
  script:
    - make lint/terraform

Or you can execute it on your local machine with:

make ci/terraform