login-action/src/aws.ts

52 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-08-21 20:45:16 +08:00
import * as semver from 'semver';
import * as io from '@actions/io';
import * as execm from './exec';
export const isECR = async (registry: string): Promise<boolean> => {
return registry.includes('amazonaws');
};
2020-08-21 21:07:43 +08:00
export const getRegion = async (registry: string): Promise<string> => {
return registry.substring(registry.indexOf('ecr.') + 4, registry.indexOf('.amazonaws'));
};
2020-08-21 20:45:16 +08:00
export const getCLI = async (): Promise<string> => {
return io.which('aws', true);
};
2020-08-21 20:56:11 +08:00
export const getCLICmdOutput = async (args: string[]): Promise<string> => {
return execm.exec(await getCLI(), args, true).then(res => {
2020-08-21 20:45:16 +08:00
if (res.stderr != '' && !res.success) {
throw new Error(res.stderr);
2020-08-21 21:07:43 +08:00
} else if (res.stderr != '') {
return res.stderr.trim();
} else {
return res.stdout.trim();
2020-08-21 20:45:16 +08:00
}
});
};
2020-08-21 21:27:22 +08:00
export const getCLIVersion = async (): Promise<string> => {
2020-08-21 20:56:11 +08:00
return parseCLIVersion(await getCLICmdOutput(['--version']));
};
2020-08-21 21:27:22 +08:00
export const parseCLIVersion = async (stdout: string): Promise<string> => {
2020-08-21 20:45:16 +08:00
const matches = /aws-cli\/([0-9.]+)/.exec(stdout);
2020-08-21 21:27:22 +08:00
if (!matches) {
throw new Error(`Cannot parse AWS CLI version`);
}
return semver.clean(matches[1]);
};
export const getECRLoginCmd = async (cliVersion: string, registry: string, region: string): Promise<string> => {
if (semver.satisfies(cliVersion, '>=2.0.0')) {
return getCLICmdOutput(['ecr', 'get-login-password', '--region', region]).then(pwd => {
return `docker login --username AWS --password ${pwd} ${registry}`;
});
} else {
return getCLICmdOutput(['ecr', 'get-login', '--region', region, '--no-include-email']).then(dockerLoginCmd => {
return dockerLoginCmd;
});
2020-08-21 20:45:16 +08:00
}
};