@ibm-cloud/cd-tools 1.0.0
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.
- package/.github/workflows/release.yml +35 -0
- package/LICENSE +201 -0
- package/README.md +2 -0
- package/cmd/check-secrets.js +106 -0
- package/cmd/copy-toolchain.js +333 -0
- package/cmd/direct-transfer.js +288 -0
- package/cmd/index.js +13 -0
- package/cmd/utils/logger.js +173 -0
- package/cmd/utils/requests.js +359 -0
- package/cmd/utils/terraform.js +441 -0
- package/cmd/utils/utils.js +128 -0
- package/cmd/utils/validate.js +503 -0
- package/config.js +202 -0
- package/index.js +24 -0
- package/package.json +28 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
branches:
|
|
5
|
+
- main
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read # for checkout
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
release:
|
|
12
|
+
name: Release
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
permissions:
|
|
15
|
+
contents: write # to publish GitHub releases
|
|
16
|
+
issues: write # to comment on released issues
|
|
17
|
+
pull-requests: write # to comment on released pull requests
|
|
18
|
+
steps:
|
|
19
|
+
- name: Checkout
|
|
20
|
+
uses: actions/checkout@v4
|
|
21
|
+
with:
|
|
22
|
+
fetch-depth: 0
|
|
23
|
+
- name: Setup Node.js
|
|
24
|
+
uses: actions/setup-node@v4
|
|
25
|
+
with:
|
|
26
|
+
node-version: "lts/*"
|
|
27
|
+
- name: Install dependencies
|
|
28
|
+
run: npm clean-install
|
|
29
|
+
- name: Verify the integrity of provenance attestations and registry signatures for installed dependencies
|
|
30
|
+
run: npm audit signatures
|
|
31
|
+
- name: Release
|
|
32
|
+
env:
|
|
33
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
34
|
+
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
35
|
+
run: npx semantic-release
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Licensed Materials - Property of IBM
|
|
3
|
+
* (c) Copyright IBM Corporation 2025. All Rights Reserved.
|
|
4
|
+
*
|
|
5
|
+
* Note to U.S. Government Users Restricted Rights:
|
|
6
|
+
* Use, duplication or disclosure restricted by GSA ADP Schedule
|
|
7
|
+
* Contract with IBM Corp.
|
|
8
|
+
*/
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
import { exit } from 'node:process';
|
|
12
|
+
import { Command } from 'commander';
|
|
13
|
+
import { parseEnvVar, decomposeCrn, isSecretReference } from './utils/utils.js';
|
|
14
|
+
import { logger, LOG_STAGES } from './utils/logger.js';
|
|
15
|
+
import { getBearerToken, getToolchainTools, getPipelineData } from './utils/requests.js';
|
|
16
|
+
import { UPDATEABLE_SECRET_PROPERTIES_BY_TOOL_TYPE } from '../config.js';
|
|
17
|
+
|
|
18
|
+
const command = new Command('check-secrets')
|
|
19
|
+
.description('Checks if you have any stored secrets in your toolchain or pipelines')
|
|
20
|
+
.requiredOption('-c, --toolchain-crn <crn>', 'The CRN of the source toolchain to check')
|
|
21
|
+
.option('-a --apikey <api key>', 'IBM Cloud IAM API key with permissions to read the toolchain.')
|
|
22
|
+
.showHelpAfterError()
|
|
23
|
+
.hook('preAction', cmd => cmd.showHelpAfterError(false)) // only show help during validation
|
|
24
|
+
.action(main);
|
|
25
|
+
|
|
26
|
+
async function main(options) {
|
|
27
|
+
const toolchainCrn = options.toolchainCrn;
|
|
28
|
+
const apiKey = options.apikey || parseEnvVar('IBMCLOUD_API_KEY');
|
|
29
|
+
|
|
30
|
+
if (!apiKey) {
|
|
31
|
+
logger.error('Missing IBM Cloud IAM API key', LOG_STAGES.setup);
|
|
32
|
+
exit(1);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
logger.print(`Checking secrets for toolchain ${toolchainCrn}...`);
|
|
36
|
+
|
|
37
|
+
const decomposedCrn = decomposeCrn(toolchainCrn);
|
|
38
|
+
|
|
39
|
+
const token = await getBearerToken(apiKey);
|
|
40
|
+
const toolchainId = decomposedCrn.serviceInstance;
|
|
41
|
+
const region = decomposedCrn.location;
|
|
42
|
+
|
|
43
|
+
const getToolsRes = await getToolchainTools(token, toolchainId, region);
|
|
44
|
+
|
|
45
|
+
const toolResults = [];
|
|
46
|
+
const pipelineResults = [];
|
|
47
|
+
|
|
48
|
+
if (getToolsRes?.tools?.length > 0) {
|
|
49
|
+
for (let i = 0; i < getToolsRes.tools.length; i++) {
|
|
50
|
+
const tool = getToolsRes.tools[i];
|
|
51
|
+
|
|
52
|
+
// Check tool integrations for any plain text secret values
|
|
53
|
+
if (UPDATEABLE_SECRET_PROPERTIES_BY_TOOL_TYPE[tool.tool_type_id]) {
|
|
54
|
+
UPDATEABLE_SECRET_PROPERTIES_BY_TOOL_TYPE[tool.tool_type_id].forEach((updateableSecretParam) => {
|
|
55
|
+
if (tool.parameters[updateableSecretParam] && !isSecretReference(tool.parameters[updateableSecretParam])) {
|
|
56
|
+
toolResults.push({
|
|
57
|
+
'Tool ID': tool.id,
|
|
58
|
+
'Tool Type': tool.tool_type_id,
|
|
59
|
+
'Property Name': updateableSecretParam
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// For tekton pipelines, check for any plain text secret properties
|
|
66
|
+
if (tool.tool_type_id === 'pipeline' && tool.parameters?.type === 'tekton') {
|
|
67
|
+
const pipelineData = await getPipelineData (token, tool.id, region);
|
|
68
|
+
|
|
69
|
+
pipelineData?.properties.forEach((prop) => {
|
|
70
|
+
if (prop.type === 'secure' && !isSecretReference(prop.value)) {
|
|
71
|
+
pipelineResults.push({
|
|
72
|
+
'Pipeline ID': pipelineData.id,
|
|
73
|
+
'Trigger Name': '-',
|
|
74
|
+
'Property Name': prop.name
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
pipelineData?.triggers.forEach((trigger) => {
|
|
80
|
+
trigger.properties?.forEach((prop) => {
|
|
81
|
+
if (prop.type === 'secure' && !isSecretReference(prop.value)) {
|
|
82
|
+
pipelineResults.push({
|
|
83
|
+
'Pipeline ID': pipelineData.id,
|
|
84
|
+
'Trigger Name': trigger.name,
|
|
85
|
+
'Property Name': prop.name
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
if (toolResults.length > 0) {
|
|
95
|
+
logger.print();
|
|
96
|
+
logger.print('The following plain text properties were found in tool integrations bound to the toolchain:');
|
|
97
|
+
logger.table(toolResults);
|
|
98
|
+
};
|
|
99
|
+
if (pipelineResults.length > 0) {
|
|
100
|
+
logger.print();
|
|
101
|
+
logger.print('The following plain text properties were found in Tekton pipeline(s) bound to the toolchain:');
|
|
102
|
+
logger.table(pipelineResults);
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export default command;
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Licensed Materials - Property of IBM
|
|
3
|
+
* (c) Copyright IBM Corporation 2025. All Rights Reserved.
|
|
4
|
+
*
|
|
5
|
+
* Note to U.S. Government Users Restricted Rights:
|
|
6
|
+
* Use, duplication or disclosure restricted by GSA ADP Schedule
|
|
7
|
+
* Contract with IBM Corp.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { exit } from 'node:process';
|
|
11
|
+
import { resolve } from 'node:path'
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
|
|
14
|
+
import { Command, Option } from 'commander';
|
|
15
|
+
|
|
16
|
+
import { parseEnvVar } from './utils/utils.js';
|
|
17
|
+
import { logger, LOG_STAGES } from './utils/logger.js';
|
|
18
|
+
import { setTerraformerEnv, setTerraformEnv, initProviderFile, runTerraformerImport, setupTerraformFiles, runTerraformInit, getNumResourcesPlanned, runTerraformApply, getNumResourcesCreated, getNewToolchainId } from './utils/terraform.js';
|
|
19
|
+
import { getAccountId, getBearerToken, getResourceGroupId, getToolchain } from './utils/requests.js';
|
|
20
|
+
import { validatePrereqsVersions, validateResourceGroupId, validateTag, validateToolchainId, validateToolchainName, validateTools, validateOAuth, warnDuplicateName, validateGritUrl } from './utils/validate.js';
|
|
21
|
+
|
|
22
|
+
import { COPY_TOOLCHAIN_DESC, MIGRATION_DOC_URL, TARGET_REGIONS, SOURCE_REGIONS } from '../config.js';
|
|
23
|
+
|
|
24
|
+
process.on('exit', (code) => {
|
|
25
|
+
if (code !== 0) logger.print(`Need help? Visit ${MIGRATION_DOC_URL} for more troubleshooting information.`);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const LOGS_DIR = '.logs';
|
|
29
|
+
const TEMP_DIR = '.migration-temp'
|
|
30
|
+
const DEBUG_MODE = false; // when true, temp folder is preserved
|
|
31
|
+
const OUTPUT_DIR = 'output-' + new Date().getTime();
|
|
32
|
+
const DRY_RUN = false; // when true, terraform apply does not run
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
const command = new Command('copy-toolchain')
|
|
36
|
+
.summary('Copies a toolchain, including tool integrations and Tekton pipelines, to another region or resource group.')
|
|
37
|
+
.description(COPY_TOOLCHAIN_DESC)
|
|
38
|
+
.optionsGroup('Basic options:')
|
|
39
|
+
.requiredOption('-c, --toolchain-crn <crn>', 'The CRN of the source toolchain to copy')
|
|
40
|
+
.addOption(
|
|
41
|
+
new Option('-r, --region <region>', 'The destination region of the copied toolchain')
|
|
42
|
+
.choices(TARGET_REGIONS)
|
|
43
|
+
.makeOptionMandatory()
|
|
44
|
+
)
|
|
45
|
+
.option('-a --apikey <api key>', 'API Key used to perform the copy. Must have IAM permission to read and create toolchains and S2S authorizations in source and target region / resource group')
|
|
46
|
+
.option('-n, --name <name>', '(Optional) The name of the copied toolchain (default: same name as original)')
|
|
47
|
+
.option('-g, --resource-group <resource group>', '(Optional) The name or ID of destination resource group of the copied toolchain (default: same resource group as original)')
|
|
48
|
+
.option('-t, --tag <tag>', '(Optional) The tag to add to the copied toolchain')
|
|
49
|
+
.helpOption('-h, --help', 'Display help for command')
|
|
50
|
+
.optionsGroup('Advanced options:')
|
|
51
|
+
.option('-d, --terraform-dir <directory path>', '(Optional) The target local directory to store the generated Terraform (.tf) files')
|
|
52
|
+
.option('-D, --dry-run', '(Optional) Skip running terraform apply')
|
|
53
|
+
.option('-f, --force', '(Optional) Force the copy toolchain command to run without user confirmation')
|
|
54
|
+
.option('-S, --skip-s2s', '(Optional) Skip importing toolchain-generated S2S authorizations')
|
|
55
|
+
.option('-T, --skip-disable-triggers', '(Optional) Skip disabling triggers')
|
|
56
|
+
.option('-C, --compact', '(Optional) Generate all resources in resources.tf')
|
|
57
|
+
.option('-v --verbose', '(Optional) Increase log output')
|
|
58
|
+
.option('-s --silent', '(Optional) Suppress non-essential output, only errors and critical warnings are displayed')
|
|
59
|
+
.option('-G --grit-mapping-file <path>', '(Optional) JSON file mapping GRIT project urls to project urls in the target region')
|
|
60
|
+
.showHelpAfterError()
|
|
61
|
+
.hook('preAction', cmd => cmd.showHelpAfterError(false)) // only show help during validation
|
|
62
|
+
.action(main);
|
|
63
|
+
|
|
64
|
+
async function main(options) {
|
|
65
|
+
const sourceToolchainCrn = options.toolchainCrn;
|
|
66
|
+
const targetRegion = options.region;
|
|
67
|
+
const targetRg = options.resourceGroup;
|
|
68
|
+
const outputDir = resolve(options.terraformDir || OUTPUT_DIR);
|
|
69
|
+
const dryRun = options.dryRun || DRY_RUN;
|
|
70
|
+
const skipUserConfirmation = options.force || false;
|
|
71
|
+
const includeS2S = !options.skipS2s;
|
|
72
|
+
const disableTriggers = !options.skipDisableTriggers;
|
|
73
|
+
const isCompact = options.compact || false;
|
|
74
|
+
const verbosity = options.silent ? 0 : options.verbose ? 2 : 1;
|
|
75
|
+
|
|
76
|
+
logger.setVerbosity(verbosity);
|
|
77
|
+
logger.createLogStream(`${LOGS_DIR}/copy-toolchain-${new Date().getTime()}.log`);
|
|
78
|
+
logger.dump(`Options: ${JSON.stringify(options)}\n`);
|
|
79
|
+
|
|
80
|
+
let bearer;
|
|
81
|
+
let sourceToolchainId;
|
|
82
|
+
let sourceRegion;
|
|
83
|
+
let sourceToolchainData;
|
|
84
|
+
let targetToolchainName = options.name;
|
|
85
|
+
let targetTag = options.tag;
|
|
86
|
+
let targetRgId;
|
|
87
|
+
let apiKey = options.apikey;
|
|
88
|
+
let moreTfResources = {};
|
|
89
|
+
let gritMapping = {};
|
|
90
|
+
|
|
91
|
+
// Validate arguments are valid and check if Terraformer and Terraform are installed appropriately
|
|
92
|
+
try {
|
|
93
|
+
validatePrereqsVersions();
|
|
94
|
+
|
|
95
|
+
if (!apiKey) apiKey = parseEnvVar('IBMCLOUD_API_KEY');
|
|
96
|
+
bearer = await getBearerToken(apiKey);
|
|
97
|
+
const accountId = await getAccountId(bearer, apiKey);
|
|
98
|
+
|
|
99
|
+
if (options.gritMappingFile) {
|
|
100
|
+
gritMapping = JSON.parse(fs.readFileSync(resolve(options.gritMappingFile)));
|
|
101
|
+
const gritPromises = [];
|
|
102
|
+
let errorCount = 0;
|
|
103
|
+
|
|
104
|
+
// check validity of mapped values
|
|
105
|
+
Object.entries(gritMapping)
|
|
106
|
+
.forEach(([k, v]) => {
|
|
107
|
+
gritPromises.push(validateGritUrl(bearer, targetRegion, v, true).catch((e) => {
|
|
108
|
+
if (errorCount < 5) {
|
|
109
|
+
logger.error(`Value of key '${k}' from GRIT mapping file is invalid`, LOG_STAGES.setup);
|
|
110
|
+
logger.error(e, LOG_STAGES.setup);
|
|
111
|
+
} else if (errorCount === 5) {
|
|
112
|
+
logger.error(`( ...additional GRIT mapping file error messages truncated )`, LOG_STAGES.setup);
|
|
113
|
+
}
|
|
114
|
+
errorCount += 1;
|
|
115
|
+
}));
|
|
116
|
+
});
|
|
117
|
+
await Promise.all(gritPromises);
|
|
118
|
+
if (errorCount > 0) throw Error(`One or more invalid entries in GRIT mapping file, error count: ${errorCount}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
[sourceToolchainId, sourceRegion] = parseToolchainCrn(sourceToolchainCrn);
|
|
122
|
+
|
|
123
|
+
if (targetToolchainName) validateToolchainName(targetToolchainName);
|
|
124
|
+
if (targetTag) validateTag(targetTag);
|
|
125
|
+
|
|
126
|
+
sourceToolchainData = await logger.withSpinner(getToolchain,
|
|
127
|
+
'Validating toolchain...',
|
|
128
|
+
'Toolchain validated',
|
|
129
|
+
LOG_STAGES.setup,
|
|
130
|
+
bearer,
|
|
131
|
+
sourceToolchainId,
|
|
132
|
+
sourceRegion
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
if (sourceToolchainCrn != sourceToolchainData['crn']) {
|
|
136
|
+
logger.error('Provided toolchain CRN is invalid', LOG_STAGES.setup);
|
|
137
|
+
exit(1);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!targetRg) {
|
|
141
|
+
// reuse resource group if not provided
|
|
142
|
+
targetRgId = sourceToolchainData['resource_group_id'];
|
|
143
|
+
} else {
|
|
144
|
+
targetRgId = await getResourceGroupId(bearer, accountId, targetRg);
|
|
145
|
+
validateResourceGroupId(targetRgId);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// reuse name if not provided
|
|
149
|
+
if (!targetToolchainName) targetToolchainName = sourceToolchainData['name'];
|
|
150
|
+
[targetToolchainName, targetTag] = await warnDuplicateName(bearer, accountId, targetToolchainName, sourceRegion, targetRegion, targetRgId, targetTag, skipUserConfirmation);
|
|
151
|
+
|
|
152
|
+
const allTools = await logger.withSpinner(validateTools,
|
|
153
|
+
'Validating Toolchain Tool(s)...',
|
|
154
|
+
'Toolchain tool(s) validated',
|
|
155
|
+
LOG_STAGES.setup,
|
|
156
|
+
bearer,
|
|
157
|
+
sourceToolchainId,
|
|
158
|
+
sourceRegion,
|
|
159
|
+
skipUserConfirmation
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
// validate git tools OAuth
|
|
163
|
+
await logger.withSpinner(validateOAuth,
|
|
164
|
+
'Validating Git OAuth in target region...',
|
|
165
|
+
'OAuth validated',
|
|
166
|
+
LOG_STAGES.setup,
|
|
167
|
+
bearer,
|
|
168
|
+
allTools,
|
|
169
|
+
targetRegion,
|
|
170
|
+
skipUserConfirmation
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
// collect instances of legacy GHE tool integrations
|
|
174
|
+
const collectGHE = () => {
|
|
175
|
+
moreTfResources['github_integrated'] = [];
|
|
176
|
+
allTools.forEach((t) => {
|
|
177
|
+
if (t.tool_type_id === 'github_integrated') {
|
|
178
|
+
moreTfResources['github_integrated'].push(t);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
collectGHE();
|
|
184
|
+
|
|
185
|
+
logger.info('Arguments and required packages verified, proceeding with copying toolchain...', LOG_STAGES.setup);
|
|
186
|
+
|
|
187
|
+
// Set up temp folder
|
|
188
|
+
if (!fs.existsSync(TEMP_DIR)) {
|
|
189
|
+
fs.mkdirSync(TEMP_DIR);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch (err) {
|
|
193
|
+
if (err.message && err.stack) {
|
|
194
|
+
const errMsg = verbosity > 1 ? err.stack : err.message;
|
|
195
|
+
logger.error(errMsg, LOG_STAGES.setup);
|
|
196
|
+
}
|
|
197
|
+
await handleCleanup();
|
|
198
|
+
exit(1);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const runTerraformer = async () => {
|
|
203
|
+
setTimeout(() => {
|
|
204
|
+
logger.updateSpinnerMsg('Still importing toolchain...');
|
|
205
|
+
}, 5000);
|
|
206
|
+
|
|
207
|
+
setTerraformerEnv(apiKey, sourceToolchainId, includeS2S);
|
|
208
|
+
|
|
209
|
+
await initProviderFile(sourceRegion, TEMP_DIR);
|
|
210
|
+
await runTerraformInit(TEMP_DIR);
|
|
211
|
+
|
|
212
|
+
await runTerraformerImport(sourceRegion, TEMP_DIR, isCompact, verbosity);
|
|
213
|
+
};
|
|
214
|
+
await logger.withSpinner(
|
|
215
|
+
runTerraformer,
|
|
216
|
+
'Importing toolchain...',
|
|
217
|
+
'Toolchain successfully imported using Terraformer',
|
|
218
|
+
LOG_STAGES.terraformer
|
|
219
|
+
);
|
|
220
|
+
} catch (err) {
|
|
221
|
+
if (err.message && err.stack) {
|
|
222
|
+
const errMsg = verbosity > 1 ? err.stack : err.message;
|
|
223
|
+
logger.error(errMsg, LOG_STAGES.terraformer);
|
|
224
|
+
}
|
|
225
|
+
await handleCleanup();
|
|
226
|
+
exit(1);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Prepare for Terraform
|
|
230
|
+
try {
|
|
231
|
+
if (!fs.existsSync(outputDir)) {
|
|
232
|
+
logger.info(`Creating output directory "${outputDir}"...`, LOG_STAGES.terraformer);
|
|
233
|
+
fs.mkdirSync(outputDir);
|
|
234
|
+
} else {
|
|
235
|
+
logger.info(`Output directory "${outputDir}" already exists`, LOG_STAGES.terraformer);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
await setupTerraformFiles({
|
|
239
|
+
token: bearer,
|
|
240
|
+
srcRegion: sourceRegion,
|
|
241
|
+
targetRegion: targetRegion,
|
|
242
|
+
targetTag: targetTag,
|
|
243
|
+
targetToolchainName: targetToolchainName,
|
|
244
|
+
targetRgId: targetRgId,
|
|
245
|
+
disableTriggers: disableTriggers,
|
|
246
|
+
isCompact: isCompact,
|
|
247
|
+
outputDir: outputDir,
|
|
248
|
+
tempDir: TEMP_DIR,
|
|
249
|
+
moreTfResources: moreTfResources,
|
|
250
|
+
gritMapping: gritMapping,
|
|
251
|
+
skipUserConfirmation: skipUserConfirmation
|
|
252
|
+
});
|
|
253
|
+
} catch (err) {
|
|
254
|
+
if (err.message && err.stack) {
|
|
255
|
+
const errMsg = verbosity > 1 ? err.stack : err.message;
|
|
256
|
+
logger.error(errMsg, LOG_STAGES.terraformer);
|
|
257
|
+
}
|
|
258
|
+
await handleCleanup();
|
|
259
|
+
exit(1);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Run Terraform
|
|
263
|
+
try {
|
|
264
|
+
if (!dryRun) {
|
|
265
|
+
setTerraformEnv(verbosity);
|
|
266
|
+
|
|
267
|
+
await logger.withSpinner(runTerraformInit,
|
|
268
|
+
'Running terraform init...',
|
|
269
|
+
'Terraform successfully initialized',
|
|
270
|
+
LOG_STAGES.tf,
|
|
271
|
+
outputDir
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
logger.info(`DRY_RUN: ${dryRun}, running terraform apply...`, LOG_STAGES.tf);
|
|
275
|
+
|
|
276
|
+
// get total planned resources before applying
|
|
277
|
+
const numResourcesPlanned = await getNumResourcesPlanned(outputDir);
|
|
278
|
+
|
|
279
|
+
let applyErrors = false;
|
|
280
|
+
|
|
281
|
+
await runTerraformApply(skipUserConfirmation, outputDir, verbosity).catch((err) => {
|
|
282
|
+
logger.error(err, LOG_STAGES.tf);
|
|
283
|
+
applyErrors = true;
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
const newTcId = await getNewToolchainId(outputDir);
|
|
287
|
+
const numResourcesCreated = await getNumResourcesCreated(outputDir);
|
|
288
|
+
|
|
289
|
+
logger.print('\n');
|
|
290
|
+
logger.info(`Toolchain "${sourceToolchainData['name']}" from ${sourceRegion} was cloned to "${targetToolchainName ?? sourceToolchainData['name']}" in ${targetRegion} ${applyErrors ? 'with some errors' : 'successfully'}, with ${numResourcesCreated} / ${numResourcesPlanned} resources created!`, LOG_STAGES.info);
|
|
291
|
+
if (newTcId) logger.info(`See cloned toolchain: https://cloud.ibm.com/devops/toolchains/${newTcId}?env_id=ibm:yp:${targetRegion}`, LOG_STAGES.info, true);
|
|
292
|
+
} else {
|
|
293
|
+
logger.info(`DRY_RUN: ${dryRun}, skipping terraform apply...`, LOG_STAGES.tf);
|
|
294
|
+
}
|
|
295
|
+
} catch (err) {
|
|
296
|
+
if (err.message && err.stack) {
|
|
297
|
+
const errMsg = verbosity > 1 ? err.stack : err.message;
|
|
298
|
+
logger.error(errMsg, LOG_STAGES.tf);
|
|
299
|
+
}
|
|
300
|
+
await handleCleanup();
|
|
301
|
+
exit(1);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
await handleCleanup();
|
|
305
|
+
exit(0);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function handleCleanup() {
|
|
309
|
+
if (!DEBUG_MODE) {
|
|
310
|
+
if (fs.existsSync(TEMP_DIR)) fs.rmSync(TEMP_DIR, { recursive: true });
|
|
311
|
+
}
|
|
312
|
+
await logger.close();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// parses crn arg into toolchain ID and region
|
|
316
|
+
function parseToolchainCrn(crn) {
|
|
317
|
+
// doesn't strictly check crn format
|
|
318
|
+
const pattern = /^crn:.*:.*:.*:toolchain:.*:.*:.*::$/;
|
|
319
|
+
if (typeof crn === 'string' && pattern.test(crn)) {
|
|
320
|
+
const crnParts = crn.toLowerCase().split(':');
|
|
321
|
+
if (crnParts.length === 10 && SOURCE_REGIONS.includes(crnParts[5])) {
|
|
322
|
+
try {
|
|
323
|
+
validateToolchainId(crnParts[7]);
|
|
324
|
+
} catch {
|
|
325
|
+
throw Error('Provided toolchain CRN is invalid');
|
|
326
|
+
}
|
|
327
|
+
return [crnParts[7], crnParts[5]];
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
throw Error('Provided toolchain CRN is invalid');
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export default command;
|