@axway/axway-central-cli
Version:
Manage APIs, services and publish to the Amplify Marketplace
527 lines (494 loc) • 26.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.testables = exports.installPreprocess = exports.gatewayConnectivity = exports.completeInstall = exports.askConfigType = exports.askBundleType = exports.DeploymentTypes = exports.ConfigFiles = exports.AWSPrompts = exports.AWSInstallMethods = void 0;
var _chalk = _interopRequireDefault(require("chalk"));
var _fs = _interopRequireDefault(require("fs"));
var _snooplogg = _interopRequireDefault(require("snooplogg"));
var _basicPrompts = require("../../common/basicPrompts");
var _dataService = require("../../common/dataService");
var _types = require("../../common/types");
var _utils = require("../../common/utils");
var helpers = _interopRequireWildcard(require("./helpers"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const {
log
} = (0, _snooplogg.default)('engage: install: agents: aws');
const daImage = `${_types.PublicDockerRepoBaseUrl}${_types.BasePaths.DockerAgentPublicRepo}/${_types.AgentNames.AWS_DA}`;
const taImage = `${_types.PublicDockerRepoBaseUrl}${_types.BasePaths.DockerAgentPublicRepo}/${_types.AgentNames.AWS_TA}`;
const STAGE_TAG_NAME_LENGTH = 127;
// DeploymentTypes - ways the agents may be deployed with an AWS APIGW setup
let DeploymentTypes = exports.DeploymentTypes = /*#__PURE__*/function (DeploymentTypes) {
DeploymentTypes["EC2"] = "EC2";
DeploymentTypes["ECS_FARGATE"] = "ECS Fargate";
DeploymentTypes["OTHER"] = "Other";
return DeploymentTypes;
}({}); //Docker Container Only
// EC2InstanceTypes - instance types allowed in cloud formation document
var EC2InstanceTypes = /*#__PURE__*/function (EC2InstanceTypes) {
EC2InstanceTypes["T3_MICRO"] = "t3.micro";
EC2InstanceTypes["T3_NAN0"] = "t3.nano";
EC2InstanceTypes["T3_SMALL"] = "t3.small";
EC2InstanceTypes["T3_MEDIUM"] = "t3.medium";
EC2InstanceTypes["T3_LARGE"] = "t3.large";
EC2InstanceTypes["T3_XLARGE"] = "t3.xlarge";
EC2InstanceTypes["T3_2XLARGE"] = "t3.2xlarge";
return EC2InstanceTypes;
}(EC2InstanceTypes || {});
const InvalidMsg = {
S3_BUCKET: `S3 Bucket Name can contain digits '0-9', lower case letters 'a-z', hyphens '-', and periods '.' with 3-63 characters. Must begin and end with number or letter`,
LOG_GROUP: `Log Group Name can contain digits '0-9', letters 'a-z' and 'A-Z', underscores '_', hyphens '-', forward slash '/', and periods '.' with a maximum length of 512 characters`,
SQS_QUEUE: `SQS Queue Name can contain digits '0-9', letters 'a-z' and 'A-Z', underscores '_', and hyphens '-' with a maximum length of 80 characters`,
CLUSTER_NAME: `ECS fargate cluster name can contain digits '0-9', letters 'a-z' and 'A-Z', underscores '_', and hyphens '-' with a maximum length of 255 characters`
};
// ConfigFiles - all the config file that are used in the setup
const ConfigFiles = exports.ConfigFiles = {
DeployAllYAML: 'amplify-agents-deploy-all.yaml',
ResourcesYAML: 'amplify-agents-setup.yaml',
EC2DeployYAML: 'amplify-agents-ec2.yaml',
FargateDeployYAML: 'amplify-agents-ecs-fargate.yaml',
AgentConfigZip: 'aws_apigw_agent_config-latest.zip',
DAEnvVars: `${helpers.configFiles.DA_ENV_VARS}`,
TAEnvVars: `${helpers.configFiles.TA_ENV_VARS}`,
CFProperties: 'cloudformation_properties.json'
};
// AWSPrompts - all prompts to the user for input
const AWSPrompts = exports.AWSPrompts = {
APIGW_LOG_GROUP: 'Enter the Log Group name to track API Gateway traffic events',
CLUSTER_NAME: 'Enter the ECS fargate cluster name to deploy the ECS task for the agents',
CONFIG_BUCKET: 'Enter the S3 bucket the config service will use to track config changes',
CONFIG_BUCKET_EXISTS: 'Does this bucket already exist on AWS, or will you create beforehand?',
CONFIG_SERVICE: 'Do you want to setup config service?',
DA_LOG_GROUP: 'Enter the log group name the discovery agent will log to',
STAGE_TAG_NAME: 'Enter the name of the tag on AWS API Gateway Stage that holds mapped stage on Amplify Engage',
DA_QUEUE: 'Enter the discovery queue name',
DEPLOYMENT: 'Select the type of deployment you wish to configure',
EC2_TYPE: 'Select the EC2 instance type',
KEY_PAIR: 'Enter the EC2 KeyPair name that will be used to connect via SSH to the EC2 instance',
PUBLIC_IP: 'Assign a Public IP Address to this, only change if your VPC has a NAT Gateway',
SECURITY_GROUP: 'Enter the Security Group for the EC2 Instance of ECS Container',
SETUP_APIGW_CW: 'The Amazon API Gateway service requires a role to write usage logs to Cloud Watch. Do you want to configure that?',
SSH_LOCATION: 'Enter the IP address range that can be used to SSH to the EC2 instances',
SSM_PRIVATE: 'Enter the name of the SSM Parameter holding the Private Key',
SSM_PUBLIC: 'Enter the name of the SSM Parameter holding the Public Key',
SUBNET: 'Enter the Subnet for the EC2 Instance of ECS Container',
S3_BUCKET: 'Enter the existing S3 bucket, within your region, where the agent resources will be uploaded',
TA_LOG_GROUP: 'Enter the log group name the traceability agent will log to',
FULL_TRANSACTION_LOGGING: 'Do you want to enable Full Transaction Logging? Please note that CloudWatch costs would increase when Full Transaction Logging is enabled',
TA_QUEUE: 'Enter the traceability queue name',
VPC_ID: 'Enter the VPC ID to deploy the EC2 instance to. Leave blank to create entire infrastructure'
};
const askBundleType = async () => {
return _types.BundleType.ALL_AGENTS;
};
exports.askBundleType = askBundleType;
const askConfigType = async () => {
return _types.AgentConfigTypes.DOCKERIZED;
};
//
// Complex prompts
//
exports.askConfigType = askConfigType;
const askDeployment = async () => {
return (0, _basicPrompts.askList)({
msg: AWSPrompts.DEPLOYMENT,
choices: [{
name: DeploymentTypes.EC2,
value: DeploymentTypes.EC2
}, {
name: DeploymentTypes.ECS_FARGATE,
value: DeploymentTypes.ECS_FARGATE
}, {
name: 'Docker Container Only',
value: DeploymentTypes.OTHER
}],
default: DeploymentTypes.EC2
});
};
// askToCreateRoleSetup - asks a Yes/No question for creating the APIGW IAM role, returns a True/False string for CloudFormation parameters
const askToCreateRoleSetup = async () => {
return (await (0, _basicPrompts.askList)({
msg: AWSPrompts.SETUP_APIGW_CW,
choices: _types.YesNoChoices,
default: _types.YesNo.Yes
})) === _types.YesNo.Yes ? _types.TrueFalse.True.toLowerCase() : _types.TrueFalse.False.toLowerCase();
};
// askToUsePublicIpAddress - asks a Yes/No question for setting a public IP address, returns a True/False string for CloudFormation parameters
const askToUsePublicIpAddress = async () => {
return (await (0, _basicPrompts.askList)({
msg: AWSPrompts.PUBLIC_IP,
choices: _types.YesNoChoices,
default: _types.YesNo.Yes
})) === _types.YesNo.Yes ? _types.TrueFalse.True.toLowerCase() : _types.TrueFalse.False.toLowerCase();
};
const askEC2InstanceType = async () => {
return await (0, _basicPrompts.askList)({
msg: AWSPrompts.EC2_TYPE,
choices: [{
name: EC2InstanceTypes.T3_MICRO,
value: EC2InstanceTypes.T3_MICRO
}, {
name: EC2InstanceTypes.T3_NAN0,
value: EC2InstanceTypes.T3_NAN0
}, {
name: EC2InstanceTypes.T3_SMALL,
value: EC2InstanceTypes.T3_SMALL
}, {
name: EC2InstanceTypes.T3_MEDIUM,
value: EC2InstanceTypes.T3_MEDIUM
}, {
name: EC2InstanceTypes.T3_LARGE,
value: EC2InstanceTypes.T3_LARGE
}, {
name: EC2InstanceTypes.T3_XLARGE,
value: EC2InstanceTypes.T3_XLARGE
}, {
name: EC2InstanceTypes.T3_2XLARGE,
value: EC2InstanceTypes.T3_2XLARGE
}],
default: EC2InstanceTypes.T3_MICRO
});
};
const askEC2VPCConfig = async awsAgentValues => {
awsAgentValues.cloudFormationConfig.EC2VPCID = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.VPC_ID,
allowEmptyInput: true,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_VPC_ID, helpers.invalidValueExampleErrMsg('VPC ID', 'vpc-xxxxxxxxxx'))
});
if (awsAgentValues.cloudFormationConfig.EC2VPCID !== '') {
// EC2 Public IP Address
awsAgentValues.cloudFormationConfig.EC2PublicIPAddress = await askToUsePublicIpAddress();
await askSecurityGroupAndSubnet(awsAgentValues);
}
return awsAgentValues;
};
const askSecurityGroupAndSubnet = async awsAgentValues => {
awsAgentValues.cloudFormationConfig.SecurityGroup = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SECURITY_GROUP,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_SECURITY_GROUP, helpers.invalidValueExampleErrMsg('security group', 'sg-xxxxxxxxxx'))
});
awsAgentValues.cloudFormationConfig.Subnet = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SUBNET,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_SUBNET, helpers.invalidValueExampleErrMsg('subnet ID', 'subnet-xxxxxxxxxx'))
});
return awsAgentValues;
};
async function configureEC2Deployment(awsAgentValues) {
// EC2 Instance type
awsAgentValues.cloudFormationConfig.EC2InstanceType = await askEC2InstanceType();
// EC2 Key Name
console.log(_chalk.default.gray(`A SSH key pair is required to access the EC2 instance. An example CLI command will be given at the end, if needed`));
awsAgentValues.cloudFormationConfig.EC2KeyName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.KEY_PAIR
});
// EC2 VPC Config
awsAgentValues = await askEC2VPCConfig(awsAgentValues);
awsAgentValues.cloudFormationConfig.EC2SSHLocation = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SSH_LOCATION,
defaultValue: awsAgentValues.cloudFormationConfig.EC2SSHLocation,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_SSH_LOCATION, helpers.invalidValueExampleErrMsg('IP Range/Mask', '1.2.3.4/0'))
});
// SSMPrivateKeyParameter
awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SSM_PRIVATE,
defaultValue: awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter
});
// SSMPublicKeyParameter
awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SSM_PUBLIC,
defaultValue: awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter
});
return awsAgentValues;
}
async function configureECSDeployment(awsAgentValues) {
// ECS Cluster name
awsAgentValues.cloudFormationConfig.ECSClusterName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.CLUSTER_NAME,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP, InvalidMsg.CLUSTER_NAME)
});
awsAgentValues = await askSecurityGroupAndSubnet(awsAgentValues);
// SSMPrivateKeyParameter
awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SSM_PRIVATE,
defaultValue: awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter
});
// SSMPublicKeyParameter
awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.SSM_PUBLIC,
defaultValue: awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter
});
return awsAgentValues;
}
// @ts-ignore
const gatewayConnectivity = async installConfig => {
console.log('\nCONNECTION TO AMAZON API GATEWAY:');
console.log(_chalk.default.gray(`You need credentials for executing the AWS CLI commands.\n` + `The Discovery Agent needs to connect to the Amazon (AWS) API Gateway to discover API's for publishing to Amplify.\n` + `The Traceability Agent needs to connect to the AWS API Gateway for the collection of transaction headers.\n` + `These headers will be formatted and forwarded to the Business Insights.\n` + `We recommend to use two different set of credentials: one for AWS CLI and one for the agents`));
// DeploymentType
const deploymentType = await askDeployment();
let awsAgentValues = new helpers.AWSAgentValues(deploymentType);
awsAgentValues.cloudFormationConfig.DeploymentType = deploymentType;
switch (awsAgentValues.cloudFormationConfig.DeploymentType) {
case DeploymentTypes.ECS_FARGATE:
{
console.log(_chalk.default.gray(`To deploy the Agents to ECS Fargate you will need an ECS Cluster Name, Security Group, and Subnet. The coming questions will ask those values.\n`));
break;
}
case DeploymentTypes.OTHER:
{
console.log(_chalk.default.gray(`To access the AWS CLI, the AWS Access Key and AWS Secret Key credentials are required.\n`));
break;
}
}
// AWS Region
awsAgentValues.region = await helpers.askAWSRegion();
// S3 bucket
awsAgentValues.cloudFormationConfig.AgentResourcesBucket = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.S3_BUCKET,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP, InvalidMsg.S3_BUCKET)
});
// APIGWCWRoleSetup
awsAgentValues.cloudFormationConfig.APIGWCWRoleSetup = await askToCreateRoleSetup();
// APIGWTrafficLogGroupName
const apiGWTrafficLogGroupName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.APIGW_LOG_GROUP,
defaultValue: awsAgentValues.cloudFormationConfig.APIGWTrafficLogGroupName,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_LOG_GROUP_NAME, InvalidMsg.LOG_GROUP)
});
awsAgentValues.logGroup = apiGWTrafficLogGroupName;
awsAgentValues.cloudFormationConfig.APIGWTrafficLogGroupName = apiGWTrafficLogGroupName;
// StageTagName
const stageTagName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.STAGE_TAG_NAME,
validate: (0, _basicPrompts.validateInputLength)(STAGE_TAG_NAME_LENGTH, "Maximum length of 'stage tag name' is 127")
});
awsAgentValues.stageTagName = stageTagName;
// FullTransactionLogging
const fullTransactionLogging = (await (0, _basicPrompts.askList)({
msg: AWSPrompts.FULL_TRANSACTION_LOGGING,
choices: _types.YesNoChoices,
default: _types.YesNo.No
})) === _types.YesNo.Yes;
awsAgentValues.fullTransactionLogging = fullTransactionLogging;
// set agent versions
awsAgentValues.cloudFormationConfig.DiscoveryAgentVersion = installConfig.daVersion;
awsAgentValues.cloudFormationConfig.TraceabilityAgentVersion = installConfig.taVersion;
// Configure appropriate Gateway type
switch (awsAgentValues.cloudFormationConfig.DeploymentType) {
case DeploymentTypes.ECS_FARGATE:
{
awsAgentValues = await configureECSDeployment(awsAgentValues);
break;
}
case DeploymentTypes.EC2:
{
awsAgentValues = await configureEC2Deployment(awsAgentValues);
break;
}
}
// DiscoveryAgentLogGroupName
awsAgentValues.cloudFormationConfig.DiscoveryAgentLogGroupName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.DA_LOG_GROUP,
defaultValue: awsAgentValues.cloudFormationConfig.DiscoveryAgentLogGroupName,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_LOG_GROUP_NAME, InvalidMsg.LOG_GROUP)
});
// TraceabilityAgentLogGroupName
awsAgentValues.cloudFormationConfig.TraceabilityAgentLogGroupName = await (0, _basicPrompts.askInput)({
msg: AWSPrompts.TA_LOG_GROUP,
defaultValue: awsAgentValues.cloudFormationConfig.TraceabilityAgentLogGroupName,
validate: (0, _basicPrompts.validateRegex)(helpers.AWSRegexPatterns.AWS_REGEXP_LOG_GROUP_NAME, InvalidMsg.LOG_GROUP)
});
return awsAgentValues;
};
exports.gatewayConnectivity = gatewayConnectivity;
const generateOutput = async installConfig => {
const awsAgentValues = installConfig.gatewayConfig;
let s3BaseFiles = [ConfigFiles.DeployAllYAML, ConfigFiles.ResourcesYAML];
let additionalSteps = '';
let dockerEnvConfig = '';
let runCommands = '';
// Configure appropriate Gateway type
switch (awsAgentValues.cloudFormationConfig.DeploymentType) {
case DeploymentTypes.ECS_FARGATE:
{
// DeploymentTypes.ECS_FARGATE
s3BaseFiles.push(ConfigFiles.FargateDeployYAML);
additionalSteps = ` - Create the SSM parameter:
${_chalk.default.cyan(` aws ssm put-parameter --type SecureString --name ${awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter} --value "file:\/\/private_key.pem"`)}
${_chalk.default.cyan(` aws ssm put-parameter --type SecureString --name ${awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter} --value "file:\/\/public_key.pem"`)}`;
// Cleanup EC2 file
_fs.default.unlinkSync(ConfigFiles.EC2DeployYAML);
break;
}
case DeploymentTypes.OTHER:
{
// DeploymentTypes.OTHER for Docker Container Only
// These files need to be put in a resources dir on S3
let s3ResourcesIncludes = '';
[ConfigFiles.DAEnvVars, ConfigFiles.TAEnvVars].forEach(value => s3ResourcesIncludes += `--include "${value}" `);
// Cleanup EC2 file
_fs.default.unlinkSync(ConfigFiles.EC2DeployYAML);
// Cleanup ECS Fargate file
_fs.default.unlinkSync(ConfigFiles.FargateDeployYAML);
const info = `To utilize the agents, pull the latest Docker images and run them using the appropriate supplied environment files, (${helpers.configFiles.DA_ENV_VARS} & ${helpers.configFiles.TA_ENV_VARS}):`;
dockerEnvConfig = `Wait for the CloudFormation Stack to complete.
- Create AWS Access and Secret Keys and copy resulting ${_chalk.default.yellow(`"AccessKeyId"`)} & ${_chalk.default.yellow(`"SecretAccessKey"`)}:
${_chalk.default.cyan(` aws iam create-access-key --user-name AxwayAmplifyAgentsUser-${awsAgentValues.region} ${helpers.eolChar}
--query "AccessKey.{"AccessKeyId":AccessKeyId,"SecretAccessKey":SecretAccessKey}"`)}
- Add "AccessKeyId" & "SecretAccessKey" variables to both agent .env files, ${ConfigFiles.DAEnvVars} & ${ConfigFiles.TAEnvVars}:
AWS_AUTH_ACCESSKEY=${_chalk.default.yellow(`Your_AccessKeyId`)}
AWS_AUTH_SECRETKEY=${_chalk.default.yellow(`Your_SecretAccessKey`)}`;
runCommands = `${_chalk.default.whiteBright(info)}
Pull the latest image of the Discovery Agent:
${_chalk.default.cyan(`docker pull ${daImage}:${installConfig.daVersion}`)}
Pull the latest image of the Traceability Agent:
${_chalk.default.cyan(`docker pull ${taImage}:${installConfig.taVersion}`)}
${_utils.isWindows ? `
Start the Discovery agent on Windows machine (cmd.exe):
${_chalk.default.cyan(`docker run --env-file ${helpers.pwdWin}/${ConfigFiles.DAEnvVars} -v ${helpers.pwdWin}:/keys ${helpers.eolCharWin}
-v /data ${daImage}:${installConfig.daVersion}`)}` : `
Start the Discovery agent on Linux based machine:
${_chalk.default.cyan(`docker run --env-file ${helpers.pwd}/${ConfigFiles.DAEnvVars} -v ${helpers.pwd}:/keys ${helpers.eolChar}
-v /data ${daImage}:${installConfig.daVersion}`)}`}
${_utils.isWindows ? `
Start the Traceability agent on Windows machine (cmd.exe):
${_chalk.default.cyan(`docker run --env-file ${helpers.pwdWin}/${ConfigFiles.TAEnvVars} -v ${helpers.pwdWin}:/keys ${helpers.eolCharWin}
-v /data ${taImage}:${installConfig.taVersion}`)}` : `
Start the Traceability agent on Linux based machine:
${_chalk.default.cyan(`docker run --env-file ${helpers.pwd}/${ConfigFiles.TAEnvVars} -v ${helpers.pwd}:/keys ${helpers.eolChar}
-v /data ${taImage}:${installConfig.taVersion}`)}`}`;
break;
}
default:
{
// DeploymentTypes.EC2
s3BaseFiles.push(ConfigFiles.EC2DeployYAML);
// These files need to be put in a resources dir on S3
let s3ResourcesIncludes = '';
[ConfigFiles.DAEnvVars, ConfigFiles.TAEnvVars].forEach(value => s3ResourcesIncludes += `--include "${value}" `);
additionalSteps = `${_chalk.default.cyan(` aws s3 sync --exclude "*" ${s3ResourcesIncludes} ./ s3://${awsAgentValues.cloudFormationConfig.AgentResourcesBucket}/resources`)}
- If necessary, create EC2 KeyPair, for EC2 login:
${_chalk.default.cyan(` aws ec2 create-key-pair --key-name ${awsAgentValues.cloudFormationConfig.EC2KeyName} --query KeyMaterial --output text > MyKeyPair.pem`)}
- Create the SSM parameter:
${_chalk.default.cyan(` aws ssm put-parameter --type SecureString --name ${awsAgentValues.cloudFormationConfig.SSMPrivateKeyParameter} --value "file:\/\/private_key.pem"`)}
${_chalk.default.cyan(` aws ssm put-parameter --type SecureString --name ${awsAgentValues.cloudFormationConfig.SSMPublicKeyParameter} --value "file:\/\/public_key.pem"`)}`;
// Cleanup Fargate file
_fs.default.unlinkSync(ConfigFiles.FargateDeployYAML);
break;
}
}
let s3BaseIncludes = '';
s3BaseFiles.forEach(value => s3BaseIncludes += `--include "${value}" `);
// if region is AWS default, 'us-east-1', region unnecessary in cloudformation template url
const s3Region = awsAgentValues.region === _types.AWSRegions.US_EAST_1 ? `s3` : `s3.${awsAgentValues.region}`;
return `
To complete the install, run the following AWS CLI command:
- Create, if necessary, and upload all files to your S3 bucket
${_chalk.default.cyan(` aws s3api create-bucket --bucket ${awsAgentValues.cloudFormationConfig.AgentResourcesBucket} --create-bucket-configuration LocationConstraint=${awsAgentValues.region}`)}
${_chalk.default.cyan(` aws s3 sync --exclude "*" ${s3BaseIncludes} ./ s3://${awsAgentValues.cloudFormationConfig.AgentResourcesBucket}`)}
${additionalSteps}
- Deploy the CloudFormation Stack:
${_chalk.default.cyan(` aws cloudformation create-stack --stack-name AxwayAmplifyAgents ${helpers.eolChar}
--template-url https://${awsAgentValues.cloudFormationConfig.AgentResourcesBucket}.${s3Region}.amazonaws.com/${ConfigFiles.DeployAllYAML} ${helpers.eolChar}
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM --parameters "file:\/\/${ConfigFiles.CFProperties}"`)}
- Check the CloudFormation Stack:
${_chalk.default.cyan(` aws cloudformation describe-stacks --stack-name AxwayAmplifyAgents ${helpers.eolChar}
--query "Stacks[].{\"Name\":StackName,\"Status\":StackStatus}"`)}
${dockerEnvConfig}
${runCommands}
${_chalk.default.gray(`Additional information about agent features can be found here:\n${helpers.agentsDocsUrl.AWS}`)}\n
`;
};
// Download latest aws apigw config zip
const downloadAPIGWAgentConfigZip = async () => {
const url = `/aws_apigw_agent_config/latest/${ConfigFiles.AgentConfigZip}`;
const service = await (0, _dataService.dataService)({
baseUrl: _types.PublicRepoUrl,
basePath: _types.BasePaths.AWSAgents
});
try {
const {
stream
} = await service.download(url);
await helpers.streamPipeline(stream, _fs.default.createWriteStream(ConfigFiles.AgentConfigZip));
return ConfigFiles.AgentConfigZip;
} catch (err) {
throw new Error(`Failed to download the agent: ${err.message}`);
}
};
// Unzip latest aws apigw config zip
const unzipAPIGWAgentConfigZip = async zipFile => {
await helpers.unzip(zipFile);
_fs.default.unlinkSync(zipFile);
const isCloudFormation = _fs.default.existsSync(ConfigFiles.DeployAllYAML);
if (!isCloudFormation) {
console.log(`${ConfigFiles.DeployAllYAML} was not extracted from ${ConfigFiles.AgentConfigZip}`);
return false;
}
return true;
};
const installPreprocess = async installConfig => {
// attempt to download the cloud formation files
console.log(_chalk.default.gray(`Downloading the latest Cloud formation template...`));
let apigwAgentConfigZipFile = await downloadAPIGWAgentConfigZip();
if (apigwAgentConfigZipFile !== '') {
console.log(_chalk.default.gray(`\nSuccess`));
}
installConfig.gatewayConfig.apigwAgentConfigZipFile = apigwAgentConfigZipFile;
return installConfig;
};
exports.installPreprocess = installPreprocess;
const completeInstall = async installConfig => {
/**
* Create agent resources
*/
const awsAgentValues = installConfig.gatewayConfig;
// Add final settings to awsAgentsValues
awsAgentValues.centralConfig = installConfig.centralConfig;
awsAgentValues.traceabilityConfig = installConfig.traceabilityConfig;
const unpackZip = await unzipAPIGWAgentConfigZip(awsAgentValues.apigwAgentConfigZipFile);
if (unpackZip) {
console.log('\nCreating the agent environment files for AWS...');
}
console.log('Generating the configuration file(s)...');
console.log('Generating the cloud formation parameters file...');
let paramStrings = [];
awsAgentValues.updateCloudFormationConfig();
for (let [key, value] of Object.entries(awsAgentValues.cloudFormationConfig)) {
paramStrings.push(`{"ParameterKey": "${key}", "ParameterValue": "${value}"}`);
}
(0, _utils.writeToFile)(ConfigFiles.CFProperties, `[\n${paramStrings.join(',\n')}\n]`);
if (installConfig.switches.isDaEnabled && DeploymentTypes.ECS_FARGATE !== awsAgentValues.cloudFormationConfig.DeploymentType) {
log('GENERATING DA TEMPLATE');
(0, _utils.writeTemplates)(ConfigFiles.DAEnvVars, awsAgentValues, helpers.awsDAEnvVarTemplate);
}
if (installConfig.switches.isTaEnabled && DeploymentTypes.ECS_FARGATE !== awsAgentValues.cloudFormationConfig.DeploymentType) {
log('GENERATING TA TEMPLATE');
(0, _utils.writeTemplates)(ConfigFiles.TAEnvVars, awsAgentValues, helpers.awsTAEnvVarTemplate);
}
console.log('Configuration file(s) have been successfully created.\n');
console.log(await generateOutput(installConfig));
};
exports.completeInstall = completeInstall;
const AWSInstallMethods = exports.AWSInstallMethods = {
GetBundleType: askBundleType,
GetDeploymentType: askConfigType,
AskGatewayQuestions: gatewayConnectivity,
InstallPreprocess: installPreprocess,
FinalizeGatewayInstall: completeInstall,
ConfigFiles: Object.values(ConfigFiles),
AgentNameMap: {
[_types.AgentTypes.da]: _types.AgentNames.AWS_DA,
[_types.AgentTypes.ta]: _types.AgentNames.AWS_TA
},
GatewayDisplay: _types.GatewayTypes.AWS_GATEWAY
};
// These are the items that are not exported, but need to be for testing
const testables = exports.testables = {
DeploymentTypes,
AWSPrompts,
EC2InstanceTypes,
ConfigFiles
};