@pagopa/dx-cli 0.18.7 → 0.18.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/azure/__tests__/cloud-account-service.test.js +30 -1
- package/dist/adapters/azure/cloud-account-service.js +43 -2
- package/dist/adapters/commander/commands/__tests__/init.test.d.ts +4 -0
- package/dist/adapters/commander/commands/__tests__/init.test.js +159 -0
- package/dist/adapters/commander/commands/init.d.ts +8 -1
- package/dist/adapters/commander/commands/init.js +58 -9
- package/dist/adapters/plop/index.d.ts +2 -1
- package/dist/adapters/plop/index.js +4 -2
- package/package.json +1 -1
- package/templates/environment/bootstrapper/{{env.name}}/main.tf.hbs +1 -0
- package/templates/monorepo/.pre-commit-config.yaml.hbs +1 -1
|
@@ -4,6 +4,12 @@ import { AzureCloudAccountService } from "../cloud-account-service.js";
|
|
|
4
4
|
const { queryResources } = vi.hoisted(() => ({
|
|
5
5
|
queryResources: vi.fn().mockRejectedValue(new Error("Not implemented")),
|
|
6
6
|
}));
|
|
7
|
+
const { mockProviderGet, mockProviderRegister } = vi.hoisted(() => ({
|
|
8
|
+
mockProviderGet: vi
|
|
9
|
+
.fn()
|
|
10
|
+
.mockResolvedValue({ registrationState: "Registered" }),
|
|
11
|
+
mockProviderRegister: vi.fn().mockResolvedValue({}),
|
|
12
|
+
}));
|
|
7
13
|
vi.mock("@azure/identity", () => ({
|
|
8
14
|
DefaultAzureCredential: vi.fn(),
|
|
9
15
|
}));
|
|
@@ -12,6 +18,14 @@ vi.mock("@azure/arm-resourcegraph", () => ({
|
|
|
12
18
|
resources = queryResources;
|
|
13
19
|
},
|
|
14
20
|
}));
|
|
21
|
+
vi.mock("@azure/arm-resources", () => ({
|
|
22
|
+
ResourceManagementClient: class {
|
|
23
|
+
providers = {
|
|
24
|
+
get: mockProviderGet,
|
|
25
|
+
register: mockProviderRegister,
|
|
26
|
+
};
|
|
27
|
+
},
|
|
28
|
+
}));
|
|
15
29
|
const test = baseTest.extend({
|
|
16
30
|
// the empty pattern is required by vitest!!!
|
|
17
31
|
// eslint-disable-next-line no-empty-pattern
|
|
@@ -94,11 +108,12 @@ describe("getTerraformBackend", () => {
|
|
|
94
108
|
});
|
|
95
109
|
});
|
|
96
110
|
describe("isInitialized", () => {
|
|
97
|
-
test("returns true when both bootstrap identity and common Key Vault exist", async ({ cloudAccountService, }) => {
|
|
111
|
+
test("returns true when both bootstrap identity and common Key Vault exist and all providers are registered", async ({ cloudAccountService, }) => {
|
|
98
112
|
// First call: identity query → found
|
|
99
113
|
queryResources.mockResolvedValueOnce({ data: [], totalRecords: 1 });
|
|
100
114
|
// Second call: key vault query → found
|
|
101
115
|
queryResources.mockResolvedValueOnce({ data: [], totalRecords: 1 });
|
|
116
|
+
// Provider checks → all registered (default mock)
|
|
102
117
|
const result = await cloudAccountService.isInitialized("sub-1", {
|
|
103
118
|
name: "dev",
|
|
104
119
|
prefix: "dx",
|
|
@@ -127,4 +142,18 @@ describe("isInitialized", () => {
|
|
|
127
142
|
});
|
|
128
143
|
expect(result).toBe(false);
|
|
129
144
|
});
|
|
145
|
+
test("returns false when resources exist but a required provider is not registered", async ({ cloudAccountService, }) => {
|
|
146
|
+
// Both resources exist
|
|
147
|
+
queryResources.mockResolvedValueOnce({ data: [], totalRecords: 1 });
|
|
148
|
+
queryResources.mockResolvedValueOnce({ data: [], totalRecords: 1 });
|
|
149
|
+
// One provider is not registered
|
|
150
|
+
mockProviderGet.mockResolvedValueOnce({
|
|
151
|
+
registrationState: "NotRegistered",
|
|
152
|
+
});
|
|
153
|
+
const result = await cloudAccountService.isInitialized("sub-1", {
|
|
154
|
+
name: "dev",
|
|
155
|
+
prefix: "dx",
|
|
156
|
+
});
|
|
157
|
+
expect(result).toBe(false);
|
|
158
|
+
});
|
|
130
159
|
});
|
|
@@ -33,6 +33,24 @@ const graphGroupMembershipResponseSchema = z.object({
|
|
|
33
33
|
});
|
|
34
34
|
export class AzureCloudAccountService {
|
|
35
35
|
#credential;
|
|
36
|
+
#requiredResourceProviders = [
|
|
37
|
+
"Microsoft.Advisor",
|
|
38
|
+
"Microsoft.AlertsManagement",
|
|
39
|
+
"Microsoft.ApiManagement",
|
|
40
|
+
"Microsoft.App",
|
|
41
|
+
"Microsoft.Authorization",
|
|
42
|
+
"Microsoft.AzureTerraform",
|
|
43
|
+
"Microsoft.Cache",
|
|
44
|
+
"Microsoft.Cdn",
|
|
45
|
+
"Microsoft.ContainerInstance",
|
|
46
|
+
"Microsoft.CostManagement",
|
|
47
|
+
"Microsoft.DBforPostgreSQL",
|
|
48
|
+
"Microsoft.KeyVault",
|
|
49
|
+
"Microsoft.ServiceBus",
|
|
50
|
+
"Microsoft.Sql",
|
|
51
|
+
"Microsoft.Storage",
|
|
52
|
+
"Microsoft.Web",
|
|
53
|
+
];
|
|
36
54
|
#resourceGraphClient;
|
|
37
55
|
constructor(credential) {
|
|
38
56
|
this.#resourceGraphClient = new ResourceGraphClient(credential);
|
|
@@ -126,6 +144,8 @@ export class AzureCloudAccountService {
|
|
|
126
144
|
assert.equal(cloudAccount.csp, "azure", "Cloud account must be Azure");
|
|
127
145
|
assert.ok(isAzureLocation(cloudAccount.defaultLocation), "The default location of the cloud account is not a valid Azure location");
|
|
128
146
|
const logger = getLogger(["gen", "env"]);
|
|
147
|
+
// Register required resource providers before creating any resources
|
|
148
|
+
await this.#registerProviders(cloudAccount.id);
|
|
129
149
|
const resourceManagementClient = new ResourceManagementClient(this.#credential, cloudAccount.id);
|
|
130
150
|
const short = {
|
|
131
151
|
env: environmentShort[name],
|
|
@@ -210,7 +230,7 @@ export class AzureCloudAccountService {
|
|
|
210
230
|
| where type == 'microsoft.keyvault/vaults'
|
|
211
231
|
| where name matches regex @'${keyVaultResourceName}'
|
|
212
232
|
`;
|
|
213
|
-
const [identityResult, keyVaultResult] = await Promise.all([
|
|
233
|
+
const [identityResult, keyVaultResult, areProvidersRegistered] = await Promise.all([
|
|
214
234
|
this.#resourceGraphClient.resources({
|
|
215
235
|
query: identityQuery,
|
|
216
236
|
subscriptions: [cloudAccountId],
|
|
@@ -219,8 +239,11 @@ export class AzureCloudAccountService {
|
|
|
219
239
|
query: keyVaultQuery,
|
|
220
240
|
subscriptions: [cloudAccountId],
|
|
221
241
|
}),
|
|
242
|
+
this.#areProvidersRegistered(cloudAccountId),
|
|
222
243
|
]);
|
|
223
|
-
const initialized = identityResult.totalRecords > 0 &&
|
|
244
|
+
const initialized = identityResult.totalRecords > 0 &&
|
|
245
|
+
keyVaultResult.totalRecords > 0 &&
|
|
246
|
+
areProvidersRegistered;
|
|
224
247
|
const logger = getLogger(["gen", "env"]);
|
|
225
248
|
logger.debug("subscription {subscriptionId} initialized: {initialized}", {
|
|
226
249
|
initialized,
|
|
@@ -282,6 +305,14 @@ export class AzureCloudAccountService {
|
|
|
282
305
|
type: "azurerm",
|
|
283
306
|
});
|
|
284
307
|
}
|
|
308
|
+
async #areProvidersRegistered(subscriptionId) {
|
|
309
|
+
const client = new ResourceManagementClient(this.#credential, subscriptionId);
|
|
310
|
+
const results = await Promise.all(this.#requiredResourceProviders.map(async (namespace) => {
|
|
311
|
+
const provider = await client.providers.get(namespace);
|
|
312
|
+
return provider.registrationState === "Registered";
|
|
313
|
+
}));
|
|
314
|
+
return results.every(Boolean);
|
|
315
|
+
}
|
|
285
316
|
async #getCurrentPrincipalIds() {
|
|
286
317
|
// Create Graph client with custom auth provider that fetches fresh tokens
|
|
287
318
|
const graphClient = Client.init({
|
|
@@ -318,4 +349,14 @@ export class AzureCloudAccountService {
|
|
|
318
349
|
const allPrincipalIds = new Set([userObjectId, ...groupIds]);
|
|
319
350
|
return allPrincipalIds;
|
|
320
351
|
}
|
|
352
|
+
async #registerProviders(subscriptionId) {
|
|
353
|
+
const logger = getLogger(["dx-cli", "register-providers"]);
|
|
354
|
+
const client = new ResourceManagementClient(this.#credential, subscriptionId);
|
|
355
|
+
logger.info("Registering {count} resource providers on subscription {subscriptionId}", { count: this.#requiredResourceProviders.length, subscriptionId });
|
|
356
|
+
await Promise.all(this.#requiredResourceProviders.map(async (namespace) => {
|
|
357
|
+
await client.providers.register(namespace);
|
|
358
|
+
logger.debug("Registered provider {namespace}", { namespace });
|
|
359
|
+
}));
|
|
360
|
+
logger.info("All resource providers registered on subscription {subscriptionId}", { subscriptionId });
|
|
361
|
+
}
|
|
321
362
|
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for authorizeCloudAccounts in the init command.
|
|
3
|
+
*/
|
|
4
|
+
import { errAsync, okAsync } from "neverthrow";
|
|
5
|
+
import { describe, expect, it } from "vitest";
|
|
6
|
+
import { mock } from "vitest-mock-extended";
|
|
7
|
+
import { AuthorizationError, AuthorizationResult, IdentityAlreadyExistsError, } from "../../../../domain/authorization.js";
|
|
8
|
+
import { authorizeCloudAccounts } from "../init.js";
|
|
9
|
+
const makeEnvPayload = (overrides = {}) => ({
|
|
10
|
+
env: {
|
|
11
|
+
cloudAccounts: [
|
|
12
|
+
{
|
|
13
|
+
csp: "azure",
|
|
14
|
+
defaultLocation: "italynorth",
|
|
15
|
+
displayName: "DEV-FooBar",
|
|
16
|
+
id: "sub-123",
|
|
17
|
+
},
|
|
18
|
+
],
|
|
19
|
+
name: "dev",
|
|
20
|
+
prefix: "dx",
|
|
21
|
+
},
|
|
22
|
+
github: { owner: "pagopa", repo: "test-repo" },
|
|
23
|
+
tags: { BusinessUnit: "BU", CostCenter: "TS000", ManagementTeam: "MT" },
|
|
24
|
+
workspace: { domain: "" },
|
|
25
|
+
...overrides,
|
|
26
|
+
});
|
|
27
|
+
describe("authorizeCloudAccounts", () => {
|
|
28
|
+
it("returns empty array when init is undefined (env already initialized)", async () => {
|
|
29
|
+
const authService = mock();
|
|
30
|
+
const envPayload = makeEnvPayload({ init: undefined });
|
|
31
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
32
|
+
expect(result.isOk()).toBe(true);
|
|
33
|
+
expect(result._unsafeUnwrap()).toEqual([]);
|
|
34
|
+
expect(authService.requestAuthorization).not.toHaveBeenCalled();
|
|
35
|
+
});
|
|
36
|
+
it("returns empty array when cloudAccountsToInitialize is empty", async () => {
|
|
37
|
+
const authService = mock();
|
|
38
|
+
const envPayload = makeEnvPayload({
|
|
39
|
+
init: { cloudAccountsToInitialize: [] },
|
|
40
|
+
});
|
|
41
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
42
|
+
expect(result.isOk()).toBe(true);
|
|
43
|
+
expect(result._unsafeUnwrap()).toEqual([]);
|
|
44
|
+
});
|
|
45
|
+
it("requests authorization for each initialized account", async () => {
|
|
46
|
+
const authService = mock();
|
|
47
|
+
const expectedPr = new AuthorizationResult("https://github.com/pagopa/eng-azure-authorization/pull/42");
|
|
48
|
+
authService.requestAuthorization.mockReturnValue(okAsync(expectedPr));
|
|
49
|
+
const account = {
|
|
50
|
+
csp: "azure",
|
|
51
|
+
defaultLocation: "italynorth",
|
|
52
|
+
displayName: "DEV-FooBar",
|
|
53
|
+
id: "sub-123",
|
|
54
|
+
};
|
|
55
|
+
const envPayload = makeEnvPayload({
|
|
56
|
+
env: {
|
|
57
|
+
cloudAccounts: [account],
|
|
58
|
+
name: "dev",
|
|
59
|
+
prefix: "dx",
|
|
60
|
+
},
|
|
61
|
+
init: { cloudAccountsToInitialize: [account] },
|
|
62
|
+
});
|
|
63
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
64
|
+
expect(result.isOk()).toBe(true);
|
|
65
|
+
expect(result._unsafeUnwrap()).toEqual([expectedPr]);
|
|
66
|
+
expect(authService.requestAuthorization).toHaveBeenCalledWith(expect.objectContaining({
|
|
67
|
+
bootstrapIdentityId: "dx-d-itn-bootstrap-id-01",
|
|
68
|
+
subscriptionName: "DEV-FooBar",
|
|
69
|
+
}));
|
|
70
|
+
});
|
|
71
|
+
it("computes correct identity for westeurope location", async () => {
|
|
72
|
+
const authService = mock();
|
|
73
|
+
authService.requestAuthorization.mockReturnValue(okAsync(new AuthorizationResult("https://example.com/pr/1")));
|
|
74
|
+
const account = {
|
|
75
|
+
csp: "azure",
|
|
76
|
+
defaultLocation: "westeurope",
|
|
77
|
+
displayName: "PROD-Bar",
|
|
78
|
+
id: "sub-456",
|
|
79
|
+
};
|
|
80
|
+
const envPayload = makeEnvPayload({
|
|
81
|
+
env: {
|
|
82
|
+
cloudAccounts: [account],
|
|
83
|
+
name: "prod",
|
|
84
|
+
prefix: "io",
|
|
85
|
+
},
|
|
86
|
+
init: { cloudAccountsToInitialize: [account] },
|
|
87
|
+
});
|
|
88
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
89
|
+
expect(result.isOk()).toBe(true);
|
|
90
|
+
expect(authService.requestAuthorization).toHaveBeenCalledWith(expect.objectContaining({
|
|
91
|
+
bootstrapIdentityId: "io-p-weu-bootstrap-id-01",
|
|
92
|
+
subscriptionName: "PROD-Bar",
|
|
93
|
+
}));
|
|
94
|
+
});
|
|
95
|
+
it("skips accounts with unsupported locations", async () => {
|
|
96
|
+
const authService = mock();
|
|
97
|
+
const account = {
|
|
98
|
+
csp: "azure",
|
|
99
|
+
defaultLocation: "eastus",
|
|
100
|
+
displayName: "DEV-Unsupported",
|
|
101
|
+
id: "sub-789",
|
|
102
|
+
};
|
|
103
|
+
const envPayload = makeEnvPayload({
|
|
104
|
+
init: { cloudAccountsToInitialize: [account] },
|
|
105
|
+
});
|
|
106
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
107
|
+
expect(result.isOk()).toBe(true);
|
|
108
|
+
expect(result._unsafeUnwrap()).toEqual([]);
|
|
109
|
+
expect(authService.requestAuthorization).not.toHaveBeenCalled();
|
|
110
|
+
});
|
|
111
|
+
it("continues when authorization fails for one account", async () => {
|
|
112
|
+
const authService = mock();
|
|
113
|
+
const account1 = {
|
|
114
|
+
csp: "azure",
|
|
115
|
+
defaultLocation: "italynorth",
|
|
116
|
+
displayName: "DEV-First",
|
|
117
|
+
id: "sub-1",
|
|
118
|
+
};
|
|
119
|
+
const account2 = {
|
|
120
|
+
csp: "azure",
|
|
121
|
+
defaultLocation: "italynorth",
|
|
122
|
+
displayName: "DEV-Second",
|
|
123
|
+
id: "sub-2",
|
|
124
|
+
};
|
|
125
|
+
const expectedPr = new AuthorizationResult("https://example.com/pr/2");
|
|
126
|
+
authService.requestAuthorization
|
|
127
|
+
.mockReturnValueOnce(errAsync(new AuthorizationError("Branch already exists")))
|
|
128
|
+
.mockReturnValueOnce(okAsync(expectedPr));
|
|
129
|
+
const envPayload = makeEnvPayload({
|
|
130
|
+
env: {
|
|
131
|
+
cloudAccounts: [account1, account2],
|
|
132
|
+
name: "dev",
|
|
133
|
+
prefix: "dx",
|
|
134
|
+
},
|
|
135
|
+
init: { cloudAccountsToInitialize: [account1, account2] },
|
|
136
|
+
});
|
|
137
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
138
|
+
expect(result.isOk()).toBe(true);
|
|
139
|
+
const prs = result._unsafeUnwrap();
|
|
140
|
+
expect(prs).toHaveLength(1);
|
|
141
|
+
expect(prs[0]).toEqual(expectedPr);
|
|
142
|
+
});
|
|
143
|
+
it("handles IdentityAlreadyExistsError gracefully", async () => {
|
|
144
|
+
const authService = mock();
|
|
145
|
+
const account = {
|
|
146
|
+
csp: "azure",
|
|
147
|
+
defaultLocation: "italynorth",
|
|
148
|
+
displayName: "DEV-Existing",
|
|
149
|
+
id: "sub-exists",
|
|
150
|
+
};
|
|
151
|
+
authService.requestAuthorization.mockReturnValue(errAsync(new IdentityAlreadyExistsError("dx-d-itn-bootstrap-id-01")));
|
|
152
|
+
const envPayload = makeEnvPayload({
|
|
153
|
+
init: { cloudAccountsToInitialize: [account] },
|
|
154
|
+
});
|
|
155
|
+
const result = await authorizeCloudAccounts(authService)(envPayload);
|
|
156
|
+
expect(result.isOk()).toBe(true);
|
|
157
|
+
expect(result._unsafeUnwrap()).toEqual([]);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import { ResultAsync } from "neverthrow";
|
|
3
|
+
import type { Payload as EnvironmentPayload } from "../../plop/generators/environment/index.js";
|
|
4
|
+
import { AuthorizationResult, AuthorizationService } from "../../../domain/authorization.js";
|
|
3
5
|
import { GitHubService } from "../../../domain/github.js";
|
|
4
6
|
export declare const checkPreconditions: () => ResultAsync<import("execa").Result<{
|
|
5
7
|
environment: {
|
|
@@ -9,8 +11,13 @@ export declare const checkPreconditions: () => ResultAsync<import("execa").Resul
|
|
|
9
11
|
};
|
|
10
12
|
shell: true;
|
|
11
13
|
}>, Error>;
|
|
14
|
+
/**
|
|
15
|
+
* Authorize a Cloud Account (Azure Subscription, AWS Account, ...), creating a Pull Request for each account that requires authorization.
|
|
16
|
+
*/
|
|
17
|
+
export declare const authorizeCloudAccounts: (authorizationService: AuthorizationService) => (envPayload: EnvironmentPayload) => ResultAsync<AuthorizationResult[], never>;
|
|
12
18
|
type InitCommandDependencies = {
|
|
19
|
+
authorizationService: AuthorizationService;
|
|
13
20
|
gitHubService: GitHubService;
|
|
14
21
|
};
|
|
15
|
-
export declare const makeInitCommand: ({ gitHubService, }: InitCommandDependencies) => Command;
|
|
22
|
+
export declare const makeInitCommand: ({ authorizationService, gitHubService, }: InitCommandDependencies) => Command;
|
|
16
23
|
export {};
|
|
@@ -6,7 +6,10 @@ import { okAsync, ResultAsync } from "neverthrow";
|
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import { oraPromise } from "ora";
|
|
8
8
|
import { z } from "zod";
|
|
9
|
+
import { requestAuthorizationInputSchema, } from "../../../domain/authorization.js";
|
|
10
|
+
import { environmentShort } from "../../../domain/environment.js";
|
|
9
11
|
import { Repository, } from "../../../domain/github.js";
|
|
12
|
+
import { isAzureLocation, locationShort } from "../../azure/locations.js";
|
|
10
13
|
import { tf$ } from "../../execa/terraform.js";
|
|
11
14
|
import { getPlopInstance, runDeploymentEnvironmentGenerator, runMonorepoGenerator, } from "../../plop/index.js";
|
|
12
15
|
import { exitWithError } from "../index.js";
|
|
@@ -16,7 +19,7 @@ const withSpinner = (text, successText, failText, promise) => ResultAsync.fromPr
|
|
|
16
19
|
text,
|
|
17
20
|
}), (cause) => new Error(failText, { cause }));
|
|
18
21
|
const displaySummary = (initResult) => {
|
|
19
|
-
const { pr, repository } = initResult;
|
|
22
|
+
const { authorizationPrs, pr, repository } = initResult;
|
|
20
23
|
console.log(chalk.green.bold("\nWorkspace created successfully!"));
|
|
21
24
|
if (repository) {
|
|
22
25
|
console.log(`- Name: ${chalk.cyan(repository.name)}`);
|
|
@@ -26,9 +29,16 @@ const displaySummary = (initResult) => {
|
|
|
26
29
|
console.log(chalk.yellow(`\n⚠️ GitHub repository may not have been created automatically.`));
|
|
27
30
|
}
|
|
28
31
|
if (pr) {
|
|
32
|
+
let step = 1;
|
|
29
33
|
console.log(chalk.green.bold("\nNext Steps:"));
|
|
30
|
-
console.log(
|
|
31
|
-
|
|
34
|
+
console.log(`${step++}. Review the Pull Request in the GitHub repository: ${chalk.underline(pr.url)}`);
|
|
35
|
+
if (authorizationPrs.length > 0) {
|
|
36
|
+
console.log(`${step++}. Review the Azure authorization Pull Request(s):`);
|
|
37
|
+
for (const authPr of authorizationPrs) {
|
|
38
|
+
console.log(` - ${chalk.underline(authPr.url)}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
console.log(`${step}. Visit ${chalk.underline("https://dx.pagopa.it/getting-started")} to deploy your first project\n`);
|
|
32
42
|
}
|
|
33
43
|
else {
|
|
34
44
|
console.log(chalk.yellow(`\n⚠️ There was an error during Pull Request creation.`));
|
|
@@ -113,7 +123,46 @@ const handleGeneratorError = (err) => {
|
|
|
113
123
|
}
|
|
114
124
|
return new Error("Failed to run the generator");
|
|
115
125
|
};
|
|
116
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Authorize a Cloud Account (Azure Subscription, AWS Account, ...), creating a Pull Request for each account that requires authorization.
|
|
128
|
+
*/
|
|
129
|
+
export const authorizeCloudAccounts = (authorizationService) => (envPayload) => {
|
|
130
|
+
const accountsToInitialize = envPayload.init?.cloudAccountsToInitialize ?? [];
|
|
131
|
+
if (accountsToInitialize.length === 0) {
|
|
132
|
+
return okAsync([]);
|
|
133
|
+
}
|
|
134
|
+
const logger = getLogger(["dx-cli", "init"]);
|
|
135
|
+
const { name, prefix } = envPayload.env;
|
|
136
|
+
const envShort = environmentShort[name];
|
|
137
|
+
const requestAll = async () => {
|
|
138
|
+
const results = [];
|
|
139
|
+
for (const account of accountsToInitialize) {
|
|
140
|
+
if (!isAzureLocation(account.defaultLocation)) {
|
|
141
|
+
logger.warn("Skipping authorization for {account}: unsupported location", { account: account.displayName });
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const locShort = locationShort[account.defaultLocation];
|
|
145
|
+
const input = requestAuthorizationInputSchema.safeParse({
|
|
146
|
+
bootstrapIdentityId: `${prefix}-${envShort}-${locShort}-bootstrap-id-01`,
|
|
147
|
+
subscriptionName: account.displayName,
|
|
148
|
+
});
|
|
149
|
+
if (!input.success) {
|
|
150
|
+
logger.warn("Skipping authorization for {account}: invalid input", {
|
|
151
|
+
account: account.displayName,
|
|
152
|
+
});
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const result = await authorizationService.requestAuthorization(input.data);
|
|
156
|
+
result.match((authResult) => results.push(authResult), (error) => logger.warn("Authorization request failed for {account}: {error}", {
|
|
157
|
+
account: account.displayName,
|
|
158
|
+
error: error.message,
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
return results;
|
|
162
|
+
};
|
|
163
|
+
return ResultAsync.fromPromise(requestAll(), () => []).orElse(() => okAsync([]));
|
|
164
|
+
};
|
|
165
|
+
export const makeInitCommand = ({ authorizationService, gitHubService, }) => new Command()
|
|
117
166
|
.name("init")
|
|
118
167
|
.description("Initialize a new DX workspace")
|
|
119
168
|
.action(async function () {
|
|
@@ -127,11 +176,11 @@ export const makeInitCommand = ({ gitHubService, }) => new Command()
|
|
|
127
176
|
process.chdir(payload.repoName);
|
|
128
177
|
console.log(chalk.blue.bold("\nCloud Environment"));
|
|
129
178
|
})
|
|
130
|
-
.andThen((
|
|
131
|
-
owner:
|
|
132
|
-
repo:
|
|
133
|
-
}), handleGeneratorError).map(() =>
|
|
179
|
+
.andThen((monorepoPayload) => ResultAsync.fromPromise(runDeploymentEnvironmentGenerator(plop, {
|
|
180
|
+
owner: monorepoPayload.repoOwner,
|
|
181
|
+
repo: monorepoPayload.repoName,
|
|
182
|
+
}), handleGeneratorError).map((envPayload) => ({ envPayload, monorepoPayload }))))
|
|
134
183
|
.andTee(() => console.log()) // Print a new line before the gh repo creation logs
|
|
135
|
-
.andThen((
|
|
184
|
+
.andThen(({ envPayload, monorepoPayload }) => handleNewGitHubRepository(gitHubService)(monorepoPayload).andThen((repoPr) => authorizeCloudAccounts(authorizationService)(envPayload).map((authorizationPrs) => ({ ...repoPr, authorizationPrs }))))
|
|
136
185
|
.match(displaySummary, exitWithError(this));
|
|
137
186
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { NodePlopAPI } from "plop";
|
|
2
2
|
import { GitHubRepo } from "../../domain/github-repo.js";
|
|
3
3
|
import { GitHubService } from "../../domain/github.js";
|
|
4
|
+
import { Payload as EnvironmentPayload } from "../plop/generators/environment/index.js";
|
|
4
5
|
import { Payload as MonorepoPayload } from "../plop/generators/monorepo/index.js";
|
|
5
6
|
export declare const setMonorepoGenerator: (plop: NodePlopAPI) => void;
|
|
6
7
|
export declare const getPlopInstance: () => Promise<NodePlopAPI>;
|
|
@@ -13,7 +14,7 @@ export declare const runMonorepoGenerator: (plop: NodePlopAPI, githubService: Gi
|
|
|
13
14
|
* uses the explicitly passed repository. When omitted (by add command),
|
|
14
15
|
* the generator infers it from the local git context.
|
|
15
16
|
*/
|
|
16
|
-
export declare const runDeploymentEnvironmentGenerator: (plop: NodePlopAPI, github?: GitHubRepo) => Promise<
|
|
17
|
+
export declare const runDeploymentEnvironmentGenerator: (plop: NodePlopAPI, github?: GitHubRepo) => Promise<EnvironmentPayload>;
|
|
17
18
|
/**
|
|
18
19
|
* Configure the deployment environment generator
|
|
19
20
|
*
|
|
@@ -7,7 +7,7 @@ import { oraPromise } from "ora";
|
|
|
7
7
|
import { RepositoryNotFoundError } from "../../domain/github.js";
|
|
8
8
|
import { AzureSubscriptionRepository } from "../azure/cloud-account-repository.js";
|
|
9
9
|
import { AzureCloudAccountService } from "../azure/cloud-account-service.js";
|
|
10
|
-
import createDeploymentEnvironmentGenerator, { PLOP_ENVIRONMENT_GENERATOR_NAME, } from "../plop/generators/environment/index.js";
|
|
10
|
+
import createDeploymentEnvironmentGenerator, { payloadSchema as environmentPayloadSchema, PLOP_ENVIRONMENT_GENERATOR_NAME, } from "../plop/generators/environment/index.js";
|
|
11
11
|
import createMonorepoGenerator, { payloadSchema as monorepoPayloadSchema, PLOP_MONOREPO_GENERATOR_NAME, } from "../plop/generators/monorepo/index.js";
|
|
12
12
|
export const setMonorepoGenerator = (plop) => {
|
|
13
13
|
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
|
|
@@ -65,12 +65,14 @@ export const runMonorepoGenerator = async (plop, githubService) => {
|
|
|
65
65
|
export const runDeploymentEnvironmentGenerator = async (plop, github) => {
|
|
66
66
|
setDeploymentEnvironmentGenerator(plop, github);
|
|
67
67
|
const generator = plop.getGenerator(PLOP_ENVIRONMENT_GENERATOR_NAME);
|
|
68
|
-
const
|
|
68
|
+
const answers = await generator.runPrompts();
|
|
69
|
+
const payload = environmentPayloadSchema.parse(answers);
|
|
69
70
|
await oraPromise(runActions(generator, payload), {
|
|
70
71
|
failText: "Failed to create deployment environment",
|
|
71
72
|
successText: "Environment created successfully!",
|
|
72
73
|
text: "Creating environment...",
|
|
73
74
|
});
|
|
75
|
+
return payload;
|
|
74
76
|
};
|
|
75
77
|
/**
|
|
76
78
|
* Configure the deployment environment generator
|
package/package.json
CHANGED
|
@@ -103,6 +103,7 @@ module "azure-{{displayName}}_bootstrap" {
|
|
|
103
103
|
key_vault = {
|
|
104
104
|
name = module.azure-{{displayName}}_core_values.common_key_vault.name
|
|
105
105
|
resource_group_name = module.azure-{{displayName}}_core_values.common_key_vault.resource_group_name
|
|
106
|
+
use_rbac = true
|
|
106
107
|
}
|
|
107
108
|
use_github_app = true
|
|
108
109
|
}
|
|
@@ -7,7 +7,7 @@ repos:
|
|
|
7
7
|
exclude: ^.*/(_modules|modules|\.terraform)(/.*)?$
|
|
8
8
|
files: infra/(resources/prod|repository)
|
|
9
9
|
- repo: https://github.com/antonbabenko/pre-commit-terraform
|
|
10
|
-
rev:
|
|
10
|
+
rev: v{{ preCommitTerraformVersion }}
|
|
11
11
|
hooks:
|
|
12
12
|
- id: terraform_tflint
|
|
13
13
|
args:
|