Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: populate custom resources CDK stacks with region and account (#12575) #13316

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { getCDKProps } from '../../utils/generate-cfn-from-cdk';

describe('generate-cfn-from-cdk', () => {
describe('getCDKProps', () => {
beforeEach(() => {
process.env = {};
});

test('should return undefined if CDK env vars are not set', () => {
const actual = getCDKProps();
expect(Object.values(actual)).toHaveLength(0);
});

test('should return cdk props with env set', () => {
process.env = {
CDK_DEFAULT_ACCOUNT: 'some_account_id',
CDK_DEFAULT_REGION: 'us-east-1',
};

const actual = getCDKProps();

expect(actual.env?.account).toEqual('some_account_id');
expect(actual.env?.region).toEqual('us-east-1');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,32 @@ import * as cdk from 'aws-cdk-lib';
import { JSONUtilities, pathManager } from '@aws-amplify/amplify-cli-core';
import * as path from 'path';
import { categoryName } from './constants';
import { StackProps } from 'aws-cdk-lib';

export type AmplifyResourceProps = {
category: string;
resourceName: string;
};

export function getCDKProps(): StackProps {
if (process.env.CDK_DEFAULT_ACCOUNT || process.env.CDK_DEFAULT_REGION) {
bombguy marked this conversation as resolved.
Show resolved Hide resolved
return {
bombguy marked this conversation as resolved.
Show resolved Hide resolved
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
};
}
return {};
}

export async function generateCloudFormationFromCDK(resourceName: string) {
const targetDir = pathManager.getResourceDirectoryPath(undefined, categoryName, resourceName);
const { cdkStack } = await import(path.resolve(path.join(targetDir, 'build', 'cdk-stack.js')));

const amplifyResourceProps: AmplifyResourceProps = { category: categoryName, resourceName };

const customStack: cdk.Stack = new cdkStack(undefined, undefined, undefined, amplifyResourceProps);
const customStack: cdk.Stack = new cdkStack(undefined, undefined, getCDKProps(), amplifyResourceProps);

// @ts-ignore
JSONUtilities.writeJson(path.join(targetDir, 'build', `${resourceName}-cloudformation-template.json`), customStack._toCloudFormation());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as cdk from 'aws-cdk-lib';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as subs from 'aws-cdk-lib/aws-sns-subscriptions';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';

// eslint-disable-next-line import/no-extraneous-dependencies
import * as AmplifyHelpers from '@aws-amplify/cli-extensibility-helper';

export class cdkStack extends cdk.Stack {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(scope: Construct, id: string, props?: cdk.StackProps, amplifyResourceProps?: AmplifyHelpers.AmplifyResourceProps) {
super(scope, id, props);
/* Do not remove - Amplify CLI automatically injects the current deployment environment in this input parameter */
new cdk.CfnParameter(this, 'env', {
type: 'String',
description: 'Current Amplify CLI env name',
});
/* AWS CDK code goes here - learn more: https://docs.aws.amazon.com/cdk/latest/guide/home.html */

ec2.Vpc.fromLookup(this, 'VPC', {
isDefault: true,
});

const queue = new sqs.Queue(this, 'sqs-queue');
// 👇 create sns topic
const topic = new sns.Topic(this, 'sns-topic');

// 👇 subscribe queue to topic
topic.addSubscription(new subs.SqsSubscription(queue));

// creation of resources inside the VPC
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { v4 as uuid } from 'uuid';

describe('adding custom resources test', () => {
let projRoot: string;

beforeEach(async () => {
projRoot = await createNewProjectDir('custom-resources');
});
Expand Down Expand Up @@ -130,4 +131,23 @@ describe('adding custom resources test', () => {
},
});
});

it('should use default cdk env var if set', async () => {
const cdkResourceName = `custom${uuid().split('-')[0]}`;
const destCustomResourceFilePath = path.join(projRoot, 'amplify', 'backend', 'custom', cdkResourceName, 'cdk-stack.ts');
const srcCustomResourceFilePath = path.join(__dirname, '..', '..', 'custom-resources', 'barebone-cdk-stack.ts');

await initJSProjectWithProfile(projRoot, {});
await addCDKCustomResource(projRoot, { name: cdkResourceName });

fs.copyFileSync(srcCustomResourceFilePath, destCustomResourceFilePath);

// no aws account & region set, should throw error,
await expect(amplifyPushAuth(projRoot)).rejects.toThrowError();

// should pickup to default cdk env vars and build cfn stack.
process.env.CDK_DEFAULT_ACCOUNT = 'some_id';
process.env.CDK_DEFAULT_REGION = process.env.CLI_REGION;
await amplifyPushAuth(projRoot);
Comment on lines +148 to +151
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this lacks assertion.
we have developed the following mechanism in override tests to assert that injected values actually work

if (amplifyProjectInfo.envName != '##EXPECTED_ENV_NAME') {
throw new Error(`Unexpected envName: ${amplifyProjectInfo.envName}`);
}
if (amplifyProjectInfo.projectName != '##EXPECTED_PROJECT_NAME') {
throw new Error(`Unexpected envName: ${amplifyProjectInfo.envName}`);
}

Can we please use similar pattern in barebone-cdk-stack.ts ?

});
});