Working with Terraform and Makefile

Personal basic Makefile for usage with Terraform project. It will automate some terraform chain commands such as plan, apply, format, clean.

For years Makefile was (and still is the best) in building tools which runs on Unix, Linux, and their flavors.

For that reason i thought to publish my Makefile for working with Terraform project, that might help you in your next project

This assumes 2 thinks. You are working with a local tfstate file and that you will put the Makefile in the same directory as the *.tf files, just to be sure :D



all: plan
	@echo "Usage: make plan"
	@echo "After applying terraform plan it prompt if to apply the changes."
	@echo "Other commands: "
	@echo " * make show - to list what the plan will apply "
	@echo " * make clean - delete the executed plan, so no files left behind "
	@echo " * make get - update the teffarom modules"
	@echo " * make format - execute terraform fmt"
	rm -f /tmp/plan_stg
	@echo "Updating modules"
	@terraform get -update
plan: format get
	@echo "Checking Infrastracture"
	@terraform plan -parallelism=80 -refresh=true -module-depth=-1 -out /tmp/plan_stg
	$(MAKE) confirm
	$(MAKE) apply
	@echo "Showing plan to apply"
	@terraform show /tmp/plan_stg
	@echo "Format existing code"
	@terraform fmt
	@echo "Applying changes to Infrastracture"
	@terraform apply -parallelism=80 /tmp/plan_stg
	@echo "Clean up after myself"
	$(MAKE) clean
	read -r -t 5 -p "Type y to apply, otherwise it will abort (timeout in 5 seconds): " CONTINUE; \
	if [ ! $$CONTINUE == "y" ] || [ -z $$CONTINUE ]; then \
	    echo "Abort apply." ; \
		exit 1; \

So now you can run commands such as make plan or make format

This is pretty basic Makefile but works pretty well in my projects.

Alexandros Sapranidis

Software engineer, keen on wearing many hat, current Senior Software Engineer @Elastic cloud

Athens, Greece