Skip to content

Instantly share code, notes, and snippets.

@matschaffer
Last active October 29, 2016 04:48
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 matschaffer/a561ebccb5512f0edec3083d74544e0e to your computer and use it in GitHub Desktop.
Save matschaffer/a561ebccb5512f0edec3083d74544e0e to your computer and use it in GitHub Desktop.
terraform makefile base
include ../../../common/Makefile.base
.PHONY: all state modules clean clean-remote-state apply
state_profile ?= ...
state_region ?= ...
state_bucket ?= ...
state_prefix ?= terraform/tfstate
root ?= $(abspath $(lastword $(MAKEFILE_LIST))/../..)
name ?= $(subst $(root)/,,$(shell pwd))
region ?= $(notdir $(name))
profile ?= $(notdir $(patsubst %/,%,$(dir $(name))))
now := $(shell date +"%s")
all: state modules
state:
terraform remote config \
-backend=s3 \
-backend-config="bucket=$(state_bucket)" \
-backend-config="key=$(state_prefix)/$(name).tfstate" \
-backend-config="region=$(state_region)" \
-backend-config="profile=$(state_profile)"
modules:
terraform get -update
clean:
rm -rf .terraform
clean-remote-state:
aws s3 rm --region $(state_region) --profile $(state_profile) s3://$(state_bucket)/$(state_prefix)/$(name).tfstate
apply:
@terraform plan -detailed-exitcode -out=.terraform/$(now).tfplan || \
( case $$? in \
0) \
echo "No changes to apply" ;; \
1) \
false ;; \
2) \
read -r -p "Apply plan? (y/N): " CONFIRMATION && \
if [[ "$$CONFIRMATION" == "y" ]]; then \
terraform apply .terraform/$(now).tfplan; \
else \
echo "Not applying."; \
fi \
esac \
)
rm .terraform/$(now).tfplan
@matschaffer
Copy link
Author

it expects to be included from a sibling dir to where you keep your tf files as shown below.
so you may need to muck with the ..'s if you have your tree set up some other way
and the ...'s are our redacted state locations

.
├── common
│   ├── Makefile.base
├── helloworld
│   ├── account
│   │   ├── ap-northeast-2
│   │   │   ├── Makefile
│   │   │   └── main.tf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment