-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathmain.ts
More file actions
220 lines (201 loc) · 9.45 KB
/
main.ts
File metadata and controls
220 lines (201 loc) · 9.45 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
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as io from '@actions/io';
import * as os from 'os';
import * as path from 'path';
import * as crypto from 'crypto';
const util = require('util');
const cpExec = util.promisify(require('child_process').exec);
import { createScriptFile, TEMP_DIRECTORY, NullOutstreamStringWritable, deleteFile, getCurrentTime, checkIfEnvironmentVariableIsOmitted } from './utils';
const START_SCRIPT_EXECUTION_MARKER: string = "Starting script execution via docker image mcr.microsoft.com/azure-cli:";
const START_SCRIPT_DIRECT_EXECUTION_MARKER: string = "Starting script execution via az in the agent:";
const AZ_CLI_VERSION_DEFAULT_VALUE = 'agentazcliversion'
const prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
export async function main() {
let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex');
let actionName = 'AzureCLIAction';
let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}_${usrAgentRepo}`;
process.env.AZURE_HTTP_USER_AGENT = userAgentString;
var scriptFileName: string = '';
const CONTAINER_NAME = `MICROSOFT_AZURE_CLI_${getCurrentTime()}_CONTAINER`;
let executingInContainer: boolean = true;
try {
if (process.env.RUNNER_OS != 'Linux') {
throw new Error('Please use Linux-based OS as a runner.');
}
let inlineScript: string = core.getInput('inlineScript', { required: true });
let azcliversion: string = core.getInput('azcliversion', { required: false }).trim().toLowerCase();
if (azcliversion == AZ_CLI_VERSION_DEFAULT_VALUE) {
try {
const { stdout } = await cpExec('az version');
azcliversion = JSON.parse(stdout)["azure-cli"]
executingInContainer = false;
console.log(`az cli version from agent: ${azcliversion}. It will be used for script execution.`);
} catch (err) {
console.log('Failed to fetch az cli version from agent. Reverting back to latest.')
azcliversion = 'latest'
}
}
if (!(await checkIfValidCLIVersion(azcliversion))) {
core.error('Please enter a valid azure cli version. \nSee available versions: https://github.com/Azure/azure-cli/releases.');
throw new Error('Please enter a valid azure cli version. \nSee available versions: https://github.com/Azure/azure-cli/releases.')
}
if (!inlineScript.trim()) {
core.error('Please enter a valid script.');
throw new Error('Please enter a valid script.')
}
if (executingInContainer == false) {
try {
inlineScript = ` set -e >&2; echo '${START_SCRIPT_DIRECT_EXECUTION_MARKER}' >&2; ${inlineScript}`;
scriptFileName = await createScriptFile(inlineScript);
let args: string[] = ["--noprofile", "--norc", "-e", `${TEMP_DIRECTORY}/${scriptFileName}`];
console.log(`${START_SCRIPT_DIRECT_EXECUTION_MARKER}`);
await executeBashCommand(args);
console.log("az script ran successfully.");
return;
} catch (err) {
console.log('Failed to fetch az cli version from agent. Reverting back to execution in container.')
}
}
inlineScript = ` set -e >&2; echo '${START_SCRIPT_EXECUTION_MARKER}' >&2; ${inlineScript}`;
scriptFileName = await createScriptFile(inlineScript);
/*
For the docker run command, we are doing the following
- Set the working directory for docker continer
- volume mount the GITHUB_WORKSPACE env variable (path where users checkout code is present) to work directory of container
- voulme mount .azure session token file between host and container,
- volume mount temp directory between host and container, inline script file is created in temp directory
*/
let args: string[] = ["run", "--workdir", `${process.env.GITHUB_WORKSPACE}`,
"-v", `${process.env.GITHUB_WORKSPACE}:${process.env.GITHUB_WORKSPACE}`,
"-v", `${process.env.HOME}/.azure:/root/.azure`,
"-v", `${TEMP_DIRECTORY}:${TEMP_DIRECTORY}`
];
for (let key in process.env) {
if (!checkIfEnvironmentVariableIsOmitted(key) && process.env[key]) {
args.push("-e", `${key}=${process.env[key]}`);
}
}
args.push("--name", CONTAINER_NAME,
`mcr.microsoft.com/azure-cli:${azcliversion}`,
"bash", "--noprofile", "--norc", "-e", `${TEMP_DIRECTORY}/${scriptFileName}`);
console.log(`${START_SCRIPT_EXECUTION_MARKER}${azcliversion}`);
await executeDockerCommand(args);
console.log("az script ran successfully.");
}
catch (error) {
core.error(error);
throw error;
}
finally {
// clean up
const scriptFilePath: string = path.join(TEMP_DIRECTORY, scriptFileName);
await deleteFile(scriptFilePath);
if (executingInContainer) {
console.log("cleaning up container...");
await executeDockerCommand(["rm", "--force", CONTAINER_NAME], true);
}
}
};
const checkIfValidCLIVersion = async (azcliversion: string): Promise<boolean> => {
const allVersions: Array<string> = await getAllAzCliVersions();
if (!allVersions || allVersions.length == 0) {
return true;
}
return allVersions.some((eachVersion) => eachVersion.toLowerCase() === azcliversion);
}
const getAllAzCliVersions = async (): Promise<Array<string>> => {
var outStream: string = '';
var execOptions: any = {
outStream: new NullOutstreamStringWritable({ decodeStrings: false }),
listeners: {
stdout: (data: any) => outStream += data.toString() + os.EOL, //outstream contains the list of all the az cli versions
}
};
try {
await exec.exec("curl", ["--location", "-s", "https://mcr.microsoft.com/v2/azure-cli/tags/list"], execOptions)
if (outStream && JSON.parse(outStream).tags) {
return JSON.parse(outStream).tags;
}
} catch (error) {
// if output is 404 page not found, please verify the url
core.warning(`Unable to fetch all az cli versions, please report it as an issue on https://github.com/Azure/CLI/issues. Output: ${outStream}, Error: ${error}`);
}
return [];
}
const executeDockerCommand = async (args: string[], continueOnError: boolean = false): Promise<void> => {
const dockerTool: string = await io.which("docker", true);
var errorStream: string = '';
var shouldOutputErrorStream: boolean = false;
var execOptions: any = {
outStream: new NullOutstreamStringWritable({ decodeStrings: false }),
listeners: {
stdout: (data: any) => console.log(data.toString()), //to log the script output while the script is running.
errline: (data: string) => {
if (!shouldOutputErrorStream) {
errorStream += data + os.EOL;
}
else {
console.log(data);
}
if (data.trim() === START_SCRIPT_EXECUTION_MARKER) {
shouldOutputErrorStream = true;
errorStream = ''; // Flush the container logs. After this, script error logs will be tracked.
}
}
}
};
var exitCode;
try {
exitCode = await exec.exec(dockerTool, args, execOptions);
} catch (error) {
if (!continueOnError) {
throw error;
}
core.warning(error);
}
finally {
if (exitCode !== 0 && !continueOnError) {
throw new Error(errorStream || 'az cli script failed.');
}
core.warning(errorStream)
}
}
const executeBashCommand = async (args: string[], continueOnError: boolean = false): Promise<void> => {
const bash: string = await io.which("bash", true);
var errorStream: string = '';
var shouldOutputErrorStream: boolean = false;
var execOptions: any = {
outStream: new NullOutstreamStringWritable({ decodeStrings: false }),
listeners: {
stdout: (data: any) => console.log(data.toString()), //to log the script output while the script is running.
errline: (data: string) => {
if (!shouldOutputErrorStream) {
errorStream += data + os.EOL;
}
else {
console.log(data);
}
if (data.trim() === START_SCRIPT_EXECUTION_MARKER) {
shouldOutputErrorStream = true;
errorStream = ''; // Flush the container logs. After this, script error logs will be tracked.
}
}
}
};
var exitCode;
try {
exitCode = await exec.exec(bash, args, execOptions);
} catch (error) {
if (!continueOnError) {
throw error;
}
core.warning(error);
}
finally {
if (exitCode !== 0 && !continueOnError) {
throw new Error(errorStream || 'az cli script failed.');
}
core.warning(errorStream)
}
}