-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster.sh
More file actions
executable file
·400 lines (348 loc) · 11.5 KB
/
Copy pathcluster.sh
File metadata and controls
executable file
·400 lines (348 loc) · 11.5 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
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
check_prerequisites() {
local missing=0
if command -v terraform >/dev/null 2>&1; then
TF_CMD="terraform"
elif command -v tofu >/dev/null 2>&1; then
TF_CMD="tofu"
else
echo "Error: Neither terraform nor tofu CLI found."
echo "Install terraform from https://www.terraform.io/downloads"
echo " or tofu from https://opentofu.org/docs/intro/install"
missing=1
fi
if ! command -v kubectl >/dev/null 2>&1; then
echo "Error: kubectl not found. Install from https://kubernetes.io/docs/tasks/tools/"
missing=1
fi
if ! command -v gcloud >/dev/null 2>&1; then
echo "Error: gcloud CLI not found. Install from https://cloud.google.com/sdk/docs/install"
missing=1
fi
if [[ $missing -eq 0 ]] && ! gcloud auth application-default print-access-token >/dev/null 2>&1; then
echo "Error: Application Default Credentials not configured."
echo "Run: gcloud auth application-default login"
missing=1
fi
if [[ $missing -ne 0 ]]; then
exit 1
fi
}
check_prerequisites
TF_VARS=()
if [[ -n "${GCP_PROJECT_ID:-}" ]]; then
TF_VARS+=(-var "project_id=${GCP_PROJECT_ID}")
fi
usage() {
echo "Usage: $0 <action> <config-path> [--private-networking]"
echo ""
echo "Actions:"
echo " up Create the cluster"
echo " down Destroy the cluster"
echo " info Print connection details for an existing cluster"
echo " specs Print effective cluster specs (no running cluster required)"
echo ""
echo "Options:"
echo " --private-networking Enable private networking (PSC on GCP, equivalent on other platforms)"
echo ""
echo "Config path: <sources|targets>/<platform>/<config>"
echo ""
echo "Examples:"
echo " $0 up sources/gcp/elasticsearch-gke"
echo " $0 up targets/gcp/opensearch-gke --private-networking"
echo " $0 info targets/gcp/opensearch-gke"
echo " $0 down sources/gcp/elasticsearch-gke"
echo ""
echo "Available source configs:"
find "${SCRIPT_DIR}/sources" -name "terraform.tfvars.example" 2>/dev/null | while read -r f; do
dir="$(dirname "$(dirname "$f")")"
echo " ${dir#"${SCRIPT_DIR}/"}"
done
echo ""
echo "Available target configs:"
find "${SCRIPT_DIR}/targets" -name "terraform.tfvars.example" 2>/dev/null | while read -r f; do
dir="$(dirname "$(dirname "$f")")"
echo " ${dir#"${SCRIPT_DIR}/"}"
done
echo ""
exit 1
}
[[ $# -lt 2 ]] && usage
ACTION="$1"
CONFIG_PATH="$2"
PRIVATE_NETWORKING=false
for arg in "${@:3}"; do
case "$arg" in
--private-networking) PRIVATE_NETWORKING=true ;;
*) echo "Error: unknown option: $arg"; usage ;;
esac
done
if [[ "$PRIVATE_NETWORKING" == "true" ]]; then
TF_VARS+=(-var "enable_psc=true")
fi
CONFIG_DIR="${SCRIPT_DIR}/${CONFIG_PATH}"
TF_DIR="${CONFIG_DIR}/terraform"
CLUSTER_ROLE="$(echo "$CONFIG_PATH" | cut -d/ -f1)"
PLATFORM="$(echo "$CONFIG_PATH" | cut -d/ -f2)"
CONFIG_NAME="$(echo "$CONFIG_PATH" | cut -d/ -f3)"
if [[ ! -d "$TF_DIR" ]]; then
echo "Error: terraform directory not found at ${TF_DIR}"
exit 1
fi
disconnect() {
case "$PLATFORM" in
gcp)
local cluster_name location project_id context
cluster_name="$($TF_CMD -chdir="$TF_DIR" output -raw cluster_name 2>/dev/null)" || return 0
location="$($TF_CMD -chdir="$TF_DIR" output -raw location 2>/dev/null)" || return 0
project_id="$($TF_CMD -chdir="$TF_DIR" output -raw project_id 2>/dev/null)" || return 0
context="gke_${project_id}_${location}_${cluster_name}"
echo "Removing kubectl context: ${context}"
kubectl config delete-context "$context" 2>/dev/null || true
;;
aws)
local cluster_name region context
cluster_name="$($TF_CMD -chdir="$TF_DIR" output -raw cluster_name 2>/dev/null)" || return 0
region="$($TF_CMD -chdir="$TF_DIR" output -raw region 2>/dev/null)" || return 0
context="arn:aws:eks:${region}:*:cluster/${cluster_name}"
echo "Removing kubectl context: ${context}"
kubectl config delete-context "$context" 2>/dev/null || true
;;
esac
}
connect() {
local cluster_name location project_id
cluster_name="$($TF_CMD -chdir="$TF_DIR" output -raw cluster_name)"
location="$($TF_CMD -chdir="$TF_DIR" output -raw location)"
project_id="$($TF_CMD -chdir="$TF_DIR" output -raw project_id)"
case "$PLATFORM" in
gcp)
gcloud container clusters get-credentials "$cluster_name" \
--location "$location" --project "$project_id" --quiet
;;
esac
}
wait_for_lb_ip() {
local svc="$1"
local timeout="${2:-300}"
local elapsed=0
local interval=5
local ip=""
while [[ $elapsed -lt $timeout ]]; do
ip="$(kubectl get svc "$svc" -o jsonpath='{.status.loadBalancer.ingress[0].ip}' 2>/dev/null || true)"
if [[ -n "$ip" ]]; then
echo "$ip"
return 0
fi
if [[ $elapsed -eq 0 ]]; then
echo "Waiting for LoadBalancer IP on service ${svc}..." >&2
fi
sleep "$interval"
elapsed=$((elapsed + interval))
done
echo "pending"
return 1
}
wait_for_psc_uri() {
local attachment_name="$1"
local timeout="${2:-300}"
local elapsed=0
local interval=5
local uri=""
while [[ $elapsed -lt $timeout ]]; do
uri="$(kubectl get serviceattachment "$attachment_name" -o jsonpath='{.status.serviceAttachmentURL}' 2>/dev/null || true)"
if [[ -n "$uri" ]]; then
echo "$uri"
return 0
fi
if [[ $elapsed -eq 0 ]]; then
echo "Waiting for PSC service attachment URI on ${attachment_name}..." >&2
fi
sleep "$interval"
elapsed=$((elapsed + interval))
done
echo "pending"
return 1
}
print_info() {
if ! $TF_CMD -chdir="$TF_DIR" output -raw cluster_name >/dev/null 2>&1; then
echo ""
echo "Cluster not found. No terraform state exists for this config."
exit 1
fi
if ! connect 2>/dev/null; then
echo ""
echo "Cluster not found. It may have been torn down."
exit 1
fi
local ip user password
local psc_uri=""
case "$CONFIG_NAME" in
elasticsearch-gke)
ip="$(wait_for_lb_ip es-source-es-http)" || true
user="elastic"
password="$(kubectl get secret es-source-es-elastic-user -o jsonpath='{.data.elastic}' 2>/dev/null | base64 -d)" || password="pending"
[[ -z "$password" ]] && password="pending"
if [[ "$($TF_CMD -chdir="$TF_DIR" output -raw psc_enabled 2>/dev/null)" == "true" ]]; then
psc_uri="$(wait_for_psc_uri es-source-psc)" || true
fi
;;
opensearch-gke)
ip="$(wait_for_lb_ip os-target-external)" || true
user="admin"
password="$($TF_CMD -chdir="$TF_DIR" output -raw cluster_password)"
if [[ "$($TF_CMD -chdir="$TF_DIR" output -raw psc_enabled 2>/dev/null)" == "true" ]]; then
psc_uri="$(wait_for_psc_uri os-target-psc)" || true
fi
;;
esac
local software
software="$($TF_CMD -chdir="$TF_DIR" output -raw software)"
echo ""
echo "============================================"
echo " Cluster Ready"
echo "============================================"
echo "Software: ${software}"
echo "IP: ${ip}"
echo "User: ${user}"
echo "Password: ${password}"
if [[ -n "$psc_uri" ]]; then
echo "PSC URI: ${psc_uri}"
fi
echo "============================================"
}
validate_private_networking() {
echo "Validating private networking configuration..."
if ! $TF_CMD -chdir="$TF_DIR" validate -no-color ${TF_VARS[@]+"${TF_VARS[@]}"} >/dev/null; then
echo "Error: Terraform validation failed. Check your terraform.tfvars."
exit 1
fi
local consumer_ids
consumer_ids="$(get_tfvars_value "${TF_DIR}/terraform.tfvars" "psc_consumer_project_ids" 2>/dev/null || true)"
if [[ -z "$consumer_ids" ]]; then
echo "Warning: psc_consumer_project_ids is not set in terraform.tfvars."
echo " The service attachment will be created with no authorized consumers."
echo " You will need to authorize the migration project separately."
echo ""
fi
}
do_up() {
echo "Initializing Terraform..."
$TF_CMD -chdir="$TF_DIR" init
if [[ "$PRIVATE_NETWORKING" == "true" ]]; then
echo ""
validate_private_networking
fi
echo ""
echo "Creating cluster..."
$TF_CMD -chdir="$TF_DIR" apply -auto-approve ${TF_VARS[@]+"${TF_VARS[@]}"}
print_info
}
do_down() {
if ! $TF_CMD -chdir="$TF_DIR" output -raw cluster_name >/dev/null 2>&1; then
echo ""
echo "Nothing to destroy. No terraform state exists for this config."
exit 0
fi
disconnect
local network project_id
network="$($TF_CMD -chdir="$TF_DIR" state show 'module.cluster.google_compute_network.main' 2>/dev/null | awk -F'"' '/^\s*name\s*=/{print $2}')"
project_id="$($TF_CMD -chdir="$TF_DIR" state show 'module.cluster.google_compute_network.main' 2>/dev/null | awk -F'"' '/^\s*project\s*=/{print $2}')"
if [[ -n "$network" && -n "$project_id" ]]; then
echo "Cleaning up GKE-managed firewall rules for network ${network}..."
gcloud compute firewall-rules list --filter="network=${network}" --format="value(name)" --project="$project_id" | \
xargs -n1 gcloud compute firewall-rules delete --quiet --project="$project_id" || true
fi
echo "Destroying cluster..."
$TF_CMD -chdir="$TF_DIR" destroy -auto-approve ${TF_VARS[@]+"${TF_VARS[@]}"}
echo ""
echo "Cluster destroyed."
}
do_info() {
print_info
}
get_var_default() {
local varfile="$1" varname="$2"
awk -v name="$varname" '
$0 ~ "variable \"" name "\"" { found=1 }
found && /default[[:space:]]*=/ {
sub(/.*default[[:space:]]*=[[:space:]]*/, "")
gsub(/^"/, ""); gsub(/"$/, "")
gsub(/^[[:space:]]+|[[:space:]]+$/, "")
print
exit
}
found && /^\}/ { exit }
' "$varfile"
}
get_tfvars_value() {
local tfvars="$1" varname="$2"
awk -v name="$varname" '
$0 ~ "^"name"[[:space:]]*=" {
sub(/.*=[[:space:]]*/, "")
gsub(/^"/, ""); gsub(/"$/, "")
gsub(/^[[:space:]]+|[[:space:]]+$/, "")
print
exit
}
' "$tfvars"
}
get_effective() {
local varname="$1"
local val=""
if [[ -f "${TF_DIR}/terraform.tfvars" ]]; then
val="$(get_tfvars_value "${TF_DIR}/terraform.tfvars" "$varname")"
fi
if [[ -z "$val" ]]; then
val="$(get_var_default "${TF_DIR}/variables.tf" "$varname")"
fi
echo "$val"
}
do_specs() {
local region zone machine_type node_count disk_size_gb software_version
region="$(get_effective region)"
zone="$(get_effective zone)"
machine_type="$(get_effective machine_type)"
node_count="$(get_effective node_count)"
disk_size_gb="$(get_effective disk_size_gb)"
local software_label software_version_var
case "$CONFIG_NAME" in
elasticsearch-gke)
software_label="Elasticsearch"
software_version="$(get_effective elasticsearch_version)"
;;
opensearch-gke)
software_label="OpenSearch"
software_version="$(get_effective opensearch_version)"
;;
*)
software_label="Unknown"
software_version="n/a"
;;
esac
local location
if [[ -n "$zone" && "$zone" != "null" ]]; then
location="$zone (zonal)"
else
location="$region (regional)"
fi
echo ""
echo "============================================"
echo " Cluster Specs"
echo "============================================"
echo "Software: ${software_label} ${software_version}"
echo "Location: ${location}"
echo "Machine type: ${machine_type}"
echo "Node count: ${node_count}"
echo "Disk size: ${disk_size_gb} GB"
echo "============================================"
}
case "$ACTION" in
up) do_up ;;
down) do_down ;;
info) do_info ;;
specs) do_specs ;;
*) usage ;;
esac