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 | // multi-stage-deployment.ts - Multi-stage deployment
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as child_process from "child_process";
// Multi-stage deployment configuration
interface DeploymentStage {
name: string;
preChecks: string[];
deploymentScript: string;
postChecks: string[];
rollbackScript?: string;
}
const deploymentStages: DeploymentStage[] = [
{
name: "prepare",
preChecks: [
"df -h / | awk 'NR==2 { if($5+0 > 80) exit 1 }'",
"free | awk 'NR==2 { if($4/($2/100) < 10) exit 1 }'"
],
deploymentScript: `#!/bin/bash
set -euo pipefail
echo "=== Stage: Prepare ==="
# Create deployment directories
mkdir -p /var/www/app/{current,staging,backups}
chown -R www-data:www-data /var/www/app
# Create backup of current deployment
if [ -d /var/www/app/current ]; then
BACKUP_NAME="backup-$(date +%Y%m%d-%H%M%S)"
cp -r /var/www/app/current /var/www/app/backups/$BACKUP_NAME
echo "Backup created: $BACKUP_NAME"
fi
# Prepare staging directory
rm -rf /var/www/app/staging
mkdir -p /var/www/app/staging
`,
postChecks: [
"test -d /var/www/app/staging",
"test -w /var/www/app/staging"
]
},
{
name: "deploy",
preChecks: [
"curl -sf https://artifacts.example.com/app.tar.gz >/dev/null"
],
deploymentScript: `#!/bin/bash
set -euo pipefail
echo "=== Stage: Deploy ==="
# Download and extract application
cd /var/www/app/staging
curl -L https://artifacts.example.com/app.tar.gz | tar -xz
# Install dependencies
if [ -f package.json ]; then
npm install --production
fi
# Set permissions
chown -R www-data:www-data /var/www/app/staging
find /var/www/app/staging -type f -exec chmod 644 {} \\;
find /var/www/app/staging -type d -exec chmod 755 {} \\;
# Create application symlink
ln -sf /var/www/app/staging /var/www/app/new
`,
postChecks: [
"test -f /var/www/app/staging/package.json",
"test -d /var/www/app/new"
]
},
{
name: "test",
preChecks: [],
deploymentScript: `#!/bin/bash
set -euo pipefail
echo "=== Stage: Test ==="
# Run application tests
cd /var/www/app/staging
# Unit tests
if [ -f tests/unit.sh ]; then
./tests/unit.sh
fi
# Integration tests
if [ -f tests/integration.sh ]; then
./tests/integration.sh
fi
# Security checks
if command -v npm >/dev/null; then
npm audit --audit-level high
fi
`,
postChecks: [
"curl -sf http://localhost/health >/dev/null"
],
rollbackScript: `#!/bin/bash
set -euo pipefail
echo "=== Rollback: Test Failed ==="
# Stop application
systemctl stop app || true
# Restore from backup
LATEST_BACKUP=$(ls -td /var/www/app/backups/*/ 2>/dev/null | head -1)
if [ -n "$LATEST_BACKUP" ]; then
rm -rf /var/www/app/current
cp -r "$LATEST_BACKUP" /var/www/app/current
systemctl start app
fi
`
},
{
name: "activate",
preChecks: [],
deploymentScript: `#!/bin/bash
set -euo pipefail
echo "=== Stage: Activate ==="
# Atomic deployment switch
mv /var/www/app/new /var/www/app/current-tmp
ln -sfn /var/www/app/current-tmp /var/www/app/current
rm -rf /var/www/app/current-tmp
# Restart services
systemctl restart nginx
systemctl restart app
# Verify services are running
systemctl is-active nginx
systemctl is-active app
# Warm up cache
curl -s http://localhost/warmup >/dev/null || true
`,
postChecks: [
"systemctl is-active app",
"curl -sf http://localhost/ >/dev/null"
]
},
{
name: "cleanup",
preChecks: [],
deploymentScript: `#!/bin/bash
set -euo pipefail
echo "=== Stage: Cleanup ==="
# Clean up old backups (keep last 5)
ls -td /var/www/app/backups/*/ 2>/dev/null | tail -n +6 | xargs rm -rf
# Clean up temporary files
find /tmp -name "deploy-*" -mtime +1 -delete 2>/dev/null || true
# Send deployment notification
curl -X POST "${process.env.SLACK_WEBHOOK}" \
-H "Content-Type: application/json" \
-d '{
"text": "Deployment completed successfully",
"attachments": [{
"color": "good",
"fields": [
{"title": "Application", "value": "MyApp", "short": true},
{"title": "Version", "value": "${process.env.APP_VERSION || 'latest'}", "short": true},
{"title": "Environment", "value": "${process.env.ENVIRONMENT || 'unknown'}", "short": true},
{"title": "Timestamp", "value": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'", "short": true}
]
}]
}' || true
`,
postChecks: []
}
];
// Execute multi-stage deployment
class MultiStageDeployment {
private stages: DeploymentStage[];
private results: Map<string, string> = new Map();
constructor(stages: DeploymentStage[]) {
this.stages = stages;
}
async execute(): Promise<Map<string, string>> {
for (const stage of this.stages) {
try {
console.log(`Executing stage: ${stage.name}`);
// Run pre-checks
for (const check of stage.preChecks) {
await this.executeCommand(check);
}
// Execute deployment script
await this.executeCommand(stage.deploymentScript);
// Run post-checks
for (const check of stage.postChecks) {
await this.executeCommand(check);
}
this.results.set(stage.name, "completed");
console.log(`Stage ${stage.name} completed successfully`);
} catch (error) {
console.error(`Stage ${stage.name} failed: ${error}`);
// Execute rollback if available
if (stage.rollbackScript) {
try {
await this.executeCommand(stage.rollbackScript);
console.log(`Rollback for stage ${stage.name} completed`);
} catch (rollbackError) {
console.error(`Rollback for stage ${stage.name} failed: ${rollbackError}`);
}
}
this.results.set(stage.name, `failed: ${error}`);
throw new Error(`Deployment failed at stage ${stage.name}: ${error}`);
}
}
return this.results;
}
private executeCommand(command: string): Promise<void> {
return new Promise((resolve, reject) => {
const child = child_process.exec(command, { timeout: 300000 }); // 5 minute timeout
child.stdout?.on('data', (data) => {
console.log(data.toString());
});
child.stderr?.on('data', (data) => {
console.error(data.toString());
});
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Command failed with exit code ${code}`));
}
});
child.on('error', (error) => {
reject(error);
});
});
}
}
// Create and execute multi-stage deployment
const deployment = new MultiStageDeployment(deploymentStages);
// Export deployment results
export const deploymentResults = pulumi.output(deployment.execute());
export const deploymentStatus = deploymentResults.apply(results => {
const failedStages = Array.from(results.entries())
.filter(([_, status]) => status.includes('failed'))
.map(([stage, _]) => stage);
return failedStages.length === 0 ? "successful" : `failed at stages: ${failedStages.join(', ')}`;
});
|