Skip to content

Commit

Permalink
feat(lib): throw error when a token is used in a construct name
Browse files Browse the repository at this point in the history
Closes #1068
  • Loading branch information
DanielMSchmidt committed Oct 26, 2021
1 parent 5122309 commit 2a58d70
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/cdktf/lib/terraform-element.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Construct } from "constructs";
import { Tokenization } from ".";
import { TerraformStack } from "./terraform-stack";

export interface TerraformElementMetadata {
Expand All @@ -19,6 +20,12 @@ export class TerraformElement extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);

if (Tokenization.containsToken(id)) {
throw new Error(
"You can not use a Token (e.g. a reference to an attribute) as name of a construct"
);
}

this.node.addMetadata("stacktrace", "trace");
this.cdktfStack = TerraformStack.of(this);
}
Expand Down
4 changes: 4 additions & 0 deletions packages/cdktf/lib/tokens/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ export class Tokenization {
return [];
}

public static containsToken(x: any): boolean {
return Tokenization.reverse(x).length > 0;
}

/**
* Un-encode a string potentially containing encoded tokens
*/
Expand Down
18 changes: 18 additions & 0 deletions packages/cdktf/test/resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,21 @@ test("numeric attributes", () => {

expect(Testing.synth(stack)).toMatchSnapshot();
});

test("tokens as ids", () => {
const app = Testing.app();
const stack = new TerraformStack(app, "test");
new TestProvider(stack, "provider", {});

const foo = new TestResource(stack, "resource", {
name: "foo",
});

expect(() => {
new TestResource(stack, `resource-${foo.stringValue}`, {
name: "foo",
});
}).toThrowErrorMatchingInlineSnapshot(
`"You can not use a Token (e.g. a reference to an attribute) as name of a construct"`
);
});

0 comments on commit 2a58d70

Please sign in to comment.