gangadhar r
gangadhar r

Reputation: 119

Travis CI for terraform which uses terraform lint for syntax checking

I have a Terraform template along with two tfvars files. We'd like to source control the Terraform code and want to run terraform lint in Travis-CI before we merge the code.

I'm a beginner in Travis, does anyone have an example of .travis.yml file which I can use in order to download Terraform and run terraform lint to check for syntax errors before merging the pull request?

Upvotes: 2

Views: 1323

Answers (1)

bdashrad
bdashrad

Reputation: 31

This will check any files changed between your branch and the target branch.

travis.yml:

sudo: false
cache:
  directories:
  - "${HOME}/bin"
env:
  global:
  - PATH="${HOME}/bin
  - TMPDIR="${TMPDIR:-/tmp}"
  - VERSION="0.11.0"
before_install:
  - if ! terraform version ; then
      mkdir -p "${HOME}/bin"
      pushd "${TMPDIR}" ;
      curl -sSL
        -o terraform.zip
        "https://releases.hashicorp.com/terraform/${VERSION}/terraform_${VERSION}_linux_amd64.zip" ;
      unzip terraform.zip ;
      mv -v terraform "${HOME}/bin/terraform" ;
      chmod +x "${HOME}/bin/terraform" ;
      popd ;
      terraform version ;
    fi
script:
  - test/check-fmt.sh

check_fmt.sh

#!/usr/bin/env bash

if [[ -z "$TRAVIS_PULL_REQUEST_BRANCH" ]]; then
  BRANCH="$TRAVIS_PULL_REQUEST_BRANCH"
else
  BRANCH="master"
fi

exitcode=0
for file in $(git diff --name-only $BRANCH | grep .tf\$); do
  if [[ "$(terraform fmt -write=false "$file" | wc -l)" -gt 0 ]]; then
    echo "ERROR: $file failed to pass terraform fmt"
    exitcode=1
  fi
done
exit $exitcode

Upvotes: 3

Related Questions