@docupace/pipeline 1.0.2 โ†’ 1.0.3-1.demo1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,10 +2,11 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import yaml from 'js-yaml';
4
4
  import { $ } from 'zx';
5
-
6
- const REPO_NAME = 'gitops-dev';
7
- const REPO_URL = `https://x-token-auth:${process.env.GITOPS_DEV_REP_TOKEN}@bitbucket.org/dp-cloud/${REPO_NAME}.git`;
8
- const GITOPS_BRANCH = 'master';
5
+ import lodash from 'lodash';
6
+ import { appInfo, environmentConfig, getRepUrl } from './config.js';
7
+ import { copy2 } from './copy.js';
8
+ import axios from 'axios';
9
+ import { deployCore, deployConnect } from './jenkins.js';
9
10
 
10
11
  /**
11
12
  * Clone the repository, read the YAML file, and return the parsed data and file paths.
@@ -13,24 +14,180 @@ const GITOPS_BRANCH = 'master';
13
14
  * @param {string} site - The site name.
14
15
  * @returns {object} - The repository path, file path, and YAML data.
15
16
  */
16
- export async function readDeployConfig(application, site) {
17
- const repoPath = path.join(process.cwd(), REPO_NAME);
18
- const deployConfigFilePath = path.join(repoPath, `dp/${site}/${application}.values.yaml`);
19
17
 
20
- console.log(`Cloning repository: ${REPO_NAME}`);
21
- await $`git clone ${REPO_URL}`;
22
- console.log(`Repository cloned to: ${repoPath}`);
18
+ function getRepoLocalPath(env) {
19
+ const repoName = `gitops-${env}`;
20
+ const repoPath = path.join(process.cwd(), repoName);
21
+ return { repoPath, repoName };
22
+ }
23
+
24
+ async function updateAndCommitConnectVersion(
25
+ toEnv,
26
+ toSite,
27
+ getComparedVersion,
28
+ connectDeployPath,
29
+ ) {
30
+ const connectToEnv = toEnv == 'qa' ? 'preprod' : toEnv;
31
+ const filePath = path.join(
32
+ connectDeployPath,
33
+ 'envs',
34
+ connectToEnv,
35
+ toSite,
36
+ 'dock.sh',
37
+ );
38
+
39
+ try {
40
+ let content = fs.readFileSync(filePath, 'utf8');
41
+ content = content.replace(
42
+ /IMAGE_VERSION=.*/,
43
+ `IMAGE_VERSION=git-commit-${getComparedVersion}`,
44
+ );
45
+ fs.writeFileSync(filePath, content, 'utf8');
46
+
47
+ // Git commands to stage, commit and push changes
48
+ await $`cd ${connectDeployPath} && git config user.email "gitops@docupace.com"`;
49
+ await $`cd ${connectDeployPath} && git add .`;
50
+ await $`cd ${connectDeployPath} && git commit -m "Update Connect version for ${toSite} in ${toEnv} to ${getComparedVersion}" || echo "No changes to commit"`;
51
+ await $`cd ${connectDeployPath} && git push`;
52
+
53
+ console.log('๐Ÿงน Cleaning up...');
54
+ await $`rm -rf ${connectDeployPath}`;
55
+ console.log('โœ… Cleanup complete.');
56
+ } catch (error) {
57
+ console.error('Error updating Connect version:', error);
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ async function fetchLoginFooter(env, site, isNewUrl) {
63
+ const url = isNewUrl
64
+ ? environmentConfig[env].newUrl(site)
65
+ : environmentConfig[env].oldUrl(site);
66
+ const endpoint = isNewUrl ? '/connect/loginFooter' : '_ui/loginFooter';
67
+ return await axios.get(`${url}${endpoint}`);
68
+ }
69
+
70
+ async function compareGetConnectSiteVersions(fromEnv, fromSite, toEnv, toSite) {
71
+ try {
72
+ let fromResponse, toResponse;
73
+ try {
74
+ fromResponse = await fetchLoginFooter(fromEnv, fromSite, true);
75
+ } catch {
76
+ fromResponse = await fetchLoginFooter(fromEnv, fromSite, false);
77
+ }
23
78
 
24
- let deployConfig;
25
79
  try {
26
- deployConfig = yaml.load(fs.readFileSync(deployConfigFilePath, 'utf8'));
27
- console.log(`YAML file loaded from: ${deployConfigFilePath}`);
28
- } catch (error) {
29
- console.error(`Error reading YAML file: ${error.message}`);
30
- process.exit(1);
80
+ toResponse = await fetchLoginFooter(toEnv, toSite, true);
81
+ } catch {
82
+ toResponse = await fetchLoginFooter(toEnv, toSite, false);
31
83
  }
32
84
 
33
- return { repoPath, deployConfigFilePath, deployConfig };
85
+ const fromMatch = fromResponse.data.match(/UI Build: ([a-f0-9]*)/);
86
+ const toMatch = toResponse.data.match(/UI Build: ([a-f0-9]*)/);
87
+
88
+ if (fromMatch && fromMatch[1] && toMatch && toMatch[1]) {
89
+ if (fromMatch[1] !== toMatch[1]) {
90
+ return fromMatch[1];
91
+ }
92
+ }
93
+ return false;
94
+ } catch (error) {
95
+ console.error('Error fetching Connect versions:', error);
96
+ throw error;
97
+ }
98
+ }
99
+ function getRepoLocalPathByRepoSlug(repoSlug) {
100
+ const repoName = `${repoSlug}`;
101
+ const repoPath = path.join(process.cwd(), repoName);
102
+ return { repoPath, repoName };
103
+ }
104
+
105
+ function cleanUpRepoPath(repoPath) {
106
+ // Check and handle repo directory
107
+ if (fs.existsSync(repoPath)) {
108
+ console.log(`${repoPath} directory exists. Removing it...`);
109
+ fs.rmSync(repoPath, {
110
+ recursive: true,
111
+ force: true,
112
+ });
113
+ }
114
+ }
115
+
116
+ export async function cloneEnvRepository(env) {
117
+ const { repoPath, repoName } = getRepoLocalPath(env);
118
+ const repoUrl = getRepUrl(repoName);
119
+ console.log(`Cloning repository: ${repoName}`);
120
+ await cleanUpRepoPath(repoPath);
121
+ await $`git clone --depth 1 ${repoUrl}`;
122
+ console.log(`Repository cloned to: ${repoPath}`);
123
+ return repoPath;
124
+ }
125
+
126
+ export async function cloneRepository(repoSlug) {
127
+ const { repoPath, repoName } = getRepoLocalPathByRepoSlug(repoSlug);
128
+ const repoUrl = getRepUrl(repoName);
129
+
130
+ await cleanUpRepoPath(repoPath);
131
+
132
+ console.log(`Cloning repository: ${repoName}`);
133
+ await $`git clone --depth 1 ${repoUrl}`;
134
+ console.log(`Repository cloned to: ${repoPath}`);
135
+ return repoPath;
136
+ }
137
+
138
+ function getConfigPath(application, env, site, name) {
139
+ const { repoPath } = getRepoLocalPath(env);
140
+ const deployConfigFilePath = path.join(
141
+ repoPath,
142
+ `dp/${site}/${application}.${name}.yaml`,
143
+ );
144
+
145
+ return { repoPath, deployConfigFilePath };
146
+ }
147
+
148
+ function getAppTypesFromRepo(env, site) {
149
+ const { repoPath } = getRepoLocalPath(env);
150
+ const deployConfigFilePath = path.join(repoPath, `dp/${site}`);
151
+ const applications = [];
152
+ if (fs.existsSync(deployConfigFilePath)) {
153
+ const files = fs.readdirSync(deployConfigFilePath);
154
+ files.forEach((file) => {
155
+ if (file.includes('.values.yaml')) {
156
+ const appName = file.split('.')[0];
157
+ applications.push(appName);
158
+ }
159
+ });
160
+ }
161
+
162
+ return { applications };
163
+ }
164
+
165
+ export async function readDeployConfig(application, env, site, name) {
166
+ const { deployConfigFilePath } = getConfigPath(application, env, site, name);
167
+
168
+ let deployConfig;
169
+ try {
170
+ deployConfig = yaml.load(fs.readFileSync(deployConfigFilePath, 'utf8'));
171
+ console.log(`YAML file loaded from: ${deployConfigFilePath}`);
172
+ } catch (error) {
173
+ console.error(`Error reading YAML file: ${error.message}`);
174
+ process.exit(1);
175
+ }
176
+
177
+ return { deployConfig, deployConfigFilePath };
178
+ }
179
+
180
+ export async function cloneAndReadDeployConfig(application, env, site) {
181
+ const repoPath = await cloneEnvRepository(env);
182
+
183
+ const { deployConfig, deployConfigFilePath } = await readDeployConfig(
184
+ application,
185
+ env,
186
+ site,
187
+ 'values',
188
+ );
189
+
190
+ return { repoPath, deployConfigFilePath, deployConfig };
34
191
  }
35
192
 
36
193
  /**
@@ -40,15 +197,15 @@ export async function readDeployConfig(application, site) {
40
197
  * @returns {object} - The updated YAML data.
41
198
  */
42
199
  export function setTag(deployConfig, tag) {
43
- if (deployConfig.image && deployConfig.image.tag) {
44
- console.log(`Current image tag: ${deployConfig.image.tag}`);
45
- deployConfig.image.tag = tag;
46
- console.log(`Updated image tag to: ${deployConfig.image.tag}`);
47
- } else {
48
- console.error('No "image.tag" field found in the YAML file.');
49
- process.exit(1);
50
- }
51
- return deployConfig;
200
+ if (deployConfig.image && deployConfig.image.tag) {
201
+ console.log(`Current image tag: ${deployConfig.image.tag}`);
202
+ deployConfig.image.tag = tag;
203
+ console.log(`Updated image tag to: ${deployConfig.image.tag}`);
204
+ } else {
205
+ console.error('No "image.tag" field found in the YAML file.');
206
+ process.exit(1);
207
+ }
208
+ return deployConfig;
52
209
  }
53
210
 
54
211
  /**
@@ -57,25 +214,50 @@ export function setTag(deployConfig, tag) {
57
214
  * @param {string} deployConfigFilePath - The path to the YAML file.
58
215
  * @param {object} deployConfig - The updated YAML data.
59
216
  */
60
- export async function writeDeployConfig(repoPath, deployConfigFilePath, deployConfig) {
61
- try {
62
- fs.writeFileSync(deployConfigFilePath, yaml.dump(deployConfig), 'utf8');
63
- console.log(`Updated YAML file saved at: ${deployConfigFilePath}`);
64
- } catch (error) {
65
- console.error(`Error writing YAML file: ${error.message}`);
66
- process.exit(1);
67
- }
68
217
 
69
- console.log('Committing changes to the repository...');
70
- await $`cd ${repoPath} && git config user.email "gitops@docupace.com"`;
71
- await $`cd ${repoPath} && git add ${deployConfigFilePath}`;
72
- await $`cd ${repoPath} && git commit -m "Update image tag to ${deployConfig.image.tag}"`;
73
- await $`cd ${repoPath} && git push origin ${GITOPS_BRANCH}`;
74
- console.log('Changes pushed to the remote repository.');
75
-
76
- console.log('Cleaning up...');
218
+ export async function pushDeployConfig(repoPath, commitMessage) {
219
+ console.log('๐Ÿ“Œ Checking for updates to commit...');
220
+ // Check if there are any changes to commit
221
+ const status = (
222
+ await $`cd ${repoPath} && git status --porcelain`
223
+ ).stdout.trim();
224
+ if (!status) {
225
+ console.log('โœ… No changes to commit. Exiting.');
77
226
  await $`rm -rf ${repoPath}`;
78
- console.log('Cleanup complete.');
227
+ console.log('๐Ÿงน Cleanup complete.');
228
+ return;
229
+ }
230
+
231
+ console.log('๐Ÿ“Œ Committing changes to the repository...');
232
+ await $`cd ${repoPath} && git config user.email "gitops@docupace.com"`;
233
+ await $`cd ${repoPath} && git add .`;
234
+ await $`cd ${repoPath} && git commit -m ${commitMessage}`;
235
+ await $`cd ${repoPath} && git push`;
236
+ console.log('โœ… Changes pushed to the remote repository.');
237
+
238
+ console.log('๐Ÿงน Cleaning up...');
239
+ await $`rm -rf ${repoPath}`;
240
+ console.log('โœ… Cleanup complete.');
241
+ }
242
+
243
+ function writeDeployConfig(deployConfigFilePath, deployConfig) {
244
+ try {
245
+ fs.writeFileSync(deployConfigFilePath, yaml.dump(deployConfig), 'utf8');
246
+ console.log(`โœ… Updated YAML file saved at: ${deployConfigFilePath}`);
247
+ } catch (error) {
248
+ console.error(`โŒ Error writing YAML file: ${error.message}`);
249
+ process.exit(1);
250
+ }
251
+ }
252
+
253
+ export async function writeAndPushDeployConfig(
254
+ repoPath,
255
+ deployConfigFilePath,
256
+ deployConfig,
257
+ commitMessage,
258
+ ) {
259
+ writeDeployConfig(deployConfigFilePath, deployConfig);
260
+ await pushDeployConfig(repoPath, commitMessage);
79
261
  }
80
262
 
81
263
  /**
@@ -85,34 +267,266 @@ export async function writeDeployConfig(repoPath, deployConfigFilePath, deployCo
85
267
  */
86
268
 
87
269
  async function getDeployTag() {
88
- const gitTag = (await $`git tag --points-at HEAD | grep '^v' | head -n 1`).stdout.trim()
89
- const deployTag = gitTag || `build-${process.env.BITBUCKET_BUILD_NUMBER}`;
90
- return deployTag;
270
+ const gitTag = (
271
+ await $`git tag --points-at HEAD | grep '^v' | head -n 1`
272
+ ).stdout.trim();
273
+ const deployTag = gitTag || `build-${process.env.BITBUCKET_BUILD_NUMBER}`;
274
+ return deployTag;
91
275
  }
92
276
 
93
277
  export async function deployTemplate(site) {
94
- const deployTag = await getDeployTag();
95
- console.log(`Deploying standard template for site: ${site}`);
96
- console.log(`Using deployment tag: ${deployTag}`);
97
- const { repoPath, deployConfigFilePath, deployConfig } = await readDeployConfig('graphql-server', site);
278
+ const deployTag = await getDeployTag();
279
+ console.log(`Deploying standard template for site: ${site}`);
280
+ console.log(`Using deployment tag: ${deployTag}`);
281
+ const { repoPath, deployConfigFilePath, deployConfig } =
282
+ await cloneAndReadDeployConfig('graphql-server', 'dev', site);
283
+
284
+ deployConfig.graphqlServer.standardConfigRemoteBranch = deployTag;
98
285
 
99
- deployConfig.graphqlServer.standardConfigRemoteBranch = deployTag;
286
+ await writeAndPushDeployConfig(
287
+ repoPath,
288
+ deployConfigFilePath,
289
+ deployConfig,
290
+ `Update template to ${deployConfig.graphqlServer.standardConfigRemoteBranch}`,
291
+ );
292
+ console.log('Deployment completed successfully.');
293
+ }
294
+
295
+ export async function deploy(application, site) {
296
+ const deployTag = getDeployTag();
100
297
 
101
- await writeDeployConfig(repoPath, deployConfigFilePath, deployConfig);
102
- console.log('Deployment completed successfully.');
298
+ console.log(`Deploying application: ${application} for site: ${site}`);
299
+ console.log(`Using deployment tag: ${deployTag}`);
103
300
 
301
+ const { repoPath, deployConfigFilePath, deployConfig } =
302
+ await cloneAndReadDeployConfig(application, 'dev', site);
303
+ const updatedConfigData = setTag(deployConfig, deployTag);
304
+ await writeAndPushDeployConfig(
305
+ repoPath,
306
+ deployConfigFilePath,
307
+ updatedConfigData,
308
+ `Update image tag to ${deployConfig.image.tag}`,
309
+ );
310
+
311
+ console.log('Deployment completed successfully.');
104
312
  }
105
313
 
314
+ async function getAppInfo(coreUrl) {
315
+ const url = `${coreUrl}/b2b/rest/v1/appinfo`;
316
+ return await axios.get(url);
317
+ }
106
318
 
107
- export async function deploy(application, site) {
108
- const deployTag = getDeployTag();
319
+ function getBranchNameFromVersion(version) {
320
+ const match = version.match(/(\d+\.\d+\.[^\-]+)(?:-(\d+)-g([a-f0-9]+))?/);
321
+
322
+ if (!match) {
323
+ throw new Error(`Invalid version format: ${version}`);
324
+ }
325
+
326
+ const fullVersion = match[1]; // e.g., 24.19.19, 24.20.alpha3, etc.
327
+ const customBranch = match[2]; // e.g., 4, 58, or 0
328
+ const commitHash = match[3]; // e.g., 668edef58e, 634cf6c904, etc.
329
+
330
+ // If "alpha" is in the version or customBranch is non-zero, use the commit hash
331
+ if (fullVersion.includes('alpha') || (customBranch && customBranch !== '0')) {
332
+ return commitHash;
333
+ }
334
+
335
+ // Otherwise, use the full version
336
+ return 'v' + fullVersion;
337
+ }
338
+
339
+ async function getCoreBranchName(fromEnv, fromSite) {
340
+ const envConfig = environmentConfig[fromEnv];
341
+ const oldUrl = envConfig.oldUrl(fromSite);
342
+ const newUrl = envConfig.newUrl(fromSite) + '/core';
343
+
344
+ let appinfo;
345
+ try {
346
+ appinfo = await getAppInfo(oldUrl);
347
+ } catch {
348
+ try {
349
+ appinfo = await getAppInfo(newUrl);
350
+ } catch {
351
+ throw new Error('Cannot get app info');
352
+ }
353
+ }
354
+
355
+ const coreVersion = appinfo.data.core.version;
356
+ const branchName = getBranchNameFromVersion(coreVersion);
357
+ return branchName;
358
+ }
359
+
360
+ export async function deployApp(
361
+ application,
362
+ appDetails,
363
+ fromEnv,
364
+ fromSite,
365
+ toEnv,
366
+ toSite,
367
+ ) {
368
+ let changesMade = false;
369
+ console.log(`Processing application: ${application}`);
370
+
371
+ // Read the deployment configuration for the source environment and site
372
+ const { deployConfig: fromDeployConfig } = await readDeployConfig(
373
+ application,
374
+ fromEnv,
375
+ fromSite,
376
+ 'values',
377
+ );
109
378
 
110
- console.log(`Deploying application: ${application} for site: ${site}`);
111
- console.log(`Using deployment tag: ${deployTag}`);
379
+ if (fromEnv !== toEnv) {
380
+ await copy2(
381
+ appDetails.repositoryName,
382
+ fromEnv,
383
+ toEnv,
384
+ fromDeployConfig.image.tag,
385
+ );
386
+ }
112
387
 
113
- const { repoPath, deployConfigFilePath, deployConfig } = await readDeployConfig(application, site);
114
- const updatedConfigData = setTag(deployConfig, deployTag);
115
- await writeDeployConfig(repoPath, deployConfigFilePath, updatedConfigData);
388
+ // Read the deployment configuration for the target environment and site
389
+ const {
390
+ deployConfig: toDeployConfig,
391
+ deployConfigFilePath: toDeployConfigFilePath,
392
+ } = await readDeployConfig(application, toEnv, toSite, 'values');
393
+
394
+ // Update target configuration using attributes specified in appInfo
395
+ for (const attribute of appDetails.deployAttributes) {
396
+ const sourceValue = lodash.get(fromDeployConfig, attribute);
397
+
398
+ if (sourceValue !== undefined) {
399
+ // Update the target configuration with the source value
400
+ lodash.set(toDeployConfig, attribute, sourceValue);
401
+ changesMade = true;
402
+ }
403
+ }
404
+
405
+ const {
406
+ deployConfig: toDeployAppConfig,
407
+ deployConfigFilePath: toDeployAppConfigFilePath,
408
+ } = await readDeployConfig(application, toEnv, toSite, 'app');
409
+
410
+ toDeployAppConfig.revision = fromDeployConfig.image.tag;
411
+
412
+ // Write updated configuration to the target YAML file
413
+ writeDeployConfig(toDeployConfigFilePath, toDeployConfig);
414
+
415
+ writeDeployConfig(toDeployAppConfigFilePath, toDeployAppConfig);
416
+ return changesMade;
417
+ }
418
+
419
+ export async function deployFromSite(
420
+ fromEnv,
421
+ fromSite,
422
+ toEnv,
423
+ toSite,
424
+ isDeployCore,
425
+ isDeployConnect,
426
+ ) {
427
+ if (isDeployCore === 'true') {
428
+ const branchName = await getCoreBranchName(fromEnv, fromSite);
429
+
430
+ const coreEnv = toEnv == 'qa' ? 'preprod' : toEnv;
431
+ await deployCore(coreEnv, toSite, 'true', branchName);
432
+
433
+ // To be added back when splitting between on prem and in cloud
434
+ /*await runPipeline('site-deploy', 'deploy-core', 'main', {
435
+ ENV: toEnv,
436
+ SITE: toSite,
437
+ LIQUIBASE: 'true',
438
+ BRANCH: branchName,
439
+ });*/
440
+ }
441
+
442
+ if (isDeployConnect === 'true') {
443
+ const branch = '';
444
+ const getComparedVersion = await compareGetConnectSiteVersions(
445
+ fromEnv,
446
+ fromSite,
447
+ toEnv,
448
+ toSite,
449
+ );
450
+ if (getComparedVersion) {
451
+ console.log('Version to deploy is: ', getComparedVersion);
452
+ const connectDeployPath = await cloneRepository('connect-deploy');
453
+ // update target version set to git-commit-${getCommparedVersion}}
454
+ await updateAndCommitConnectVersion(
455
+ toEnv,
456
+ toSite,
457
+ getComparedVersion,
458
+ connectDeployPath,
459
+ );
460
+ // save and deploy
461
+ const runLiquibase = true;
462
+ await deployConnect(toEnv, toSite, runLiquibase, branch);
463
+ }
464
+ }
465
+
466
+ // Clone repositories for source and target environments
467
+ const fromRepoPath = await cloneEnvRepository(fromEnv);
468
+ const toRepoPath =
469
+ toEnv === fromEnv ? fromRepoPath : await cloneEnvRepository(toEnv);
470
+
471
+ // Initialize a flag to track changes
472
+ let changesMade = false;
473
+ const applications = await getAppTypesFromRepo(toEnv, toSite);
474
+ console.log(applications);
475
+ // Iterate over applications in appInfo
476
+
477
+ let appInfoLocal = Object.fromEntries(
478
+ applications.applications
479
+ .filter((application) =>
480
+ Object.prototype.hasOwnProperty.call(appInfo, application),
481
+ )
482
+ .map((application) => [application, appInfo[application]]),
483
+ );
484
+
485
+ // let appInfoLocal = {};
486
+ // for (const application of applications.applications) {
487
+ // if (Object.prototype.hasOwnProperty.call(appInfo, application)) {
488
+ // appInfoLocal[application] = appInfo[application];
489
+ // }
490
+ // }
491
+
492
+ if (Object.keys(appInfoLocal).length === 0) {
493
+ const { deployConfig: toDeployAppConfig } = await readDeployConfig(
494
+ fromSite,
495
+ toEnv,
496
+ toSite,
497
+ 'app',
498
+ );
499
+
500
+ appInfoLocal[fromSite] = {
501
+ repositoryName: toDeployAppConfig.repo,
502
+ deployAttributes: ['image.tag'],
503
+ };
504
+ }
505
+
506
+ console.log('appinfoLocal', appInfoLocal);
507
+
508
+ for (const [application, appDetails] of Object.entries(appInfoLocal)) {
509
+ let cm = await deployApp(
510
+ application,
511
+ appDetails,
512
+ fromEnv,
513
+ fromSite,
514
+ toEnv,
515
+ toSite,
516
+ );
517
+ if (cm) {
518
+ changesMade = true;
519
+ }
520
+ }
116
521
 
117
- console.log('Deployment completed successfully.');
522
+ // Push all changes if any updates were made
523
+ if (changesMade) {
524
+ await pushDeployConfig(
525
+ toRepoPath,
526
+ `Updated deployment configurations from ${fromEnv}/${fromSite} to ${toEnv}/${toSite}`,
527
+ );
528
+ console.log('โœ… All configurations updated and pushed successfully.');
529
+ } else {
530
+ console.log('โœ… No changes detected. Nothing to push.');
531
+ }
118
532
  }
@@ -0,0 +1,50 @@
1
+ import { $ } from 'zx';
2
+
3
+
4
+ export async function haproxySync() {
5
+ const repoPath = '/root/repo/docupace-ansible';
6
+ const inventory = path.join(repoPath, 'inventories/preprod/inventory');
7
+
8
+ // Create haproxy.sh
9
+ const scriptContent = `
10
+ #!/bin/bash
11
+
12
+ [[ ! -f ${inventory} ]] && ( echo "Alert: no inventory file: ${inventory}" ; exit 1 )
13
+ cd ${repoPath}
14
+ pwd
15
+ git stash
16
+ git pull origin master
17
+ git checkout master
18
+ git submodule update --remote
19
+ git submodule foreach --recursive git checkout master
20
+ git submodule foreach --recursive git pull origin master
21
+
22
+ ansible-playbook -i inventories/preprod/inventory haproxy.yml -e "cluster=preprod"
23
+
24
+ echo "proceeding"
25
+ echo "committing changes"
26
+ git add preprod-haproxy.cfg
27
+ git commit -m "Sync haproxy"
28
+ git push origin master
29
+ `;
30
+
31
+ await fs.writeFile('haproxy.sh', scriptContent);
32
+
33
+ // Private key
34
+ const haproxyPrivateKey = process.env.HAPROXY_PRIVATE_KEY;
35
+ if (!haproxyPrivateKey) {
36
+ log('Error: HAPROXY_PRIVATE_KEY not set.');
37
+ process.exit(1);
38
+ }
39
+
40
+ await fs.writeFile('private.key', Buffer.from(haproxyPrivateKey, 'base64'));
41
+ await fs.chmod('private.key', 0o600);
42
+
43
+ await $`cat private.key`; // Just to mimic the script's behavior
44
+
45
+ // Copy script to remote
46
+ await $`scp -i private.key -o StrictHostKeyChecking=no haproxy.sh root@10.10.28.198:/tmp/haproxy.sh`;
47
+
48
+ // Execute script on remote
49
+ await $`ssh -i private.key -o StrictHostKeyChecking=no root@10.10.28.198 "bash /tmp/haproxy.sh"`;
50
+ }