-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.ts
407 lines (359 loc) · 11.6 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
import { Construct } from "constructs";
import {
App,
TerraformStack,
TerraformOutput,
RemoteBackend,
Annotations,
Aspects,
MigrateIds,
} from "cdktf";
import {
GithubRepository,
GithubRepositoryFromExistingRepository,
SecretFromVariable,
PublishingSecretSet,
} from "./lib";
import * as fs from "fs";
import * as path from "path";
import { TerraformVariable } from "cdktf";
import { GithubProvider } from "@cdktf/provider-github/lib/provider";
import { DataGithubTeam } from "@cdktf/provider-github/lib/data-github-team";
type StackShards = {
primaryStack: string;
stacks: {
[name: string]: {
backend: {
workspaceName: string;
};
providers: string[];
};
};
};
const allProviders: Record<string, string> = JSON.parse(
fs.readFileSync(path.join(__dirname, "provider.json"), "utf8"),
);
const shardedStacks: StackShards = JSON.parse(
fs.readFileSync(path.join(__dirname, "sharded-stacks.json"), "utf8"),
);
interface GitUrls {
html: string;
ssh: string;
}
/**
* Get list of providers that need to be generated for a stack with name
*
* @param name name of stack as defined in sharded-stacks.json
* @returns Object containing provider name to terraform provider version
*/
function getShardedStackProviders(name: string): Record<string, string> {
const stackShardInformation = shardedStacks.stacks[name];
const stackProvidersList = stackShardInformation.providers;
return Object.fromEntries(
Object.entries(allProviders).filter(([key]) =>
stackProvidersList.includes(key),
),
);
}
class TerraformCdkProviderStack extends TerraformStack {
constructor(scope: Construct, name: string, isPrimaryStack: boolean) {
super(scope, name);
const providers = getShardedStackProviders(name);
this.validateProviderNames(providers);
const githubProvider = new GithubProvider(this, "github-provider-cdktf", {
owner: "cdktf",
alias: "cdktf",
});
const githubTeam = new DataGithubTeam(this, "cdktf-team-cdktf", {
slug: "tf-cdk-team",
provider: githubProvider,
});
new RemoteBackend(this, {
organization: "cdktf-team",
workspaces: {
name: shardedStacks.stacks[name].backend.workspaceName,
},
});
const slackWebhook = new TerraformVariable(this, "slack-webhook", {
type: "string",
});
slackWebhook.overrideLogicalId("slack-webhook");
const secrets = new PublishingSecretSet(this, "secret-set");
if (isPrimaryStack) {
this.createRepositoryManagerRepo(
slackWebhook,
githubProvider,
githubTeam,
);
this.createProviderProjectRepo(
slackWebhook,
secrets.npmSecret,
githubProvider,
githubTeam,
);
}
const providerRepos: GitUrls[] = Object.keys(providers).map((provider) => {
const repo = new GithubRepository(this, `cdktf-provider-${provider}`, {
description: `Prebuilt Terraform CDK (cdktf) provider for ${provider}.`,
topics: [...GithubRepository.defaultTopics, provider],
team: githubTeam,
protectMain: true,
protectMainChecks: [
"build",
"package-js",
"package-java",
"package-python",
"package-dotnet",
"package-go",
"Validate PR title",
],
webhookUrl: slackWebhook.stringValue,
provider: githubProvider,
});
// repo to publish go packages to
new GithubRepository(this, `cdktf-provider-${provider}-go`, {
description: `CDK for Terraform Go provider bindings for ${provider}.`,
topics: [...GithubRepository.defaultTopics, provider],
team: githubTeam,
protectMain: false,
webhookUrl: slackWebhook.stringValue,
provider: githubProvider,
});
secrets.forAllLanguages(repo.resource, githubProvider);
repo.addSecret("alert-prs-slack-webhook-url");
return {
html: repo.resource.htmlUrl,
ssh: repo.resource.sshCloneUrl,
};
});
new TerraformOutput(this, `providerRepos`, {
value: `\${[${providerRepos.map((e) => `"${e.ssh}"`).join(",")}]}`,
});
}
private createProviderProjectRepo(
slackWebhook: TerraformVariable,
npmSecret: SecretFromVariable,
githubProvider: GithubProvider,
githubTeam: DataGithubTeam,
) {
const templateRepository = new GithubRepository(
this,
"cdktf-provider-project",
{
team: githubTeam,
webhookUrl: slackWebhook.stringValue,
protectMain: true,
protectMainChecks: ["build", "package-js", "license/cla"],
provider: githubProvider,
},
);
npmSecret.for(templateRepository.resource, githubProvider);
new TerraformOutput(this, "templateRepoUrl", {
value: templateRepository?.resource.htmlUrl,
});
}
private createRepositoryManagerRepo(
slackWebhook: TerraformVariable,
githubProvider: GithubProvider,
githubTeam: DataGithubTeam,
) {
const selfTokens = [
new SecretFromVariable(this, "tf-cloud-token"),
new SecretFromVariable(this, "gh-comment-token"),
];
const self = new GithubRepository(this, "cdktf-repository-manager", {
team: githubTeam,
webhookUrl: slackWebhook.stringValue,
provider: githubProvider,
});
selfTokens.forEach((token) => token.for(self.resource, githubProvider));
new TerraformOutput(this, "selfRepoUrl", {
value: self.resource.htmlUrl,
});
}
private validateProviderNames(providers: Record<string, string>) {
// validate that providers contain only valid names (-go suffix is forbidden)
const goSuffixProviders = Object.keys(providers).filter((key) =>
key.endsWith("-go"),
);
if (goSuffixProviders.length > 0) {
Annotations.of(this).addError(
`Providers contain a provider key with a suffix -go which is not allowed due to conflicts with go package repositories. Please remove the -go suffix from these provider keys ${goSuffixProviders.join(
", ",
)}`,
);
}
// validate key matches provider name
const notMatchingProviders = Object.entries(providers).filter(
([key, value]) => {
const fullProviderName = new RegExp("(.*)@", "g").exec(value)![1];
const providerName = fullProviderName.includes("/")
? fullProviderName.split("/")[1]
: fullProviderName;
const sanitizedProviderName = providerName.replace(/-/g, "");
return key !== sanitizedProviderName;
},
);
if (notMatchingProviders.length > 0) {
Annotations.of(this).addError(
`Provider name and provider key do not match for ${notMatchingProviders.join(
", ",
)}. This leads to issues when deploying go packages. Please rename the provider key to match the provider name.`,
);
}
}
}
class CustomConstructsStack extends TerraformStack {
constructor(
scope: Construct,
name: string,
constructRepos: {
name: string;
languages: ("typescript" | "python" | "csharp" | "java" | "go")[];
topics?: string[];
}[],
) {
super(scope, name);
const githubProvider = new GithubProvider(this, "github-provider-cdktf", {
owner: "cdktf",
alias: "cdktf",
});
const githubTeam = new DataGithubTeam(this, "cdktf-team-cdktf", {
slug: "tf-cdk-team",
provider: githubProvider,
});
new RemoteBackend(this, {
organization: "cdktf-team",
workspaces: {
name: "custom-constructs",
},
});
const slackWebhook = new TerraformVariable(this, "slack-webhook", {
type: "string",
});
slackWebhook.overrideLogicalId("slack-webhook");
const secrets = new PublishingSecretSet(this, "secret-set");
constructRepos.forEach(({ name: repoName, languages, topics }) => {
const protectMainChecks = ["build", "license/cla"].concat(
languages.map((language) => {
return `package-${
language === "typescript"
? "js"
: language === "csharp"
? "dotnet"
: language
}`;
}),
);
const repo = new GithubRepositoryFromExistingRepository(
this,
`cdktf-construct-${repoName}`,
{
repositoryName: repoName,
team: githubTeam,
webhookUrl: slackWebhook.stringValue,
provider: githubProvider,
protectMain: true,
protectMainChecks,
},
);
secrets.forGitHub(repo.resource, githubProvider);
if (languages.includes("typescript")) {
secrets.forTypescript(repo.resource, githubProvider);
}
if (languages.includes("python")) {
secrets.forPython(repo.resource, githubProvider);
}
if (languages.includes("csharp")) {
secrets.forCsharp(repo.resource, githubProvider);
}
if (languages.includes("java")) {
secrets.forJava(repo.resource, githubProvider);
}
if (languages.includes("go")) {
secrets.forGo(repo.resource, githubProvider);
// repo to publish go packages to
new GithubRepository(this, `${repoName}-go`, {
description: `CDK for Terraform Go bindings for ${repoName}.`,
topics,
team: githubTeam,
protectMain: false,
webhookUrl: slackWebhook.stringValue,
provider: githubProvider,
});
}
});
}
}
const app = new App();
const primaryStackName = shardedStacks.primaryStack;
const stackNames = Object.keys(shardedStacks.stacks);
const allProvidersInShards = Object.values(shardedStacks.stacks)
.map((stack) => stack.providers)
.flat() as string[];
const allProviderNames = Object.keys(allProviders);
// Validations for provider names
const shardProviderSet = new Set(allProvidersInShards);
const allProviderSet = new Set(allProviderNames);
const missingProvidersInShards = new Set(
[...allProviderSet].filter((provider) => !shardProviderSet.has(provider)),
);
const missingProvidersInAllProviders = new Set(
[...shardProviderSet].filter((provider) => !allProviderSet.has(provider)),
);
if (shardProviderSet.size < allProvidersInShards.length) {
throw new Error("Duplicates present in sharded-stacks.json");
}
if (missingProvidersInShards.size > 0) {
throw new Error(
`One or more providers present in provider.json are missing in sharded-stacks.json: ${[
...missingProvidersInShards,
]}`,
);
}
if (missingProvidersInAllProviders.size > 0) {
throw new Error(
`One or more providers present in sharded-stacks.json are missing in provider.json: ${[
...missingProvidersInAllProviders,
]}`,
);
}
if (!primaryStackName) {
throw new Error("Cannot proceed without a primary stack");
}
if (!stackNames.includes(primaryStackName)) {
throw new Error("Cannot proceed with a non-existent stack as primary");
}
stackNames.forEach((stackName) => {
const providerStack = new TerraformCdkProviderStack(
app,
stackName,
primaryStackName === stackName,
);
Aspects.of(providerStack).add(new MigrateIds());
});
const customConstructs = new CustomConstructsStack(app, "custom-constructs", [
{
name: "cdktf-tf-module-stack",
languages: ["typescript", "python", "csharp", "java", "go"],
topics: ["terraform", "cdktf", "terraform-module"],
},
{
name: "cdktf-cdk8s",
languages: ["typescript", "python"],
},
{
name: "cdktf-local-exec",
languages: ["typescript", "python"],
},
{
name: "cdktf-multi-stack-tfe",
languages: ["typescript", "python"],
},
]);
Aspects.of(customConstructs).add(new MigrateIds());
app.synth();