Create and update command should use make file in photowall repo (#16)

* fixed build

* create and update command uses make file in repo
This commit is contained in:
Arwid Thornström
2022-12-07 14:34:30 +01:00
committed by GitHub
parent c7090fc1f3
commit 780354d8f8
5 changed files with 29 additions and 151 deletions
@@ -1,28 +1,10 @@
import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu' import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu'
import { exit } from 'process';
const chalk = require('chalk'); const chalk = require('chalk');
const { AutoComplete, Input, Confirm } = require('enquirer'); const { AutoComplete, Input, Confirm } = require('enquirer');
import { defaultMenuSettings, getSettings } from '../../../../globals'; import { defaultMenuSettings, getSettings } from '../../../../globals';
import { getRepoBranches } from '../../../../services/github_rest'; import { getRepoBranches } from '../../../../services/github_rest';
const STACK_DEFAULTS = {
STACK_ENVIRONMENT_NAME_TAG: 'test',
CPU_SIZE: 512,
MEMORY_SIZE: '1GB',
HOSTED_ZONE_WITHOUT_TLD: 'photowall-test',
DOMAIN_NAME_WITHOUT_TLD: '.photowall-test',
PRIMARY_CERTIFICATE_ARN:
'arn:aws:acm:eu-west-1:954747537408:certificate/12e33b74-da14-430d-a7ed-f62fa7113112',
STATIC_CDN_CERTIFICATE_ARN:
'arn:aws:acm:us-east-1:954747537408:certificate/223550cf-e404-4ff1-85bb-703b936c9347',
DB_SECURITY_GROUP_ID: 'sg-001b3667edf19e1ce',
GITHUB_REPO: 'photowall',
GITHUB_USER: 'Photowall',
STATIC_CDN_HOSTNAME: `''`,
MAX_CONTAINERS: 1,
MIN_CONTAINERS: 1,
AWS_KEY_ENVIRONMENT: 'staging'
}
type Stack = { type Stack = {
name: string name: string
status: string status: string
@@ -31,42 +13,6 @@ type Stack = {
updated: string updated: string
} }
const getDownloadFileFromRepoCommand = (token: string, org: string, repo: string, path: string) => {
const file = path.split('/').pop();
return `curl -o /tmp/${file} -H 'Authorization: token ${token} ' -H 'Accept: application/vnd.github.v3.raw' -O -L https://api.github.com/repos/${org}/${repo}/contents/${path}`;
}
const getCreateStackCommand = (stackName: string, branch: string, templateFile: string, dockerImage: string, githubToken: string, composerAuth: string) => {
const stackDomain = stackName.replace('photowall-', '');
const cmd = [
`aws cloudformation create-stack --stack-name ${stackName}`,
`--template-body ${templateFile}`,
`--capabilities CAPABILITY_NAMED_IAM`,
`--tags Key=EnvironmentName,Value=test`,
`--parameters`,
`ParameterKey=EnvironmentName,ParameterValue=${stackDomain}`,
`ParameterKey=Image,ParameterValue=${dockerImage}`,
`ParameterKey=HostedZoneNameWithOutTLD,ParameterValue=${STACK_DEFAULTS.HOSTED_ZONE_WITHOUT_TLD}`,
`ParameterKey=DomainNameWithoutTld,ParameterValue=${stackDomain}${STACK_DEFAULTS.DOMAIN_NAME_WITHOUT_TLD}`,
`ParameterKey=PrimaryCertificateArn,ParameterValue='${STACK_DEFAULTS.PRIMARY_CERTIFICATE_ARN}'`,
`ParameterKey=GitHubRepo,ParameterValue=${STACK_DEFAULTS.GITHUB_REPO}`,
`ParameterKey=GitHubUser,ParameterValue=${STACK_DEFAULTS.GITHUB_USER}`,
`ParameterKey=GitHubBranch,ParameterValue=${branch}`,
`ParameterKey=GitHubToken,ParameterValue=${githubToken}`,
`ParameterKey=ComposerAuth,ParameterValue="${composerAuth}"`,
`ParameterKey=CpuSize,ParameterValue=${STACK_DEFAULTS.CPU_SIZE}`,
`ParameterKey=MemorySize,ParameterValue=${STACK_DEFAULTS.MEMORY_SIZE}`,
`ParameterKey=MinContainers,ParameterValue=${STACK_DEFAULTS.MIN_CONTAINERS}`,
`ParameterKey=MaxContainers,ParameterValue=${STACK_DEFAULTS.MAX_CONTAINERS}`,
`ParameterKey=StaticCdnHostName,ParameterValue=${STACK_DEFAULTS.STATIC_CDN_HOSTNAME}`,
`ParameterKey=StaticCdnCertificateArn,ParameterValue=${STACK_DEFAULTS.STATIC_CDN_CERTIFICATE_ARN}`,
`ParameterKey=AwsAccessKeyParamNameEnvironment,ParameterValue=${STACK_DEFAULTS.AWS_KEY_ENVIRONMENT}`,
`ParameterKey=DatabaseSecurityGroup,ParameterValue=${STACK_DEFAULTS.DB_SECURITY_GROUP_ID}`,
];
return cmd.join(' ');
};
const getConfirmation = async (branchName: string, stackName: string) => { const getConfirmation = async (branchName: string, stackName: string) => {
const url = stackName.replace('photowall-', ''); const url = stackName.replace('photowall-', '');
const confirm = new Confirm({ const confirm = new Confirm({
@@ -92,7 +38,12 @@ module.exports = {
// Load settings // Load settings
const config = await getSettings(toolbox); const config = await getSettings(toolbox);
if (!config) { if (!config || (!config.photowall_repo || config.photowall_repo === "")) {
print.error(`
The create command requires that you set an absolute path to your local photowall repository.
`);
await toolbox.menu.showMenu('setup', defaultMenuSettings); await toolbox.menu.showMenu('setup', defaultMenuSettings);
return; return;
} }
@@ -169,6 +120,8 @@ module.exports = {
`); `);
if (toolbox.fromMenu()) { if (toolbox.fromMenu()) {
await toolbox.menu.showMenu('deployment testservers'); await toolbox.menu.showMenu('deployment testservers');
} else {
exit();
} }
} else if (stackName.indexOf('photowall-test-') !== 0) { } else if (stackName.indexOf('photowall-test-') !== 0) {
print.error(` print.error(`
@@ -178,36 +131,19 @@ module.exports = {
`); `);
if (toolbox.fromMenu()) { if (toolbox.fromMenu()) {
await toolbox.menu.showMenu('deployment testservers', defaultMenuSettings); await toolbox.menu.showMenu('deployment testservers', defaultMenuSettings);
} else {
exit();
} }
} }
try { try {
const shouldRun = await getConfirmation(branchName, stackName); const shouldRun = await getConfirmation(branchName, stackName);
if (shouldRun) { if (shouldRun) {
// Download files to /tmp const cmd = `make create-stack STACK_ENVIRONMENT_NAME=${stacksuffix} GITHUB_BRANCH=${branchName}`;
await system.run(getDownloadFileFromRepoCommand(config.gh_token, 'Photowall', 'photowall', 'cloudformation/ecr-lifecycle-policy.json')); print.fancy(`Running [${chalk.yellow(cmd)}] in folder [${`${config.photowall_repo}/cloudformation/`}]`);
await system.run(getDownloadFileFromRepoCommand(config.gh_token, 'Photowall', 'photowall', 'cloudformation/ecs-service.yaml')); const output = await system.run(cmd, {cwd: `${config.photowall_repo}/cloudformation/`, trim: true});
print.fancy(output);
const awsAccountId = strings.trim(await system.run(`aws sts get-caller-identity --query Account --output text`));
const awsRegion = strings.trim(await system.run(`aws configure get region`));
const githubToken = strings.trim(await system.run(`aws ssm get-parameter --with-decryption --name /github/CODE_PIPELINE_TOKEN --output text --query Parameter.Value`));
print.fancy(await system.run(`aws ecr create-repository --repository ${stackName}`));
print.fancy(await system.run(`aws ecr get-login-password --region ${awsRegion} | docker login --username AWS --password-stdin ${awsAccountId}.dkr.ecr.${awsRegion}.amazonaws.com`));
print.fancy(await system.run(`docker pull nginx`));
print.fancy(await system.run(`docker tag nginx ${awsAccountId}.dkr.ecr.${awsRegion}.amazonaws.com/${stackName}:latest`));
print.fancy(await system.run(`docker push ${awsAccountId}.dkr.ecr.${awsRegion}.amazonaws.com/${stackName}:latest`));
const dockerImage = `${awsAccountId}.dkr.ecr.${awsRegion}.amazonaws.com/${stackName}`;
let composerAuthToken = await system.run(`aws ssm get-parameter --with-decryption --name /github/COMPOSER_TOKEN --output text --query Parameter.Value`);
composerAuthToken = composerAuthToken.replace('\n', '');
const composerAuth = `'{\\\"github-oauth\\\":{\\\"github.com\\\":\\\"${composerAuthToken}\\\"}}'`;
const createCommand = getCreateStackCommand(stackName, branchName, 'file://ecs-service.yaml', dockerImage, githubToken, composerAuth);
print.fancy(await system.run(createCommand, {cwd: '/tmp/', trim: true}));
} }
} catch (e) { } catch (e) {
console.log(`e`, e); console.log(`e`, e);
@@ -1,5 +1,5 @@
import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu' import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu'
import { GluegunSystem, print } from 'gluegun'; import { GluegunSystem } from 'gluegun';
import { defaultMenuSettings } from '../../../../globals'; import { defaultMenuSettings } from '../../../../globals';
const chalk = require('chalk'); const chalk = require('chalk');
const { AutoComplete, Input, Confirm } = require('enquirer'); const { AutoComplete, Input, Confirm } = require('enquirer');
@@ -78,9 +78,9 @@ module.exports = {
const timeSince = (date: number) => { const timeSince = (date: number) => {
const now = Date.now(); const now = Date.now();
var seconds = Math.floor((now - date) / 1000); const seconds = Math.floor((now - date) / 1000);
var interval = seconds / 31536000; let interval = seconds / 31536000;
if (interval > 1) { if (interval > 1) {
return Math.floor(interval) + " years"; return Math.floor(interval) + " years";
@@ -2,25 +2,7 @@ import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu'
const chalk = require('chalk'); const chalk = require('chalk');
const { AutoComplete, Input, Confirm } = require('enquirer'); const { AutoComplete, Input, Confirm } = require('enquirer');
import { Octokit } from "@octokit/core"; import { Octokit } from "@octokit/core";
import { GluegunPrint } from 'gluegun';
import { defaultMenuSettings, getCurrentBranch, getSettings } from '../../../../globals'; import { defaultMenuSettings, getCurrentBranch, getSettings } from '../../../../globals';
const os = require("os");
const STACK_DEFAULTS = {
STACK_ENVIRONMENT_NAME_TAG: 'test',
CPU_SIZE: 512,
MEMORY_SIZE: '1GB',
HOSTED_ZONE_WITHOUT_TLD: 'photowall-test',
PRIMARY_CERTIFICATE_ARN:
'arn:aws:acm:eu-west-1:954747537408:certificate/12e33b74-da14-430d-a7ed-f62fa7113112',
STATIC_CDN_CERTIFICATE_ARN:
'arn:aws:acm:us-east-1:954747537408:certificate/223550cf-e404-4ff1-85bb-703b936c9347',
DB_SECURITY_GROUP_ID: 'sg-001b3667edf19e1ce',
STATIC_CDN_HOSTNAME: `''`,
MAX_CONTAINERS: 1,
MIN_CONTAINERS: 1,
AWS_KEY_ENVIRONMENT: 'staging'
}
type Stack = { type Stack = {
name: string name: string
@@ -30,44 +12,6 @@ type Stack = {
updated: string updated: string
} }
const getDownloadFileFromRepoCommand = (token: string, org: string, repo: string, path: string) => {
const file = path.split('/').pop();
return `curl -o /tmp/${file} -H 'Authorization: token ${token} ' -H 'Accept: application/vnd.github.v3.raw' -O -L https://api.github.com/repos/${org}/${repo}/contents/${path}`;
}
const getLifeCyclePolicyCommand = (stackName: string, policyFile: string) => {
return `aws ecr put-lifecycle-policy --repository-name ${stackName} --lifecycle-policy-text "${policyFile}"`;
}
const getUpdateStackCommand = (stackName: string, branch: string, templateFile: string) => {
const cmd = [
`aws cloudformation update-stack --stack-name ${stackName}`,
`--template-body ${templateFile}`,
`--capabilities CAPABILITY_NAMED_IAM`,
`--tags Key=EnvironmentName,Value=test`,
`--parameters`,
`ParameterKey=EnvironmentName,UsePreviousValue=true`,
`ParameterKey=Image,UsePreviousValue=true`,
`ParameterKey=HostedZoneNameWithOutTLD,UsePreviousValue=true`,
`ParameterKey=DomainNameWithoutTld,UsePreviousValue=true`,
`ParameterKey=PrimaryCertificateArn,UsePreviousValue=true`,
`ParameterKey=GitHubRepo,UsePreviousValue=true`,
`ParameterKey=GitHubUser,UsePreviousValue=true`,
`ParameterKey=GitHubBranch,ParameterValue=${branch}`,
`ParameterKey=GitHubToken,UsePreviousValue=true`,
`ParameterKey=ComposerAuth,UsePreviousValue=true`,
`ParameterKey=CpuSize,ParameterValue=${STACK_DEFAULTS.CPU_SIZE}`,
`ParameterKey=MemorySize,ParameterValue=${STACK_DEFAULTS.MEMORY_SIZE}`,
`ParameterKey=MinContainers,ParameterValue=${STACK_DEFAULTS.MIN_CONTAINERS}`,
`ParameterKey=MaxContainers,ParameterValue=${STACK_DEFAULTS.MAX_CONTAINERS}`,
`ParameterKey=StaticCdnHostName,ParameterValue=${STACK_DEFAULTS.STATIC_CDN_HOSTNAME}`,
`ParameterKey=StaticCdnCertificateArn,ParameterValue=${STACK_DEFAULTS.STATIC_CDN_CERTIFICATE_ARN}`,
`ParameterKey=AwsAccessKeyParamNameEnvironment,ParameterValue=${STACK_DEFAULTS.AWS_KEY_ENVIRONMENT}`,
`ParameterKey=DatabaseSecurityGroup,ParameterValue=${STACK_DEFAULTS.DB_SECURITY_GROUP_ID}`
];
return cmd.join(' ');
}
const getBranchName = async (toolbox: GluegunMenuToolbox, token: string, repoPath: string) => { const getBranchName = async (toolbox: GluegunMenuToolbox, token: string, repoPath: string) => {
const {print} = toolbox; const {print} = toolbox;
const currentBranch = await getCurrentBranch(repoPath, toolbox); const currentBranch = await getCurrentBranch(repoPath, toolbox);
@@ -121,7 +65,12 @@ module.exports = {
// Load settings // Load settings
const config = await getSettings(toolbox); const config = await getSettings(toolbox);
if (!config) { if (!config || (!config.photowall_repo || config.photowall_repo === "")) {
print.error(`
The create command requires that you set an absolute path to your local photowall repository.
`);
await toolbox.menu.showMenu('setup', defaultMenuSettings); await toolbox.menu.showMenu('setup', defaultMenuSettings);
return; return;
} }
@@ -184,22 +133,15 @@ module.exports = {
}); });
try { try {
// Download files to /tmp
await system.run(getDownloadFileFromRepoCommand(config.gh_token, 'Photowall', 'photowall', 'cloudformation/ecr-lifecycle-policy.json'));
await system.run(getDownloadFileFromRepoCommand(config.gh_token, 'Photowall', 'photowall', 'cloudformation/ecs-service.yaml'));
const stackName = await prompt.run(); const stackName = await prompt.run();
const stacksuffix = stackName.replace('photowall-', '');
const lifeCycleCommand = getLifeCyclePolicyCommand(stackName, `file://ecr-lifecycle-policy.json`);
const updateStackCommand = getUpdateStackCommand(stackName, branchName, `file://ecs-service.yaml`);
const shouldRun = await getConfirmation(branchName, stackName); const shouldRun = await getConfirmation(branchName, stackName);
if (shouldRun) { if (shouldRun) {
let output = await system.run(lifeCycleCommand, {cwd: '/tmp/', trim: true}); const cmd = `make update-stack STACK_ENVIRONMENT_NAME=${stacksuffix} GITHUB_BRANCH=${branchName}`;
print.fancy(output); print.fancy(`Running [${chalk.yellow(cmd)}] in folder [${`${config.photowall_repo}/cloudformation/`}]`);
output = await system.run(updateStackCommand, {cwd: '/tmp/', trim: true}); const output = await system.run(cmd, {cwd: `${config.photowall_repo}/cloudformation/`, trim: true});
print.fancy(output); print.fancy(output);
} }
+1 -1
View File
@@ -115,7 +115,7 @@ module.exports = {
})).run(); })).run();
config.photowall_repo = await (new Input({ config.photowall_repo = await (new Input({
message: `If you want to be able to use current branch in your photowall repository\nwhen creating or updating testservers, please insert\nthe absolute path to the project or leave blank >`, message: `If you want to be able to use current branch in your photowall repository\nor the create and update commands for testservers, please insert\nthe absolute path to the project or leave blank >`,
initial: config.photowall_repo, initial: config.photowall_repo,
})).run(); })).run();