-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathazureclitask.ts
398 lines (344 loc) · 17.6 KB
/
azureclitask.ts
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
import path = require("path");
import tl = require("azure-pipelines-task-lib/task");
import fs = require("fs");
import { IExecSyncResult } from 'azure-pipelines-task-lib/toolrunner';
import { Utility } from "./src/Utility";
import { ScriptType, ScriptTypeFactory } from "./src/ScriptType";
import { getSystemAccessToken } from 'azure-pipelines-tasks-artifacts-common/webapi';
import { getHandlerFromToken, WebApi } from "azure-devops-node-api";
import { ITaskApi } from "azure-devops-node-api/TaskApi";
#if NODE20
const nodeVersion = parseInt(process.version.split('.')[0].replace('v', ''));
if (nodeVersion > 16) {
require("dns").setDefaultResultOrder("ipv4first");
tl.debug("Set default DNS lookup order to ipv4 first");
}
if (nodeVersion > 19) {
require("net").setDefaultAutoSelectFamily(false);
tl.debug("Set default auto select family to false");
}
#endif
const FAIL_ON_STDERR: string = "FAIL_ON_STDERR";
const AZ_SESSION_REFRESH_INTERVAL_MS: number = 480000; // 8 minutes, 2 minutes before IdToken expiry date
export class azureclitask {
public static async runMain(): Promise<void> {
var toolExecutionError = null;
var exitCode: number = 0;
if(tl.getBoolFeatureFlag('AZP_AZURECLIV2_SETUP_PROXY_ENV')) {
const proxyConfig: tl.ProxyConfiguration | null = tl.getHttpProxyConfiguration();
if (proxyConfig) {
process.env['HTTP_PROXY'] = proxyConfig.proxyFormattedUrl;
process.env['HTTPS_PROXY'] = proxyConfig.proxyFormattedUrl;
tl.debug(tl.loc('ProxyConfigMessage', proxyConfig.proxyUrl));
}
}
try{
var scriptType: ScriptType = ScriptTypeFactory.getSriptType();
var tool: any = await scriptType.getTool();
var cwd: string = tl.getPathInput("cwd", true, false);
if (tl.getInput("scriptLocation", true).toLowerCase() === "scriptPath" && !tl.filePathSupplied("cwd")) {
cwd = path.dirname(tl.getPathInput("scriptPath", true, true));
}
// determines whether output to stderr will fail a task.
// some tools write progress and other warnings to stderr. scripts can also redirect.
var failOnStdErr: boolean = tl.getBoolInput("failOnStandardError", false);
tl.mkdirP(cwd);
tl.cd(cwd);
const azVersionResult: IExecSyncResult = tl.execSync("az", "--version");
Utility.throwIfError(azVersionResult);
this.isSupportCertificateParameter = this.isAzVersionGreaterOrEqual(azVersionResult.stdout, "2.66.0");
// set az cli config dir
this.setConfigDirectory();
this.setAzureCloudBasedOnServiceEndpoint();
var connectedService: string = tl.getInput("connectedServiceNameARM", true);
const authorizationScheme = tl.getEndpointAuthorizationScheme(connectedService, true).toLowerCase();
await this.loginAzureRM(connectedService);
var keepAzSessionActive: boolean = tl.getBoolInput('keepAzSessionActive', false);
var stopRefreshingSession: () => void = () => {};
if (keepAzSessionActive) {
// This is a tactical workaround to keep the session active for the duration of the task to avoid AADSTS700024 errors.
// This is a temporary solution until the az cli provides a way to refresh the session.
if (authorizationScheme !== 'workloadidentityfederation') {
const errorMessage = tl.loc('KeepingAzSessionActiveUnsupportedScheme', authorizationScheme);
tl.error(errorMessage);
throw errorMessage;
}
stopRefreshingSession = this.keepRefreshingAzSession(connectedService);
}
let errLinesCount: number = 0;
let aggregatedErrorLines: string[] = [];
tool.on('errline', (errorLine: string) => {
if (errLinesCount < 10) {
aggregatedErrorLines.push(errorLine);
}
errLinesCount++;
});
const addSpnToEnvironment: boolean = tl.getBoolInput('addSpnToEnvironment', false);
if (!!addSpnToEnvironment && authorizationScheme == 'serviceprincipal') {
exitCode = await tool.exec({
failOnStdErr: false,
ignoreReturnCode: true,
env: {
...process.env,
...{ servicePrincipalId: this.servicePrincipalId, servicePrincipalKey: this.servicePrincipalKey, tenantId: this.tenantId }
}
});
} else if (!!addSpnToEnvironment && authorizationScheme == 'workloadidentityfederation') {
exitCode = await tool.exec({
failOnStdErr: false,
ignoreReturnCode: true,
env: {
...process.env,
...{ servicePrincipalId: this.servicePrincipalId, idToken: this.federatedToken, tenantId: this.tenantId }
}
});
} else {
exitCode = await tool.exec({
failOnStdErr: false,
ignoreReturnCode: true
});
}
if (failOnStdErr && aggregatedErrorLines.length > 0) {
let error = FAIL_ON_STDERR;
tl.error(aggregatedErrorLines.join("\n"), tl.IssueSource.CustomerScript);
throw error;
}
}
catch (err) {
toolExecutionError = err;
if (err.stderr) {
toolExecutionError = err.stderr;
}
}
finally {
if (keepAzSessionActive) {
stopRefreshingSession();
}
if (scriptType) {
await scriptType.cleanUp();
}
if (this.cliPasswordPath) {
tl.debug('Removing spn certificate file');
tl.rmRF(this.cliPasswordPath);
}
//set the task result to either succeeded or failed based on error was thrown or not
if(toolExecutionError === FAIL_ON_STDERR) {
tl.setResult(tl.TaskResult.Failed, tl.loc("ScriptFailedStdErr"));
} else if (toolExecutionError) {
let message = tl.loc('ScriptFailed', toolExecutionError);
if (typeof toolExecutionError === 'string') {
const expiredSecretErrorCode = 'AADSTS7000222';
let serviceEndpointSecretIsExpired = toolExecutionError.indexOf(expiredSecretErrorCode) >= 0;
if (serviceEndpointSecretIsExpired) {
const organizationURL = tl.getVariable('System.CollectionUri');
const projectName = tl.getVariable('System.TeamProject');
const serviceConnectionLink = encodeURI(`${organizationURL}${projectName}/_settings/adminservices?resourceId=${connectedService}`);
message = tl.loc('ExpiredServicePrincipalMessageWithLink', serviceConnectionLink);
}
}
// only Aggregation error contains array of errors
if (toolExecutionError.errors) {
// Iterates through array and log errors separately
toolExecutionError.errors.forEach((error) => {
tl.error(error.message, tl.IssueSource.TaskInternal);
});
// fail with main message
tl.setResult(tl.TaskResult.Failed, toolExecutionError.message);
} else {
tl.setResult(tl.TaskResult.Failed, message);
}
tl.setResult(tl.TaskResult.Failed, message);
} else if (exitCode != 0){
tl.setResult(tl.TaskResult.Failed, tl.loc("ScriptFailedWithExitCode", exitCode));
}
else {
tl.setResult(tl.TaskResult.Succeeded, tl.loc("ScriptReturnCode", 0));
}
//Logout of Azure if logged in
if (this.isLoggedIn) {
this.logoutAzure();
}
if (process.env.AZURESUBSCRIPTION_SERVICE_CONNECTION_ID && process.env.AZURESUBSCRIPTION_SERVICE_CONNECTION_ID !== "")
{
process.env.AZURESUBSCRIPTION_SERVICE_CONNECTION_ID = '';
process.env.AZURESUBSCRIPTION_CLIENT_ID = '';
process.env.AZURESUBSCRIPTION_TENANT_ID = '';
}
}
}
private static isLoggedIn: boolean = false;
private static cliPasswordPath: string = null;
private static servicePrincipalId: string = null;
private static servicePrincipalKey: string = null;
private static federatedToken: string = null;
private static tenantId: string = null;
private static isSupportCertificateParameter: boolean = false;
private static isAzVersionGreaterOrEqual(azVersionResultOutput, versionToCompare) {
try {
const versionMatch = azVersionResultOutput.match(/azure-cli\s+(\d+\.\d+\.\d+)/);
if (!versionMatch || versionMatch.length < 2) {
tl.error(`Can't parse az version from: ${azVersionResultOutput}`);
return false;
}
const currentVersion = versionMatch[1];
tl.debug(`Current Azure CLI version: ${currentVersion}`);
// Parse both versions into major, minor, patch components
const [currentMajor, currentMinor, currentPatch] = currentVersion.split('.').map(Number);
const [compareMajor, compareMinor, comparePatch] = versionToCompare.split('.').map(Number);
// Compare versions
if (currentMajor > compareMajor) return true;
if (currentMajor < compareMajor) return false;
if (currentMinor > compareMinor) return true;
if (currentMinor < compareMinor) return false;
return currentPatch >= comparePatch;
} catch (error) {
tl.error(`Error checking Azure CLI version: ${error.message}`);
return false;
}
}
private static async loginAzureRM(connectedService: string):Promise<void> {
var authScheme: string = tl.getEndpointAuthorizationScheme(connectedService, true);
var subscriptionID: string = tl.getEndpointDataParameter(connectedService, "SubscriptionID", true);
var visibleAzLogin: boolean = tl.getBoolInput("visibleAzLogin", true);
if (authScheme.toLowerCase() == "workloadidentityfederation") {
var servicePrincipalId: string = tl.getEndpointAuthorizationParameter(connectedService, "serviceprincipalid", false);
var tenantId: string = tl.getEndpointAuthorizationParameter(connectedService, "tenantid", false);
const federatedToken = await this.getIdToken(connectedService);
tl.setSecret(federatedToken);
let args = `login --service-principal -u "${servicePrincipalId}" --tenant "${tenantId}" --allow-no-subscriptions --federated-token "${federatedToken}"`;
if(!visibleAzLogin ){
args += ` --output none`;
}
//login using OpenID Connect federation
Utility.throwIfError(tl.execSync("az", args), tl.loc("LoginFailed"));
this.servicePrincipalId = servicePrincipalId;
this.federatedToken = federatedToken;
this.tenantId = tenantId;
process.env.AZURESUBSCRIPTION_SERVICE_CONNECTION_ID = connectedService;
process.env.AZURESUBSCRIPTION_CLIENT_ID = servicePrincipalId;
process.env.AZURESUBSCRIPTION_TENANT_ID = tenantId;
}
else if (authScheme.toLowerCase() == "serviceprincipal") {
let authType: string = tl.getEndpointAuthorizationParameter(connectedService, 'authenticationType', true);
let cliPassword: string = null;
let authParam: string = "--password";
var servicePrincipalId: string = tl.getEndpointAuthorizationParameter(connectedService, "serviceprincipalid", false);
var tenantId: string = tl.getEndpointAuthorizationParameter(connectedService, "tenantid", false);
this.servicePrincipalId = servicePrincipalId;
this.tenantId = tenantId;
if (authType == "spnCertificate") {
tl.debug('certificate based endpoint');
if(this.isSupportCertificateParameter) {
authParam = "--certificate";
}
let certificateContent: string = tl.getEndpointAuthorizationParameter(connectedService, "servicePrincipalCertificate", false);
cliPassword = path.join(tl.getVariable('Agent.TempDirectory') || tl.getVariable('system.DefaultWorkingDirectory'), 'spnCert.pem');
fs.writeFileSync(cliPassword, certificateContent);
this.cliPasswordPath = cliPassword;
}
else {
tl.debug('key based endpoint');
cliPassword = tl.getEndpointAuthorizationParameter(connectedService, "serviceprincipalkey", false);
this.servicePrincipalKey = cliPassword;
}
let escapedCliPassword = cliPassword.replace(/"/g, '\\"');
tl.setSecret(escapedCliPassword.replace(/\\/g, '\"'));
//login using svn
if (visibleAzLogin) {
Utility.throwIfError(tl.execSync("az", `login --service-principal -u "${servicePrincipalId}" ${authParam}="${escapedCliPassword}" --tenant "${tenantId}" --allow-no-subscriptions`), tl.loc("LoginFailed"));
}
else {
Utility.throwIfError(tl.execSync("az", `login --service-principal -u "${servicePrincipalId}" ${authParam}="${escapedCliPassword}" --tenant "${tenantId}" --allow-no-subscriptions --output none`), tl.loc("LoginFailed"));
}
}
else if(authScheme.toLowerCase() == "managedserviceidentity") {
//login using msi
if (visibleAzLogin) {
Utility.throwIfError(tl.execSync("az", "login --identity"), tl.loc("MSILoginFailed"));
}
else {
Utility.throwIfError(tl.execSync("az", "login --identity --output none"), tl.loc("MSILoginFailed"));
}
}
else {
throw tl.loc('AuthSchemeNotSupported', authScheme);
}
this.isLoggedIn = true;
if (!!subscriptionID) {
//set the subscription imported to the current subscription
Utility.throwIfError(tl.execSync("az", "account set --subscription \"" + subscriptionID + "\""), tl.loc("ErrorInSettingUpSubscription"));
}
}
private static setConfigDirectory(): void {
if (tl.getBoolInput("useGlobalConfig")) {
return;
}
if (!!tl.getVariable('Agent.TempDirectory')) {
var azCliConfigPath = path.join(tl.getVariable('Agent.TempDirectory'), ".azclitask");
console.log(tl.loc('SettingAzureConfigDir', azCliConfigPath));
process.env['AZURE_CONFIG_DIR'] = azCliConfigPath;
} else {
console.warn(tl.loc('GlobalCliConfigAgentVersionWarning'));
}
}
private static setAzureCloudBasedOnServiceEndpoint(): void {
var connectedService: string = tl.getInput("connectedServiceNameARM", true);
var environment = tl.getEndpointDataParameter(connectedService, 'environment', true);
if (!!environment) {
console.log(tl.loc('SettingAzureCloud', environment));
Utility.throwIfError(tl.execSync("az", "cloud set -n " + environment));
}
}
private static logoutAzure() {
try {
tl.execSync("az", " account clear");
}
catch (err) {
// task should not fail if logout doesn`t occur
tl.warning(tl.loc("FailedToLogout"));
}
}
private static async getIdToken(connectedService: string) : Promise<string> {
#if NODE20
// since node19 default node's GlobalAgent has timeout 5sec
// keepAlive is set to true to avoid creating default node's GlobalAgent
const webApiOptions = {
keepAlive: true
}
#endif
const jobId = tl.getVariable("System.JobId");
const planId = tl.getVariable("System.PlanId");
const projectId = tl.getVariable("System.TeamProjectId");
const hub = tl.getVariable("System.HostType");
const uri = tl.getVariable("System.CollectionUri");
const token = getSystemAccessToken();
const authHandler = getHandlerFromToken(token);
#if NODE20
const connection = new WebApi(uri, authHandler, webApiOptions);
#else
const connection = new WebApi(uri, authHandler);
#endif
const api: ITaskApi = await connection.getTaskApi();
const response = await api.createOidcToken({}, projectId, hub, planId, jobId, connectedService);
if (response == null) {
return null;
}
return response.oidcToken;
}
private static keepRefreshingAzSession(connectedService: string): () => void {
const intervalId = setInterval(async () => {
try {
tl.debug(tl.loc('RefreshingAzSession'));
await this.loginAzureRM(connectedService);
} catch (error) {
tl.warning(tl.loc('FailedToRefreshAzSession', error));
}
}, AZ_SESSION_REFRESH_INTERVAL_MS);
return () => clearInterval(intervalId);
}
}
tl.setResourcePath(path.join(__dirname, "task.json"));
if (!Utility.checkIfAzurePythonSdkIsInstalled()) {
tl.setResult(tl.TaskResult.Failed, tl.loc("AzureSDKNotFound"));
}
azureclitask.runMain();