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 21, 2021
1 parent 5122309 commit 788496a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/cdktf/lib/terraform-resource.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Construct } from "constructs";
import { Token } from "./tokens";
import { Token, Tokenization } from "./tokens";
import { TerraformElement } from "./terraform-element";
import { TerraformProvider } from "./terraform-provider";
import { keysToSnakeCase, deepMerge } from "./util";
Expand Down Expand Up @@ -60,6 +60,12 @@ export class TerraformResource
constructor(scope: Construct, id: string, config: TerraformResourceConfig) {
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.terraformResourceType = config.terraformResourceType;
this.terraformGeneratorMetadata = config.terraformGeneratorMetadata;
if (Array.isArray(config.dependsOn)) {
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 788496a

Please sign in to comment.