Skip to content

Commit b707782

Browse files
author
Elad Ben-Israel
authored
feat(cdk-dasm): wip: generate cdk code from cloudformation (#2244)
(not fully functional yet) Converts AWS CloudFormation templates to CDK TypeScript code that synthesizes the same output.
1 parent aebcde5 commit b707782

13 files changed

+5914
-0
lines changed

packages/cdk-dasm/.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
*.js
2+
*.d.ts
3+
!deps.js
4+
test/fixture/.jsii
5+
cdk.schema.json

packages/cdk-dasm/README.md

+114
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# CDK CloudFormation Disassembler
2+
3+
[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)
4+
5+
----
6+
7+
## __WIP__ - this module is still not fully functional:
8+
9+
- [ ] Does not handle intrinsic functions
10+
- [ ] Only handles the "Resources" section (parameters, outputs, mappings,
11+
conditions, ...)
12+
- [ ] Keys in JSON blobs (such as IAM policies) are converted to camel case
13+
(instead of remain as pascal case).
14+
- [ ] Only TypeScript is supported
15+
16+
-----
17+
18+
Converts an AWS CloudFormation template into AWS CDK code which synthesizes the
19+
same exact template.
20+
21+
## Why you should not use this tool?
22+
23+
Generally, this is not a recommended approach when using the AWS CDK, but some
24+
people may find this useful as a means to get started or migrate an existing
25+
template.
26+
27+
Using this method means that you will have to use the low-level resources (e.g.
28+
`s3.CfnBucket` instead of `s3.Bucket`). This means that you lose a substantial
29+
portion of the value of the CDK, which abstracts away much of the boilerplate
30+
and glue logic required to work with AWS resources.
31+
32+
For example, this is how you would define an S3 bucket encrypted with a KMS key
33+
with high-level resources:
34+
35+
```ts
36+
new s3.Bucket(this, 'MyBucket', {
37+
encryption: s3.BucketEncryption.Kms
38+
});
39+
```
40+
41+
And this is how the same exact configuration will be defined using low-level
42+
resources:
43+
44+
```ts
45+
new kms.CfnKey(this, 'MyBucketKeyC17130CF', {
46+
keyPolicy: {
47+
"statement": [
48+
{
49+
"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" ],
50+
"effect": "Allow",
51+
"principal": {
52+
"aws": { "Fn::Join": [ "", [ "arn:", { "Ref": "AWS::Partition" }, ":iam::", { "Ref": "AWS::AccountId" }, ":root" ] ] }
53+
},
54+
"resource": "*"
55+
}
56+
],
57+
"version": "2012-10-17"
58+
}
59+
});
60+
61+
new s3.CfnBucket(this, 'MyBucketF68F3FF0', {
62+
bucketEncryption: {
63+
"serverSideEncryptionConfiguration": [
64+
{
65+
"serverSideEncryptionByDefault": {
66+
"kmsMasterKeyId": Fn.getAtt('MyBucketKeyC17130CF', 'Arn').toString(),
67+
"sseAlgorithm": "aws:kms"
68+
}
69+
}
70+
]
71+
},
72+
});
73+
```
74+
As you can see, there are a lot of details here that you really don't want to
75+
care about (like the value to put under `sseAlgorithm` or which actions are
76+
required in the key policy so the key can be managed by administrators. Also,
77+
this is actually one of the more simple examples we have in the CDK.
78+
79+
The AWS Construct Library includes a very large amount of "undifferentiated
80+
heavy lifting" that you can only enjoy if you use the high level resources which
81+
encapsulate all this goodness for you behind a nice clean object-oriented API.
82+
83+
Therefore, we encourage you to use the high-level constructs in the AWS
84+
Construct Library as much as possible. If you encounter a gap or missing
85+
capability or resource, take a look at the [Escape
86+
Hatches](https://docs.aws.amazon.com/CDK/latest/userguide/cfn_layer.html)
87+
section of the User Guide.
88+
89+
## Usage
90+
91+
```console
92+
$ cdk-dasm < my-stack-template.json > my-stack.ts
93+
```
94+
95+
For example, given:
96+
97+
```json
98+
{
99+
"Resources": {
100+
"MyTopic": {
101+
"Type": "AWS::SNS::Topic",
102+
"Properties": {
103+
"DisplayName": "YoTopic"
104+
}
105+
}
106+
}
107+
}
108+
```
109+
110+
The output will be:
111+
112+
```ts
113+
114+
```

packages/cdk-dasm/bin/cdk-dasm

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#!/usr/bin/env node
2+
require('./cdk-dasm.js');

packages/cdk-dasm/bin/cdk-dasm.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import YAML = require('yaml');
2+
import { dasmTypeScript } from '../lib';
3+
4+
let s = '';
5+
process.stdin.resume();
6+
process.stdin.on('data', data => {
7+
s += data.toString('utf-8');
8+
});
9+
10+
process.stdin.on('end', () => {
11+
dasmTypeScript(YAML.parse(s)).then(out => {
12+
process.stdout.write(out);
13+
});
14+
});

packages/cdk-dasm/jest.config.js

+180
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// For a detailed explanation regarding each configuration property, visit:
2+
// https://jestjs.io/docs/en/configuration.html
3+
4+
module.exports = {
5+
// All imported modules in your tests should be mocked automatically
6+
// automock: false,
7+
8+
// Stop running tests after `n` failures
9+
// bail: 0,
10+
11+
// Respect "browser" field in package.json when resolving modules
12+
// browser: false,
13+
14+
// The directory where Jest should store its cached dependency information
15+
// cacheDirectory: "/private/var/folders/n2/6v4_tbz97ws0h4bn5gbyvzb0m8vcjb/T/jest_b92skr",
16+
17+
// Automatically clear mock calls and instances between every test
18+
// clearMocks: false,
19+
20+
// Indicates whether the coverage information should be collected while executing the test
21+
// collectCoverage: false,
22+
23+
// An array of glob patterns indicating a set of files for which coverage information should be collected
24+
// collectCoverageFrom: null,
25+
26+
// The directory where Jest should output its coverage files
27+
coverageDirectory: "coverage",
28+
29+
// An array of regexp pattern strings used to skip coverage collection
30+
// coveragePathIgnorePatterns: [
31+
// "/node_modules/"
32+
// ],
33+
34+
// A list of reporter names that Jest uses when writing coverage reports
35+
// coverageReporters: [
36+
// "json",
37+
// "text",
38+
// "lcov",
39+
// "clover"
40+
// ],
41+
42+
// An object that configures minimum threshold enforcement for coverage results
43+
// coverageThreshold: null,
44+
45+
// A path to a custom dependency extractor
46+
// dependencyExtractor: null,
47+
48+
// Make calling deprecated APIs throw helpful error messages
49+
// errorOnDeprecated: false,
50+
51+
// Force coverage collection from ignored files using an array of glob patterns
52+
// forceCoverageMatch: [],
53+
54+
// A path to a module which exports an async function that is triggered once before all test suites
55+
// globalSetup: null,
56+
57+
// A path to a module which exports an async function that is triggered once after all test suites
58+
// globalTeardown: null,
59+
60+
// A set of global variables that need to be available in all test environments
61+
// globals: {},
62+
63+
// An array of directory names to be searched recursively up from the requiring module's location
64+
// moduleDirectories: [
65+
// "node_modules"
66+
// ],
67+
68+
// An array of file extensions your modules use
69+
moduleFileExtensions: [
70+
"js"
71+
],
72+
73+
// A map from regular expressions to module names that allow to stub out resources with a single module
74+
// moduleNameMapper: {},
75+
76+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
77+
// modulePathIgnorePatterns: [],
78+
79+
// Activates notifications for test results
80+
// notify: false,
81+
82+
// An enum that specifies notification mode. Requires { notify: true }
83+
// notifyMode: "failure-change",
84+
85+
// A preset that is used as a base for Jest's configuration
86+
// preset: null,
87+
88+
// Run tests from one or more projects
89+
// projects: null,
90+
91+
// Use this configuration option to add custom reporters to Jest
92+
// reporters: undefined,
93+
94+
// Automatically reset mock state between every test
95+
// resetMocks: false,
96+
97+
// Reset the module registry before running each individual test
98+
// resetModules: false,
99+
100+
// A path to a custom resolver
101+
// resolver: null,
102+
103+
// Automatically restore mock state between every test
104+
// restoreMocks: false,
105+
106+
// The root directory that Jest should scan for tests and modules within
107+
// rootDir: null,
108+
109+
// A list of paths to directories that Jest should use to search for files in
110+
// roots: [
111+
// "<rootDir>"
112+
// ],
113+
114+
// Allows you to use a custom runner instead of Jest's default test runner
115+
// runner: "jest-runner",
116+
117+
// The paths to modules that run some code to configure or set up the testing environment before each test
118+
// setupFiles: [],
119+
120+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
121+
// setupFilesAfterEnv: [],
122+
123+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
124+
// snapshotSerializers: [],
125+
126+
// The test environment that will be used for testing
127+
testEnvironment: "node",
128+
129+
// Options that will be passed to the testEnvironment
130+
// testEnvironmentOptions: {},
131+
132+
// Adds a location field to test results
133+
// testLocationInResults: false,
134+
135+
// The glob patterns Jest uses to detect test files
136+
// testMatch: [
137+
// "**/__tests__/**/*.[jt]s?(x)",
138+
// "**/?(*.)+(spec|test).[tj]s?(x)"
139+
// ],
140+
141+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
142+
// testPathIgnorePatterns: [
143+
// "/node_modules/"
144+
// ],
145+
146+
// The regexp pattern or array of patterns that Jest uses to detect test files
147+
// testRegex: [],
148+
149+
// This option allows the use of a custom results processor
150+
// testResultsProcessor: null,
151+
152+
// This option allows use of a custom test runner
153+
// testRunner: "jasmine2",
154+
155+
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
156+
// testURL: "http://localhost",
157+
158+
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
159+
// timers: "real",
160+
161+
// A map from regular expressions to paths to transformers
162+
// transform: null,
163+
164+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
165+
// transformIgnorePatterns: [
166+
// "/node_modules/"
167+
// ],
168+
169+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
170+
// unmockedModulePathPatterns: undefined,
171+
172+
// Indicates whether each individual test should be reported during the run
173+
// verbose: null,
174+
175+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
176+
// watchPathIgnorePatterns: [],
177+
178+
// Whether to use watchman for file crawling
179+
// watchman: true,
180+
};

0 commit comments

Comments
 (0)