/
index.js
94 lines (81 loc) · 2.98 KB
/
index.js
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
const core = require('@actions/core');
const exec = require('@actions/exec');
const aws = require('aws-sdk');
function replaceSpecialCharacters(registryUri) {
return registryUri.replace(/[^a-zA-Z0-9_]+/g, '_')
}
async function run() {
const registryUriState = [];
const skipLogout = core.getInput('skip-logout', { required: false });
try {
const registries = core.getInput('registries', { required: false });
// Get the ECR authorization token
const ecr = new aws.ECR({
customUserAgent: 'amazon-ecr-login-for-github-actions'
});
const authTokenRequest = {};
if (registries) {
const registryIds = registries.split(',');
core.debug(`Requesting auth token for ${registryIds.length} registries:`);
for (const id of registryIds) {
core.debug(` '${id}'`);
}
authTokenRequest.registryIds = registryIds;
}
const authTokenResponse = await ecr.getAuthorizationToken(authTokenRequest).promise();
if (!Array.isArray(authTokenResponse.authorizationData) || !authTokenResponse.authorizationData.length) {
throw new Error('Could not retrieve an authorization token from Amazon ECR');
}
for (const authData of authTokenResponse.authorizationData) {
const authToken = Buffer.from(authData.authorizationToken, 'base64').toString('utf-8');
const creds = authToken.split(':', 2);
const proxyEndpoint = authData.proxyEndpoint;
const registryUri = proxyEndpoint.replace(/^https?:\/\//,'');
if (authTokenResponse.authorizationData.length == 1) {
// output the registry URI if this action is doing a single registry login
core.setOutput('registry', registryUri);
}
// Execute the docker login command
let doLoginStdout = '';
let doLoginStderr = '';
const exitCode = await exec.exec('docker login', ['-u', creds[0], '-p', creds[1], proxyEndpoint], {
silent: true,
ignoreReturnCode: true,
listeners: {
stdout: (data) => {
doLoginStdout += data.toString();
},
stderr: (data) => {
doLoginStderr += data.toString();
}
}
});
if (exitCode != 0) {
core.debug(doLoginStdout);
throw new Error('Could not login: ' + doLoginStderr);
}
const secretSuffix = replaceSpecialCharacters(registryUri)
core.setOutput(`docker_username_${secretSuffix}`, creds[0]);
core.setOutput(`docker_password_${secretSuffix}`, creds[1]);
registryUriState.push(registryUri);
}
}
catch (error) {
core.setFailed(error.message);
}
// Pass the logged-in registry URIs to the post action for logout
if (registryUriState.length) {
if (!skipLogout) {
core.saveState('registries', registryUriState.join());
}
core.debug(`'skip-logout' is ${skipLogout} for ${registryUriState.length} registries.`);
}
}
module.exports = {
run,
replaceSpecialCharacters
};
/* istanbul ignore next */
if (require.main === module) {
run();
}