Repository navigation
305 lines (285 loc) · 14 KB
/
Copy pathcd.yml
File metadata and controls
305 lines (285 loc) · 14 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
name: CloudMonitor CD — Deploy to AWS EC2 via SSM
# Manual-only during migration. Re-enable push-to-main only after SSM is verified.
on:
workflow_dispatch:
inputs:
operation:
description: "Choose OIDC check, SSM preflight, deploy, or rollback"
required: true
type: choice
options: [oidc-check, ssm-preflight, deploy, rollback]
default: oidc-check
confirm_production:
description: "Required for production deploy and rollback"
required: false
type: boolean
default: false
permissions:
contents: read
concurrency:
group: cloudmonitor-production-deployment
cancel-in-progress: false
jobs:
ssm:
name: CloudMonitor Production — SSM
runs-on: ubuntu-latest
environment: production
timeout-minutes: 35
permissions:
contents: read
id-token: write
env:
AWS_REGION: ap-southeast-2
AWS_ACCOUNT_ID: ${{ vars.AWS_ACCOUNT_ID }}
AWS_DEPLOY_ROLE_ARN: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
EC2_INSTANCE_ID: ${{ vars.EC2_INSTANCE_ID }}
OPERATION: ${{ inputs.operation }}
CONFIRM_PRODUCTION: ${{ inputs.confirm_production }}
steps:
- name: Validate requested operation and configuration
shell: bash
run: |
set -euo pipefail
case "$OPERATION" in
oidc-check|ssm-preflight|deploy|rollback) ;;
*) echo "::error::Unsupported operation."; exit 1 ;;
esac
if [[ "$OPERATION" == "deploy" || "$OPERATION" == "rollback" ]] && [[ "$CONFIRM_PRODUCTION" != "true" ]]; then
echo "::error::Set confirm_production=true for production deploy/rollback."
exit 1
fi
if [[ "$OPERATION" != "oidc-check" ]]; then
for name in AWS_ACCOUNT_ID AWS_DEPLOY_ROLE_ARN EC2_INSTANCE_ID; do
if [[ -z "${!name}" ]]; then
echo "::error::Missing GitHub Environment variable: $name (environment: production)."
exit 1
fi
done
[[ "$AWS_ACCOUNT_ID" =~ ^[0-9]{12}$ ]] || { echo "::error::AWS_ACCOUNT_ID must be 12 digits."; exit 1; }
[[ "$EC2_INSTANCE_ID" =~ ^i-[0-9a-f]{8,17}$ ]] || { echo "::error::Invalid EC2_INSTANCE_ID."; exit 1; }
case "$AWS_DEPLOY_ROLE_ARN" in
"arn:aws:iam::${AWS_ACCOUNT_ID}:role/"*) ;;
*) echo "::error::AWS_DEPLOY_ROLE_ARN does not match AWS_ACCOUNT_ID."; exit 1 ;;
esac
fi
- name: Inspect OIDC claims (token value is never logged)
shell: bash
run: |
set -euo pipefail
python3 - <<'PY'
import base64, json, os, urllib.request
url = os.environ["ACTIONS_ID_TOKEN_REQUEST_URL"] + "&audience=sts.amazonaws.com"
request = urllib.request.Request(url, headers={
"Authorization": f"bearer {os.environ['ACTIONS_ID_TOKEN_REQUEST_TOKEN']}"
})
with urllib.request.urlopen(request, timeout=15) as response:
token = json.load(response)["value"]
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload))
print("OIDC issuer:", claims.get("iss"))
print("OIDC audience:", claims.get("aud"))
print("OIDC subject:", claims.get("sub"))
if claims.get("iss") != "https://token.actions.githubusercontent.com":
raise SystemExit("Unexpected OIDC issuer.")
aud = claims.get("aud")
if aud != "sts.amazonaws.com" and not (isinstance(aud, list) and "sts.amazonaws.com" in aud):
raise SystemExit("Unexpected OIDC audience.")
PY
- name: Configure AWS credentials using GitHub OIDC
uses: aws-actions/configure-aws-credentials@v6.3.0
with:
role-to-assume: ${{ env.AWS_DEPLOY_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
role-session-name: CloudMonitor-SSM-${{ github.run_id }}
allowed-account-ids: ${{ env.AWS_ACCOUNT_ID }}
- name: Verify AWS role assumption and optional SSM managed-node status
shell: bash
run: |
set -euo pipefail
ACTUAL_ACCOUNT="$(aws sts get-caller-identity --query Account --output text)"
[[ "$ACTUAL_ACCOUNT" == "$AWS_ACCOUNT_ID" ]] || { echo "::error::Unexpected AWS account."; exit 1; }
ACTUAL_ARN="$(aws sts get-caller-identity --query Arn --output text)"
echo "GitHub OIDC successfully assumed the configured AWS role: $ACTUAL_ARN"
if [[ "$OPERATION" != "oidc-check" ]]; then
PING_STATUS="$(aws ssm describe-instance-information \
--filters "Key=InstanceIds,Values=${EC2_INSTANCE_ID}" \
--query 'InstanceInformationList[0].PingStatus' --output text)"
[[ "$PING_STATUS" == "Online" ]] || {
echo "::error::EC2 is not Online in SSM (status: $PING_STATUS). Fix instance role, SSM Agent, and outbound HTTPS before deploying."
exit 1
}
echo "EC2 is Online in Systems Manager."
fi
- name: Run SSM preflight, deployment, or rollback
if: inputs.operation != 'oidc-check'
shell: bash
run: |
set -euo pipefail
case "$OPERATION" in
ssm-preflight)
REMOTE_SCRIPT="$(cat <<'REMOTE'
set -Eeuo pipefail
DEPLOY_DIR="/home/ubuntu/cloud_monitor"
test -d "$DEPLOY_DIR"
test -f "$DEPLOY_DIR/.env"
if sudo -u ubuntu -- git -C "$DEPLOY_DIR" ls-files --error-unmatch .env >/dev/null 2>&1; then
echo "ERROR: .env is tracked by Git. Refusing to continue."
exit 1
fi
cd "$DEPLOY_DIR"
command -v git >/dev/null
command -v curl >/dev/null
sudo -n docker --version
sudo -n docker compose version
sudo -n docker compose -f docker-compose.prod.yml config --quiet
sudo -n docker compose -f docker-compose.prod.yml ps
echo "SSM preflight passed. No application or database changes were made."
REMOTE
)"
;;
deploy)
REMOTE_SCRIPT="$(cat <<'REMOTE'
set -Eeuo pipefail
DEPLOY_DIR="/home/ubuntu/cloud_monitor"
test -d "$DEPLOY_DIR"
test -f "$DEPLOY_DIR/.env"
if sudo -u ubuntu -- git -C "$DEPLOY_DIR" ls-files --error-unmatch .env >/dev/null 2>&1; then
echo "ERROR: .env is tracked by Git. Refusing to deploy."
exit 1
fi
cd "$DEPLOY_DIR"
PREVIOUS_SHA="$(sudo -u ubuntu -- git -C "$DEPLOY_DIR" rev-parse HEAD)"
rollback_on_error() {
local rc=$?
trap - ERR
echo "Deployment failed; attempting rollback to ${PREVIOUS_SHA}."
sudo -u ubuntu -- git -C "$DEPLOY_DIR" checkout -B main "$PREVIOUS_SHA" || true
sudo -n docker compose -f docker-compose.prod.yml build backend frontend || true
sudo -n docker compose -f docker-compose.prod.yml up -d --remove-orphans || true
exit "$rc"
}
trap rollback_on_error ERR
sudo -n install -d -m 0750 /var/lib/cloudmonitor
printf '%s\n' "$PREVIOUS_SHA" | sudo -n tee /var/lib/cloudmonitor/previous-deploy-sha >/dev/null
sudo -u ubuntu -- git -C "$DEPLOY_DIR" fetch --prune origin +refs/heads/main:refs/remotes/origin/main
sudo -u ubuntu -- git -C "$DEPLOY_DIR" checkout -B main origin/main
DEPLOY_SHA="$(sudo -u ubuntu -- git -C "$DEPLOY_DIR" rev-parse HEAD)"
sudo -n docker compose -f docker-compose.prod.yml config --quiet
sudo -n docker compose -f docker-compose.prod.yml pull prometheus node-exporter alertmanager
sudo -n docker compose -f docker-compose.prod.yml build backend frontend
sudo -n docker compose -f docker-compose.prod.yml up -d --remove-orphans
wait_for_http() {
local url="$1" attempt status
for attempt in $(seq 1 12); do
status="$(curl -sS --max-time 5 -o /dev/null -w '%{http_code}' "$url" || true)"
[[ "$status" == "200" ]] && return 0
sleep 5
done
echo "HTTP health check failed: $url"
return 1
}
wait_for_backend() {
local attempt body
for attempt in $(seq 1 12); do
body="$(curl -fsS --max-time 5 http://127.0.0.1/health 2>/dev/null || true)"
if printf '%s' "$body" | python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin).get("status") == "healthy" else 1)' 2>/dev/null; then return 0; fi
sleep 5
done
echo "Backend did not report status=healthy."
return 1
}
wait_for_prometheus() {
local attempt body
for attempt in $(seq 1 12); do
body="$(sudo -n docker compose -f docker-compose.prod.yml exec -T prometheus wget -qO- http://localhost:9090/api/v1/targets 2>/dev/null || true)"
if printf '%s' "$body" | python3 -c 'import json,sys; p=json.load(sys.stdin); required={"alertmanager","cloudmonitor-backend","node-exporter","prometheus"}; ts=p.get("data",{}).get("activeTargets",[]); bad=[n for n in required if not any(t.get("scrapePool")==n and t.get("health")=="up" for t in ts)]; sys.exit(0 if p.get("status")=="success" and not bad else 1)' 2>/dev/null; then return 0; fi
sleep 5
done
echo "Prometheus targets are not all healthy."
return 1
}
wait_for_http "http://127.0.0.1/"
wait_for_backend
wait_for_prometheus
printf '%s\n' "$DEPLOY_SHA" | sudo -n tee /var/lib/cloudmonitor/last-successful-deploy-sha >/dev/null
trap - ERR
echo "Deployment and health checks succeeded for ${DEPLOY_SHA}."
echo "No PostgreSQL volume was deleted or recreated."
REMOTE
)"
;;
rollback)
REMOTE_SCRIPT="$(cat <<'REMOTE'
set -Eeuo pipefail
DEPLOY_DIR="/home/ubuntu/cloud_monitor"
test -d "$DEPLOY_DIR"
test -f "$DEPLOY_DIR/.env"
if sudo -u ubuntu -- git -C "$DEPLOY_DIR" ls-files --error-unmatch .env >/dev/null 2>&1; then
echo "ERROR: .env is tracked by Git. Refusing to roll back."
exit 1
fi
cd "$DEPLOY_DIR"
CURRENT_SHA="$(sudo -u ubuntu -- git -C "$DEPLOY_DIR" rev-parse HEAD)"
ROLLBACK_SHA="$(sudo -n cat /var/lib/cloudmonitor/previous-deploy-sha)"
sudo -u ubuntu -- git -C "$DEPLOY_DIR" cat-file -e "${ROLLBACK_SHA}^{commit}"
restore_current_on_error() {
local rc=$?
trap - ERR
sudo -u ubuntu -- git -C "$DEPLOY_DIR" checkout -B main "$CURRENT_SHA" || true
sudo -n docker compose -f docker-compose.prod.yml build backend frontend || true
sudo -n docker compose -f docker-compose.prod.yml up -d --remove-orphans || true
exit "$rc"
}
trap restore_current_on_error ERR
sudo -u ubuntu -- git -C "$DEPLOY_DIR" checkout -B main "$ROLLBACK_SHA"
sudo -n docker compose -f docker-compose.prod.yml config --quiet
sudo -n docker compose -f docker-compose.prod.yml build backend frontend
sudo -n docker compose -f docker-compose.prod.yml up -d --remove-orphans
curl -fsS --max-time 5 http://127.0.0.1/ >/dev/null
BACKEND_BODY="$(curl -fsS --max-time 5 http://127.0.0.1/health)"
printf '%s' "$BACKEND_BODY" | python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin).get("status") == "healthy" else 1)'
printf '%s\n' "$CURRENT_SHA" | sudo -n tee /var/lib/cloudmonitor/previous-deploy-sha >/dev/null
printf '%s\n' "$ROLLBACK_SHA" | sudo -n tee /var/lib/cloudmonitor/last-successful-deploy-sha >/dev/null
trap - ERR
echo "Rollback to ${ROLLBACK_SHA} succeeded; PostgreSQL volumes were preserved."
REMOTE
)"
;;
*)
echo "::error::Unsupported SSM operation."
exit 1
;;
esac
PARAMETERS="$(jq -n --arg script "$REMOTE_SCRIPT" '{commands: [("bash -lc " + ($script | @sh))]}')"
COMMAND_ID="$(aws ssm send-command \
--instance-ids "$EC2_INSTANCE_ID" \
--document-name "AWS-RunShellScript" \
--comment "CloudMonitor ${OPERATION} via GitHub Actions" \
--timeout-seconds 900 \
--parameters "$PARAMETERS" \
--query 'Command.CommandId' --output text)"
echo "SSM Command ID: $COMMAND_ID"
for attempt in $(seq 1 360); do
INVOCATION="$(aws ssm get-command-invocation \
--command-id "$COMMAND_ID" --instance-id "$EC2_INSTANCE_ID" \
--output json 2>/dev/null || true)"
STATUS="$(printf '%s' "$INVOCATION" | jq -r '.Status // "Pending"' 2>/dev/null || echo "Pending")"
case "$STATUS" in
Success)
printf '%s\n' "$INVOCATION" | jq -r '.StandardOutputContent // ""'
exit 0
;;
Failed|TimedOut|ExecutionTimedOut|DeliveryTimedOut|Cancelled|Cancelling|Undeliverable|Terminated|InvalidPlatform|AccessDenied|NoInstancesInTag|InvalidDocument|Incomplete|RateExceeded)
echo "::error::SSM command ended with status: $STATUS"
printf '%s\n' "$INVOCATION" | jq -r '"Status details: \(.StatusDetails // "unknown")\nResponse code: \(.ResponseCode // "unknown")\nStandard output:\n\(.StandardOutputContent // "")\nStandard error:\n\(.StandardErrorContent // "")"'
exit 1
;;
esac
sleep 5
done
echo "::error::Timed out waiting for SSM command completion. Command ID: $COMMAND_ID"
exit 1
- name: Confirm deployment mode
if: inputs.operation == 'deploy'
run: echo "SSM production deployment completed. Review output before re-enabling push-based deployment."