-
Notifications
You must be signed in to change notification settings - Fork 4
/
terraform-apply.sh
executable file
·91 lines (78 loc) · 2.46 KB
/
terraform-apply.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/bin/bash
# vim: set ft=sh
set -eux
if [ "$TERRAFORM_ACTION" != "plan" ] && \
[ "$TERRAFORM_ACTION" != "apply" ]; then
echo 'must set $TERRAFORM_ACTION to "plan" or "apply"' >&2
exit 1
fi
TERRAFORM="${TERRAFORM_BIN:-terraform}"
BASE="$(pwd)"
DIR="terraform-templates"
set +x
# unset TF_VARs that are empty strings
for tfvar in "${!TF_VAR_@}"; do
if [[ -z "${!tfvar}" ]]; then
unset ${tfvar}
fi
done
set -x
if [ -n "${TEMPLATE_SUBDIR:-}" ]; then
DIR="${DIR}/${TEMPLATE_SUBDIR}"
fi
${TERRAFORM} -chdir=${DIR} get \
-update
init_args=(
"-backend=true"
"-backend-config=encrypt=true"
"-backend-config=bucket=${S3_TFSTATE_BUCKET}"
"-backend-config=key=${STACK_NAME}/terraform.tfstate"
)
set +x
if [ -n "${TF_VAR_aws_region:-}" ]; then
init_args+=("-backend-config=region=${TF_VAR_aws_region}")
fi
if [ -n "${TF_VAR_aws_access_key:-}" ]; then
init_args+=("-backend-config=access_key=${TF_VAR_aws_access_key}")
fi
if [ -n "${TF_VAR_aws_secret_key:-}" ]; then
init_args+=("-backend-config=secret_key=${TF_VAR_aws_secret_key}")
fi
${TERRAFORM} -chdir="${DIR}" init \
"${init_args[@]}"
set -x
if [ "${TERRAFORM_ACTION}" = "plan" ]; then
${TERRAFORM} -chdir="${DIR}" "${TERRAFORM_ACTION}" \
-refresh=true \
-input=false \
-out=${BASE}/terraform-state/terraform.tfplan \
> ${BASE}/terraform-state/terraform-plan-output.txt
cat ${BASE}/terraform-state/terraform-plan-output.txt
# Write a sentinel value; pipelines can alert to slack if set using `text_file`
# Ensure that slack notification resource detects text file
touch ${BASE}/terraform-state/message.txt
if ! cat ${BASE}/terraform-state/terraform-plan-output.txt | grep 'No changes.' ; then
echo "sentinel" > ${BASE}/terraform-state/message.txt
fi
else
# run apply twice to work around bugs like this
# https://github.com/hashicorp/terraform/issues/7235
${TERRAFORM} -chdir="${DIR}" "${TERRAFORM_ACTION}" \
-refresh=true \
-input=false \
-auto-approve
${TERRAFORM} -chdir="${DIR}" "${TERRAFORM_ACTION}" \
-refresh=true \
-input=false \
-auto-approve
if [ -n "${TF_VAR_aws_region:-}" ]; then
export AWS_DEFAULT_REGION="${TF_VAR_aws_region}"
fi
if [ -n "${TF_VAR_aws_access_key:-}" ]; then
export AWS_ACCESS_KEY_ID="${TF_VAR_aws_access_key}"
fi
if [ -n "${TF_VAR_aws_secret_key:-}" ]; then
export AWS_SECRET_ACCESS_KEY="${TF_VAR_aws_secret_key}"
fi
aws s3 cp "s3://${S3_TFSTATE_BUCKET}/${STACK_NAME}/terraform.tfstate" terraform-state
fi