-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackctl.sh
More file actions
executable file
·436 lines (349 loc) · 10.6 KB
/
stackctl.sh
File metadata and controls
executable file
·436 lines (349 loc) · 10.6 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env bash
set -euo pipefail
STARTED_SSH_AGENT=0
FORCE_FRESH_INSTALL=0
DELETE_WITH_DESTROY=0
VERBOSE=0
TF_PLAN="tfplan"
INVENTORY_DIR="inventory"
PLAYBOOK="site.yml"
usage() {
echo "Usage: $0 <stack-name> <command> [-f] [-d] [-v]"
echo
echo "Commands:"
echo " create Create stacks/<stack-name> scaffold"
echo " deploy Provision and configure stack"
echo " destroy Destroy stack infrastructure"
echo " delete Delete stack directory"
echo
echo "Options:"
echo " -f Force clean reinstall of Terraform/Ansible dependencies"
echo " -d (delete only) Destroy stack before delete"
echo " -v Show full Terraform/Ansible output"
echo " (for delete, -f only applies when -d is also set)"
}
die() {
echo "$1" >&2
exit 1
}
setup_ssh_agent() {
if [[ -z "${ssh_master_key_private:-}" ]]; then
return
fi
if [[ -z "${SSH_AUTH_SOCK:-}" ]] || ! ssh-add -l >/dev/null 2>&1; then
eval "$(ssh-agent -s)" >/dev/null
STARTED_SSH_AGENT=1
trap 'if [[ "${STARTED_SSH_AGENT}" == "1" ]] && [[ -n "${SSH_AGENT_PID:-}" ]]; then ssh-agent -k >/dev/null; fi' EXIT
fi
if ! ssh-add -l >/dev/null 2>&1; then
printf '%s\n' "${ssh_master_key_private}" | ssh-add - >/dev/null
fi
}
install_terraform() {
if ! command -v terraform &>/dev/null; then
echo "Terraform not found. Installing Terraform..."
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux installation
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common gpg
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg >/dev/null
gpg --no-default-keyring --keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg --fingerprint
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform
else
die "Unsupported OS type: $OSTYPE. Please install Terraform manually."
fi
fi
}
install_ansible() {
local repo_root="$1"
local force_fresh="$2"
local ve
ve=${VIRTUAL_ENV:-}
if [[ -z "${ve}" ]]; then
if [[ -d "${repo_root}/venv" ]]; then
echo "Activating existing python virtual environment..."
# shellcheck disable=SC1091
source "${repo_root}/venv/bin/activate"
else
echo "No python virtual environment detected. Creating a new virtual environment..."
python3 -m venv "${repo_root}/venv"
# shellcheck disable=SC1091
source "${repo_root}/venv/bin/activate"
fi
fi
echo "==> [PIP] Installing python dependencies from requirements.txt..."
if [[ "${force_fresh}" == "1" ]]; then
run_cmd pip3 install --upgrade --force-reinstall -r "${repo_root}/requirements.txt"
else
run_cmd pip3 install -r "${repo_root}/requirements.txt"
fi
}
load_env() {
local env_file="$1"
local -a env_keys=()
local var
while IFS= read -r var; do
env_keys+=("${var}")
done < <(grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "${env_file}" | sed -E 's/=.*$//')
set -a
# shellcheck disable=SC1090
source "${env_file}"
set +a
for var in "${env_keys[@]}"; do
if [[ "${var}" == TF_VAR_* ]]; then
continue
fi
export "TF_VAR_${var}=${!var-}"
done
}
load_stack_envs() {
local repo_root="$1"
local stack_dir="$2"
local global_env stack_env
global_env="${repo_root}/.env"
stack_env="${stack_dir}/.env"
# Load global defaults first, then allow component-level overrides.
if [[ -f "${global_env}" ]]; then
load_env "${global_env}"
fi
if [[ -f "${stack_env}" ]]; then
load_env "${stack_env}"
fi
}
run_cmd() {
local tmp_out rc
if [[ "${VERBOSE}" == "1" ]]; then
"$@"
return
fi
tmp_out="$(mktemp)"
if "$@" >"${tmp_out}" 2>&1; then
rm -f "${tmp_out}"
else
rc=$?
cat "${tmp_out}" >&2
rm -f "${tmp_out}"
return "${rc}"
fi
}
run_terraform_deploy() {
local force_fresh="$1"
local -a init_args=("-input=false")
if [[ "${force_fresh}" == "1" ]]; then
init_args+=("-upgrade")
fi
echo "==> [Terraform] Initializing providers and module dependencies..."
run_cmd terraform init "${init_args[@]}"
echo "==> [Terraform] Validating stack configuration..."
run_cmd terraform validate
echo "==> [Terraform] Building execution plan..."
run_cmd terraform plan -input=false -out="${TF_PLAN}"
echo "==> [Terraform] Applying planned infrastructure changes..."
run_cmd terraform apply "${TF_PLAN}"
}
run_ansible_configure() {
local repo_root="$1"
local force_fresh="$2"
local -a collection_args=("-r" "${repo_root}/requirements.yml")
if [[ "${force_fresh}" == "1" ]]; then
collection_args+=("--force")
fi
echo "==> [Ansible] Installing required collections..."
run_cmd ansible-galaxy collection install "${collection_args[@]}"
echo "==> [Ansible] Running playbook lint checks..."
run_cmd ansible-lint "${PLAYBOOK}"
echo "==> [Ansible] Executing stack playbook..."
run_cmd ansible-playbook -i "${INVENTORY_DIR}" "${PLAYBOOK}"
}
run_terraform_destroy() {
local force_fresh="$1"
local -a init_args=("-input=false")
if [[ "${force_fresh}" == "1" ]]; then
init_args+=("-upgrade")
fi
echo "==> [Terraform] Initializing providers and module dependencies..."
run_cmd terraform init "${init_args[@]}"
echo "==> [Terraform] Destroying stack infrastructure..."
run_cmd terraform destroy -input=false -auto-approve
}
resolve_stack_dir() {
local name="$1"
local repo_root
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "${repo_root}/stacks/${name}"
}
cleanup_stack_temp_files() {
local stack_dir="$1"
echo "==> Fresh cleanup"
rm -rf \
"${stack_dir}/.terraform" \
"${stack_dir}/.ansible"
rm -f \
"${stack_dir}/${TF_PLAN}" \
"${stack_dir}/.terraform.lock.hcl"
}
create_file() {
local target="$1"
local content="${2:-}"
if [[ -e "${target}" ]]; then
return
fi
if [[ -n "${content}" ]]; then
printf '%s\n' "${content}" >"${target}"
else
: >"${target}"
fi
}
validate_stack_name() {
local name="$1"
if [[ -z "${name}" ]]; then
die "Stack name cannot be empty."
fi
if [[ ! "${name}" =~ ^[a-zA-Z0-9._-]+$ ]] || [[ "${name}" == .* ]] || [[ "${name}" == *..* ]]; then
die "Invalid stack name '${name}'. Use letters, numbers, '.', '_' or '-' only."
fi
}
create_stack() {
local name="$1"
local repo_root ansible_root terraform_root stack_dir shared_playbook
validate_stack_name "${name}"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ansible_root="${repo_root}/shared/ansible"
terraform_root="${repo_root}/shared/terraform"
stack_dir="${repo_root}/stacks/${name}"
shared_playbook="${ansible_root}/site.yml"
[[ -d "${ansible_root}" ]] || die "Missing directory: ${ansible_root}"
[[ -d "${terraform_root}" ]] || die "Missing directory: ${terraform_root}"
[[ -f "${ansible_root}/ansible.cfg" ]] || die "Missing file: ${ansible_root}/ansible.cfg"
[[ -f "${shared_playbook}" ]] || die "Missing file: ${shared_playbook}"
mkdir -p "${stack_dir}"
# Link shared directories and Terraform files from repo root.
ln -sfn "../../shared/ansible/inventory" "${stack_dir}/inventory"
ln -sfn "../../shared/ansible/roles" "${stack_dir}/roles"
ln -sfn "../../shared/ansible/ansible.cfg" "${stack_dir}/ansible.cfg"
ln -sfn "../../shared/terraform/modules" "${stack_dir}/modules"
ln -sfn "../../shared/terraform/versions.tf" "${stack_dir}/common.versions.tf"
ln -sfn "../../shared/terraform/providers.tf" "${stack_dir}/common.providers.tf"
ln -sfn "../../shared/terraform/locals.tf" "${stack_dir}/common.locals.tf"
ln -sfn "../../shared/terraform/variables.tf" "${stack_dir}/common.variables.tf"
create_file "${stack_dir}/main.tf"
#create_file "${stack_dir}/outputs.tf"
#create_file "${stack_dir}/variables.tf"
#create_file "${stack_dir}/locals.tf"
#create_file "${stack_dir}/versions.tf"
#create_file "${stack_dir}/providers.tf"
create_file "${stack_dir}/site.yml" "$(<"${shared_playbook}")"
create_file "${stack_dir}/.env"
echo "Created stack ${name} at ${stack_dir}"
}
deploy_stack() {
local name="$1"
local repo_root stack_dir
validate_stack_name "${name}"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
stack_dir="$(resolve_stack_dir "${name}")"
[[ -d "${stack_dir}" ]] || die "Missing stack directory: ${stack_dir}"
[[ -f "${repo_root}/requirements.txt" ]] || die "Missing file: ${repo_root}/requirements.txt"
[[ -f "${repo_root}/requirements.yml" ]] || die "Missing file: ${repo_root}/requirements.yml"
if [[ "${FORCE_FRESH_INSTALL}" == "1" ]]; then
cleanup_stack_temp_files "${stack_dir}"
fi
load_stack_envs "${repo_root}" "${stack_dir}"
setup_ssh_agent
install_terraform
install_ansible "${repo_root}" "${FORCE_FRESH_INSTALL}"
pushd "${stack_dir}" >/dev/null
run_terraform_deploy "${FORCE_FRESH_INSTALL}"
run_ansible_configure "${repo_root}" "${FORCE_FRESH_INSTALL}"
popd >/dev/null
}
destroy_stack() {
local name="$1"
local repo_root stack_dir
validate_stack_name "${name}"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
stack_dir="$(resolve_stack_dir "${name}")"
[[ -d "${stack_dir}" ]] || die "Missing stack directory: ${stack_dir}"
if [[ "${FORCE_FRESH_INSTALL}" == "1" ]]; then
cleanup_stack_temp_files "${stack_dir}"
fi
load_stack_envs "${repo_root}" "${stack_dir}"
setup_ssh_agent
install_terraform
pushd "${stack_dir}" >/dev/null
run_terraform_destroy "${FORCE_FRESH_INSTALL}"
popd >/dev/null
}
delete_stack() {
local name="$1"
local stack_dir
validate_stack_name "${name}"
stack_dir="$(resolve_stack_dir "${name}")"
[[ -d "${stack_dir}" ]] || die "Missing stack directory: ${stack_dir}"
if [[ "${DELETE_WITH_DESTROY}" == "1" ]]; then
echo "Destroying stack '${name}' before delete..."
# For delete flow, -f takes effect only when -d is also set.
destroy_stack "${name}"
fi
rm -rf "${stack_dir}"
echo "Deleted stack ${name} at ${stack_dir}"
}
parse_command_options() {
local arg
for arg in "$@"; do
case "${arg}" in
-f)
FORCE_FRESH_INSTALL=1
;;
-v)
VERBOSE=1
;;
-d)
DELETE_WITH_DESTROY=1
;;
*)
# Ignore unsupported options.
;;
esac
done
}
main() {
local name="${1:-}"
local command="${2:-}"
local action
if [[ -z "${name}" ]]; then
usage
exit 1
fi
case "${name}" in
-h | --help | help)
usage
exit 0
;;
esac
[[ -n "${command}" ]] || die "Missing command for stack '${name}'."
case "${command}" in
-h | --help | help)
usage
return 0
;;
create)
action="create_stack"
;;
deploy)
action="deploy_stack"
;;
destroy)
action="destroy_stack"
;;
delete)
action="delete_stack"
;;
*)
die "Unknown command '${command}'."
;;
esac
parse_command_options "${@:3}"
"${action}" "${name}"
}
main "$@"