Skip to content

Instantly share code, notes, and snippets.

@nwillems
Last active July 25, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwillems/cde8953edfa38f306bb36ed3cc8adb40 to your computer and use it in GitHub Desktop.
Save nwillems/cde8953edfa38f306bb36ed3cc8adb40 to your computer and use it in GitHub Desktop.
Terraform wrapper script to run inside of a docker container

Run terraform in a container!

This file should just be in your path and your terraform codebase located in a folder called terraform. Then just run it like this:

terraformw init
terraformw plan -out plan.tfplan
terraformw apply plan.tfplan

Note that your AWS credentials should be in $HOME/.aws/credentials, but I guess they already are :-)

The script will ensure that the whole terraform codebase is mounted inside the container, under /app. It will then change the working directory in the container, to be the current host directory relative to the first occurence of a folder called terraform. See expected code structure below.

/code/project-foo/terraform <- folder
/code/project-foo/terraform/common <- example of module used
/code/project-foo/terraform/awesome-stack <- configuration of instances

The from within awesome-stack you can run terraformw, and the container will have /code/project-foo/terraform mounted on /app and then change working directory to be /app/awesome-stack and run terraform from there.

#!/usr/bin/env python3
from os import getcwd,getenv
from os.path import normpath, sep, join
from itertools import takewhile
from subprocess import run
from sys import argv
def main(args):
home = getenv("HOME")
# Figure working directory
cwd = getcwd()
normalized_cwd = normpath(cwd)
# Figure base path
cwd_parts = normalized_cwd.split(sep)
condition = lambda x: x != "terraform"
base_path = join( sep.join( takewhile(condition, cwd_parts) ), "terraform")
# Start docker container
workdirectory = normalized_cwd[len(base_path)+1:]
run([
"docker", "run", "--rm", "-it",
"-e", "AWS_SHARED_CREDENTIALS_FILE=/aws_credentials",
"-v", "{}/.aws/credentials:/aws_credentials".format(home),
"-v", "{}:/app/".format(base_path),
"-w", "/app/{}".format(workdirectory),
"hashicorp/terraform:light"] + args
)
if __name__ == "__main__":
main(argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment