Add ability to login to ECR repositories

This commit is contained in:
Philipp Trulson 2022-06-02 19:07:25 +02:00
parent 8a0c05b53e
commit 3364306a59
No known key found for this signature in database
GPG key ID: 73CBABEA8D422ABC
7 changed files with 1156 additions and 7 deletions

54
src/ecr.ts Normal file
View file

@ -0,0 +1,54 @@
import * as core from "@actions/core";
import { ECR } from "@aws-sdk/client-ecr";
const ecrRegistryRegex = /^(([0-9]{12})\.dkr\.ecr\.(.+)\.amazonaws\.com(.cn)?)(\/([^:]+)(:.+)?)?$/;
export interface ECRData {
username: string;
password: string;
}
export function isECR(registry: string): boolean {
return ecrRegistryRegex.test(registry);
}
function getRegion(registry: string): string {
const matches = registry.match(ecrRegistryRegex);
if (!matches) {
return "";
}
return matches[3];
}
function getAccountID(registry: string): string {
const matches = registry.match(ecrRegistryRegex);
if (!matches) {
return "";
}
return matches[2];
}
export async function getECRToken(registry: string, username: string, password: string): Promise<ECRData> {
const ecr = new ECR({
credentials: {
accessKeyId: username,
secretAccessKey: password,
},
region: getRegion(registry),
});
const response = await ecr.getAuthorizationToken({ registryIds: [ getAccountID(registry) ] });
if (!Array.isArray(response.authorizationData) || response.authorizationData.length === 0) {
throw new Error("Unable to fetch ECR credentials from AWS!");
}
const tokenString = Buffer.from(response.authorizationData[0].authorizationToken || "", "base64").toString("utf-8");
const ecrCredentials = tokenString.split(":", 2);
// Hide auth token in actions logs
core.setSecret(ecrCredentials[1]);
return {
username: ecrCredentials[0],
password: ecrCredentials[1],
};
}

View file

@ -8,6 +8,7 @@ import { promises as fs } from "fs";
import * as io from "@actions/io";
import * as os from "os";
import * as path from "path";
import * as ecr from "./ecr";
import { execute, getDockerConfigJson } from "./utils";
import * as stateHelper from "./state-helper";
import { Inputs } from "./generated/inputs-outputs";
@ -31,11 +32,18 @@ async function run(): Promise<void> {
}
registry = core.getInput(Inputs.REGISTRY, { required: true });
const username = core.getInput(Inputs.USERNAME, { required: true });
const password = core.getInput(Inputs.PASSWORD, { required: true });
let username = core.getInput(Inputs.USERNAME, { required: true });
let password = core.getInput(Inputs.PASSWORD, { required: true });
const logout = core.getInput(Inputs.LOGOUT) || "true";
const authFilePath = core.getInput(Inputs.AUTH_FILE_PATH);
if (ecr.isECR(registry)) {
core.info(`💡 Detected ${registry} as an ECR repository`);
const ECRData = await ecr.getECRToken(registry, username, password);
username = ECRData.username;
password = ECRData.password;
}
stateHelper.setRegistry(registry);
stateHelper.setLogout(logout);