-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.ts
159 lines (146 loc) · 6.89 KB
/
main.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
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 AZ_CLI_VERSION_DEFAULT_VALUE = 'agentazcliversion'
const prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
const AZ_CLI_TAG_lIST_URL = "https://mcr.microsoft.com/v2/azure-cli/tags/list";
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}@v2_${usrAgentRepo}_${process.env.RUNNER_ENVIRONMENT}_${process.env.GITHUB_RUN_ID}`;
process.env.AZURE_HTTP_USER_AGENT = userAgentString;
var scriptFileName: string = '';
const CONTAINER_NAME = `MICROSOFT_AZURE_CLI_${getCurrentTime()}_CONTAINER`;
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"]
} 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.')
}
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);
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>> => {
try {
const response = await fetch(AZ_CLI_TAG_lIST_URL);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, errorText: ${errorText}`);
}
const data = await response.json();
if (data && data.tags) {
return data.tags;
}
else {
throw new Error('Response data does not contain tags.');
}
}
catch (error) {
core.warning(`Unable to fetch all az cli versions with Error: ${error}. Skipping the version check.`);
}
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)
}
}