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

feat(cdk-dasm): generate cdk code from cloudformation #2244

Merged
merged 3 commits into from
Apr 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions packages/cdk-dasm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*.js
*.d.ts
!deps.js
test/fixture/.jsii
cdk.schema.json
114 changes: 114 additions & 0 deletions packages/cdk-dasm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# CDK CloudFormation Disassembler

[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)

----

## __WIP__ - this module is still not fully functional:

- [ ] Does not handle intrinsic functions
- [ ] Only handles the "Resources" section (parameters, outputs, mappings,
conditions, ...)
- [ ] Keys in JSON blobs (such as IAM policies) are converted to camel case
(instead of remain as pascal case).
- [ ] Only TypeScript is supported

-----

Converts an AWS CloudFormation template into AWS CDK code which synthesizes the
same exact template.

## Why you should not use this tool?

Generally, this is not a recommended approach when using the AWS CDK, but some
people may find this useful as a means to get started or migrate an existing
template.

Using this method means that you will have to use the low-level resources (e.g.
`s3.CfnBucket` instead of `s3.Bucket`). This means that you lose a substantial
portion of the value of the CDK, which abstracts away much of the boilerplate
and glue logic required to work with AWS resources.

For example, this is how you would define an S3 bucket encrypted with a KMS key
with high-level resources:

```ts
new s3.Bucket(this, 'MyBucket', {
encryption: s3.BucketEncryption.Kms
});
```

And this is how the same exact configuration will be defined using low-level
resources:

```ts
new kms.CfnKey(this, 'MyBucketKeyC17130CF', {
keyPolicy: {
"statement": [
{
"action": [ "kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*", "kms:Update*", "kms:Revoke*", "kms:Disable*", "kms:Get*", "kms:Delete*", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion" ],
"effect": "Allow",
"principal": {
"aws": { "Fn::Join": [ "", [ "arn:", { "Ref": "AWS::Partition" }, ":iam::", { "Ref": "AWS::AccountId" }, ":root" ] ] }
},
"resource": "*"
}
],
"version": "2012-10-17"
}
});

new s3.CfnBucket(this, 'MyBucketF68F3FF0', {
bucketEncryption: {
"serverSideEncryptionConfiguration": [
{
"serverSideEncryptionByDefault": {
"kmsMasterKeyId": Fn.getAtt('MyBucketKeyC17130CF', 'Arn').toString(),
"sseAlgorithm": "aws:kms"
}
}
]
},
});
```
As you can see, there are a lot of details here that you really don't want to
care about (like the value to put under `sseAlgorithm` or which actions are
required in the key policy so the key can be managed by administrators. Also,
this is actually one of the more simple examples we have in the CDK.

The AWS Construct Library includes a very large amount of "undifferentiated
heavy lifting" that you can only enjoy if you use the high level resources which
encapsulate all this goodness for you behind a nice clean object-oriented API.

Therefore, we encourage you to use the high-level constructs in the AWS
Construct Library as much as possible. If you encounter a gap or missing
capability or resource, take a look at the [Escape
Hatches](https://docs.aws.amazon.com/CDK/latest/userguide/cfn_layer.html)
section of the User Guide.

## Usage

```console
$ cdk-dasm < my-stack-template.json > my-stack.ts
```

For example, given:

```json
{
"Resources": {
"MyTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"DisplayName": "YoTopic"
}
}
}
}
```

The output will be:

```ts

```
2 changes: 2 additions & 0 deletions packages/cdk-dasm/bin/cdk-dasm
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./cdk-dasm.js');
14 changes: 14 additions & 0 deletions packages/cdk-dasm/bin/cdk-dasm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import YAML = require('yaml');
import { dasmTypeScript } from '../lib';

let s = '';
process.stdin.resume();
process.stdin.on('data', data => {
s += data.toString('utf-8');
});

process.stdin.on('end', () => {
dasmTypeScript(YAML.parse(s)).then(out => {
process.stdout.write(out);
});
});
141 changes: 141 additions & 0 deletions packages/cdk-dasm/lib/dasm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { CodeMaker, toCamelCase } from 'codemaker';
import fs = require('fs');
import os = require('os');
import path = require('path');
import { promisify, deprecate } from 'util';

const mkdtemp = promisify(fs.mkdtemp);
const readFile = promisify(fs.readFile);

interface ConstructDefinition {
namespace: string;
className: string;
id: string;
props: { [key: string]: any };
}

export async function dasmTypeScript(template: Template) {
const definitions = new Array<ConstructDefinition>();

for (const [ id, resource ] of Object.entries(template.Resources || {})) {
const type = resource.Type;
const props = resource.Properties || {};

definitions.push({
id,
...toCfnClassName(type),
props: capitalizeKeys(props)
});
}

const code = new CodeMaker();

const outFile = 'out.ts';

code.openFile(outFile);

code.line(`// generated by cdk-dasm at ${new Date().toISOString()}`);
code.line();

//
// imports
//

code.line(`import { Stack, StackProps, Construct, Fn } from '@aws-cdk/cdk';`);

for (const def of definitions) {
const importName = `@aws-cdk/aws-${def.namespace}`;
code.line(`import ${def.namespace} = require('${importName}');`);
}

code.line();

//
// stack
//

code.openBlock(`export class MyStack extends Stack`);
code.openBlock(`constructor(scope: Construct, id: string, props: StackProps = {})`);
code.line(`super(scope, id, props);`);

for (const def of definitions) {

// no props
if (Object.keys(def.props).length === 0) {
code.line(`new ${def.className}(this, '${def.id}');`);
continue;
}

code.indent(`new ${def.className}(this, '${def.id}', {`);

for (const [key, value] of Object.entries(def.props)) {
const json = JSON.stringify(value, undefined, 2);
const [ first, ...rest ] = json.split('\n');

if (rest.length === 0) {
code.line(`${key}: ${first},`); // single line
} else {
code.line(`${key}: ${first}`);
rest.forEach((r, i) => {
code.line(r + ((i === rest.length - 1) ? ',' : ''));
});
}
}

code.unindent('});');
}

code.closeBlock();

code.closeBlock(' // MyStack');

code.closeFile(outFile);

const workdir = await mkdtemp(path.join(os.tmpdir(), 'cdk-dasm-typescript'));
await code.save(workdir);

return (await readFile(path.join(workdir, outFile))).toString();
}

function capitalizeKeys(x: any): any {
if (typeof(x) === 'function') {
throw new Error(`function?`);
}

if (Array.isArray(x)) {
return x.map(i => capitalizeKeys(i));
}

if (typeof(x) === 'object') {
const ret: { [key: string]: any } = {};
for (const [ key, value ] of Object.entries(x)) {
let newKey;
if (key === 'Ref' || key.startsWith('Fn::')) {
newKey = key;
} else {
newKey = toCamelCase(key);
}

ret[newKey] = capitalizeKeys(value);
}
return ret;
}

// primitive
return x;
}

function toCfnClassName(resourceType: string) {
const [ , namespace, type ] = resourceType.split('::');
const className = `${namespace.toLocaleLowerCase()}.Cfn${type}`;
return { namespace: namespace.toLocaleLowerCase(), className };
}

interface Template {
Resources: { [id: string]: Resource };
}

interface Resource {
Type: string;
Properties?: { [prop: string]: any }
}
1 change: 1 addition & 0 deletions packages/cdk-dasm/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './dasm';
Loading