@goldstack/template-docker-image-aws 0.5.0 → 0.5.1

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.
@@ -1,40 +1,40 @@
1
- import ECS from 'aws-sdk/clients/ecs';
2
- import CloudWatchLogs from 'aws-sdk/clients/cloudwatchlogs';
3
- import { AWSDockerImageDeployment, AWSDockerImagePackage } from './types/AWSDockerImagePackage';
4
- import { DeploymentState } from '@goldstack/infra';
5
- interface GetLogsParams {
6
- taskId: string;
7
- deployment: AWSDockerImageDeployment;
8
- deploymentState: DeploymentState;
9
- config: AWSDockerImagePackage;
10
- limit?: number;
11
- nextToken?: string;
12
- startTime?: number;
13
- endTime?: number;
14
- }
15
- export declare const getLogs: (params: GetLogsParams) => Promise<CloudWatchLogs.OutputLogEvents>;
16
- interface EnvVarDefinition {
17
- name: string;
18
- value: string;
19
- }
20
- interface RunParams {
21
- cmd: string[];
22
- env?: EnvVarDefinition[];
23
- imageHash?: string;
24
- deployment: AWSDockerImageDeployment;
25
- config: AWSDockerImagePackage;
26
- deploymentState: DeploymentState;
27
- }
28
- export declare const getTaskStatus: (deployment: AWSDockerImageDeployment, taskExecutionArn: string) => Promise<ECS.Task>;
29
- export interface StartTaskResult {
30
- taskArn: string;
31
- taskId: string;
32
- awsLogsGroup: string;
33
- awsLogsConsoleLink: string;
34
- ecsConsoleLink: string;
35
- }
36
- export declare const startTask: (params: RunParams) => Promise<StartTaskResult>;
37
- export declare const runTask: (params: RunParams) => Promise<StartTaskResult>;
38
- export declare const apiDockerImageAwsCli: (config: AWSDockerImagePackage, deployment: AWSDockerImageDeployment, args: string[]) => Promise<void>;
39
- export {};
1
+ import ECS from 'aws-sdk/clients/ecs';
2
+ import CloudWatchLogs from 'aws-sdk/clients/cloudwatchlogs';
3
+ import { AWSDockerImageDeployment, AWSDockerImagePackage } from './types/AWSDockerImagePackage';
4
+ import { DeploymentState } from '@goldstack/infra';
5
+ interface GetLogsParams {
6
+ taskId: string;
7
+ deployment: AWSDockerImageDeployment;
8
+ deploymentState: DeploymentState;
9
+ config: AWSDockerImagePackage;
10
+ limit?: number;
11
+ nextToken?: string;
12
+ startTime?: number;
13
+ endTime?: number;
14
+ }
15
+ export declare const getLogs: (params: GetLogsParams) => Promise<CloudWatchLogs.OutputLogEvents>;
16
+ interface EnvVarDefinition {
17
+ name: string;
18
+ value: string;
19
+ }
20
+ interface RunParams {
21
+ cmd: string[];
22
+ env?: EnvVarDefinition[];
23
+ imageHash?: string;
24
+ deployment: AWSDockerImageDeployment;
25
+ config: AWSDockerImagePackage;
26
+ deploymentState: DeploymentState;
27
+ }
28
+ export declare const getTaskStatus: (deployment: AWSDockerImageDeployment, taskExecutionArn: string) => Promise<ECS.Task>;
29
+ export interface StartTaskResult {
30
+ taskArn: string;
31
+ taskId: string;
32
+ awsLogsGroup: string;
33
+ awsLogsConsoleLink: string;
34
+ ecsConsoleLink: string;
35
+ }
36
+ export declare const startTask: (params: RunParams) => Promise<StartTaskResult>;
37
+ export declare const runTask: (params: RunParams) => Promise<StartTaskResult>;
38
+ export declare const apiDockerImageAwsCli: (config: AWSDockerImagePackage, deployment: AWSDockerImageDeployment, args: string[]) => Promise<void>;
39
+ export {};
40
40
  //# sourceMappingURL=apiDockerImageAws.d.ts.map
@@ -1,283 +1,283 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.apiDockerImageAwsCli = exports.runTask = exports.startTask = exports.getTaskStatus = exports.getLogs = void 0;
7
- const ecs_1 = __importDefault(require("aws-sdk/clients/ecs"));
8
- const cloudwatchlogs_1 = __importDefault(require("aws-sdk/clients/cloudwatchlogs"));
9
- const assert_1 = __importDefault(require("assert"));
10
- const infra_aws_1 = require("@goldstack/infra-aws");
11
- const infra_1 = require("@goldstack/infra");
12
- const createECS = async (deployment) => {
13
- const awsUser = await (0, infra_aws_1.getAWSUser)(deployment.awsUser);
14
- return new ecs_1.default({
15
- apiVersion: '2014-11-13',
16
- credentials: awsUser,
17
- });
18
- };
19
- const createCloudWatchLogs = async (deployment) => {
20
- const awsUser = await (0, infra_aws_1.getAWSUser)(deployment.awsUser);
21
- return new cloudwatchlogs_1.default({
22
- credentials: awsUser,
23
- });
24
- };
25
- const getLogs = async (params) => {
26
- const ecs = await createECS(params.deployment);
27
- const deploymentState = params.deploymentState;
28
- const taskId = params.taskId;
29
- const tasks = await ecs
30
- .describeTasks({
31
- tasks: [taskId],
32
- cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
33
- })
34
- .promise();
35
- (0, assert_1.default)(tasks.tasks);
36
- const task = tasks.tasks[0];
37
- (0, assert_1.default)(task.taskDefinitionArn);
38
- const taskDefinitionResponse = await ecs
39
- .describeTaskDefinition({
40
- taskDefinition: task.taskDefinitionArn.split('/')[1],
41
- })
42
- .promise();
43
- const taskDefinition = taskDefinitionResponse.taskDefinition;
44
- (0, assert_1.default)(taskDefinition);
45
- const containerDefinitions = taskDefinition.containerDefinitions;
46
- (0, assert_1.default)(containerDefinitions);
47
- const logConfiguration = containerDefinitions[0].logConfiguration;
48
- (0, assert_1.default)(logConfiguration);
49
- (0, assert_1.default)(logConfiguration.options);
50
- const awsLogsGroup = logConfiguration.options['awslogs-group'];
51
- const awsLogsPrefix = logConfiguration.options['awslogs-stream-prefix'];
52
- const cwlogs = await createCloudWatchLogs(params.deployment);
53
- const logEvents = await cwlogs
54
- .getLogEvents({
55
- logGroupName: awsLogsGroup,
56
- logStreamName: `${awsLogsPrefix}/main/${taskId}`,
57
- limit: params.limit,
58
- nextToken: params.nextToken,
59
- startTime: params.startTime,
60
- endTime: params.endTime,
61
- })
62
- .promise();
63
- return logEvents.events || [];
64
- };
65
- exports.getLogs = getLogs;
66
- const getTaskStatus = async (deployment, taskExecutionArn) => {
67
- const ecs = await createECS(deployment);
68
- const tasksState = await ecs
69
- .describeTasks({ tasks: [taskExecutionArn] })
70
- .promise();
71
- if (tasksState.failures && tasksState.failures.length > 0) {
72
- throw new Error(`Cannot determine state of launched tast. ${tasksState.failures[0].reason}`);
73
- }
74
- (0, assert_1.default)(tasksState.tasks);
75
- return tasksState.tasks[0];
76
- };
77
- exports.getTaskStatus = getTaskStatus;
78
- const startTask = async (params) => {
79
- const deployment = params.deployment;
80
- const ecs = await createECS(params.deployment);
81
- const config = params.config;
82
- const deploymentState = params.deploymentState;
83
- if (!deploymentState) {
84
- throw new Error(`Deployment state for '${params.deployment.name}' is not defined. Make sure to have deployed the image to this environment.`);
85
- }
86
- const repo = (0, infra_1.readTerraformStateVariable)(deploymentState, 'repo_url');
87
- let imageName;
88
- let imageHash = params.imageHash;
89
- if (!params.imageHash) {
90
- if (!deploymentState['latest']) {
91
- throw new Error(`Cannot run image since image has not been deployed for deployment '${params.deployment.name}'.`);
92
- }
93
- imageName = deploymentState['latest'];
94
- imageHash = deploymentState['latest'].split(':')[1];
95
- }
96
- else {
97
- imageName = `${repo}:${imageHash}`;
98
- }
99
- const awsLogsGroup = '/ecs/' + repo + '/' + imageHash;
100
- const taskDefinition = (await ecs
101
- .registerTaskDefinition({
102
- containerDefinitions: [
103
- {
104
- name: 'main',
105
- command: params.cmd,
106
- environment: params.env,
107
- image: imageName,
108
- logConfiguration: {
109
- logDriver: 'awslogs',
110
- options: {
111
- 'awslogs-create-group': 'true',
112
- 'awslogs-region': deployment.awsRegion,
113
- 'awslogs-group': awsLogsGroup,
114
- 'awslogs-stream-prefix': 'ecs',
115
- },
116
- },
117
- },
118
- ],
119
- taskRoleArn: (0, infra_1.readTerraformStateVariable)(deploymentState, 'ecs_task_role_arn'),
120
- networkMode: 'awsvpc',
121
- cpu: '1 vcpu',
122
- memory: '4 GB',
123
- executionRoleArn: (0, infra_1.readTerraformStateVariable)(deploymentState, 'ecs_task_execution_role_arn'),
124
- requiresCompatibilities: ['FARGATE'],
125
- family: `temp-${config.configuration.imageTag}-${new Date().getTime()}-${imageHash}`,
126
- })
127
- .promise()).taskDefinition;
128
- (0, assert_1.default)(taskDefinition);
129
- const clusterName = (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name');
130
- const runTaskResponse = await ecs
131
- .runTask({
132
- cluster: clusterName,
133
- count: 1,
134
- launchType: 'FARGATE',
135
- networkConfiguration: {
136
- awsvpcConfiguration: {
137
- subnets: [(0, infra_1.readTerraformStateVariable)(deploymentState, 'subnet')],
138
- assignPublicIp: 'ENABLED',
139
- securityGroups: [
140
- (0, infra_1.readTerraformStateVariable)(deploymentState, 'container_security_group'),
141
- ],
142
- },
143
- },
144
- taskDefinition: `${taskDefinition.family}:${taskDefinition.revision}`,
145
- // command does not need to overriden here since it is defined in the task definition
146
- overrides: {},
147
- })
148
- .promise();
149
- const tasks = runTaskResponse.tasks;
150
- if (!tasks) {
151
- throw new Error(`Task definitions not supplied after running define tasks for ${imageName}`);
152
- }
153
- const taskExecution = tasks[0];
154
- (0, assert_1.default)(taskExecution.taskArn);
155
- const taskId = taskExecution.taskArn.split('/')[1];
156
- const cloudWatchLink = `https://${deployment.awsRegion}.console.aws.amazon.com/cloudwatch/home?region=${deployment.awsRegion}#logsV2:log-groups/log-group/${awsLogsGroup.replace(/\//g, '$252F')}/log-events/${`ecs/main/${taskExecution.taskArn.split('/')[2]}`
157
- .replace('$', '$2524')
158
- .replace('[', '$255B')
159
- .replace(']', '$255D')
160
- .replace(/\//g, '$252F')}`;
161
- const ecsConsoleLink = `https://${deployment.awsRegion}.console.aws.amazon.com/ecs/home?region=${deployment.awsRegion}#/clusters/${clusterName}/tasks/${taskExecution.taskArn.split('/')[2]}/details`;
162
- return {
163
- taskArn: taskExecution.taskArn,
164
- taskId,
165
- awsLogsGroup,
166
- ecsConsoleLink,
167
- awsLogsConsoleLink: cloudWatchLink,
168
- };
169
- };
170
- exports.startTask = startTask;
171
- const runTask = async (params) => {
172
- var _a, _b;
173
- const deployment = params.deployment;
174
- const ecs = await createECS(deployment);
175
- const result = await (0, exports.startTask)(params);
176
- const taskId = result.taskArn.split('/')[1];
177
- console.log(`Started task ${result.taskArn}`);
178
- const deploymentState = params.deploymentState;
179
- let tasks = await ecs
180
- .describeTasks({
181
- tasks: [taskId],
182
- cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
183
- })
184
- .promise();
185
- (0, assert_1.default)(tasks.tasks);
186
- let task = tasks.tasks[0];
187
- console.log(`Task status: ${task.lastStatus}`);
188
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
- const waitForStateRunning = 'tasksRunning';
190
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
191
- const waitForParams = {
192
- tasks: [taskId],
193
- cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
194
- };
195
- await ecs.waitFor(waitForStateRunning, waitForParams).promise();
196
- console.log('Task started up successfully ...');
197
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
198
- const waitForStateStopped = 'tasksStopped';
199
- await ecs.waitFor(waitForStateStopped, waitForParams).promise();
200
- console.log('Task stopped on ECS.');
201
- tasks = await ecs
202
- .describeTasks({
203
- tasks: [taskId],
204
- cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
205
- })
206
- .promise();
207
- (0, assert_1.default)(tasks.tasks);
208
- task = tasks.tasks[0];
209
- const taskDefinition = {
210
- family: (_a = task.taskDefinitionArn) === null || _a === void 0 ? void 0 : _a.split('/')[1].split(':')[0],
211
- revision: (_b = task.taskDefinitionArn) === null || _b === void 0 ? void 0 : _b.split('/')[1].split(':')[1],
212
- };
213
- const logEvents = await (0, exports.getLogs)({
214
- deployment,
215
- taskId,
216
- deploymentState,
217
- config: params.config,
218
- });
219
- console.log('Logs from container:');
220
- for (const event of logEvents) {
221
- console.log(`> ${event.timestamp} ${event.message}`);
222
- }
223
- await ecs
224
- .deregisterTaskDefinition({
225
- taskDefinition: `${taskDefinition.family}:${taskDefinition.revision}`,
226
- })
227
- .promise();
228
- (0, assert_1.default)(task.containers);
229
- const taskContainer = task.containers[0];
230
- const exitCode = taskContainer.exitCode;
231
- console.log(`Container exited with code ${exitCode}`);
232
- if (exitCode !== 0) {
233
- throw new Error(`Error running container: ${taskContainer.reason}`);
234
- }
235
- return result;
236
- };
237
- exports.runTask = runTask;
238
- const apiDockerImageAwsCli = async (config, deployment, args) => {
239
- if (args.length < 1) {
240
- throw new Error('Please specify an operation along with the image command. Supported operations ["run"]');
241
- }
242
- const [, deploymentName] = args;
243
- const deploymentState = (0, infra_1.readDeploymentState)('./', deploymentName);
244
- const operation = args[0];
245
- if (operation === 'run') {
246
- const [, , ...remainingArgs] = args;
247
- const taskArn = await (0, exports.runTask)({
248
- cmd: remainingArgs,
249
- deployment,
250
- deploymentState,
251
- config,
252
- });
253
- console.log(taskArn);
254
- return;
255
- }
256
- if (operation === 'start') {
257
- const [, , ...remainingArgs] = args;
258
- const taskArn = await (0, exports.startTask)({
259
- cmd: remainingArgs,
260
- deployment,
261
- deploymentState,
262
- config,
263
- });
264
- console.log(taskArn);
265
- return;
266
- }
267
- if (operation === 'logs') {
268
- const [, , taskArn] = args;
269
- const logEvents = await (0, exports.getLogs)({
270
- deployment,
271
- taskId: taskArn.split('/')[1],
272
- deploymentState,
273
- config,
274
- });
275
- for (const event of logEvents) {
276
- console.log(`${event.timestamp} ${event.message}`);
277
- }
278
- return;
279
- }
280
- throw new Error(`Unknown operation for image command: ${operation}`);
281
- };
282
- exports.apiDockerImageAwsCli = apiDockerImageAwsCli;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.apiDockerImageAwsCli = exports.runTask = exports.startTask = exports.getTaskStatus = exports.getLogs = void 0;
7
+ const ecs_1 = __importDefault(require("aws-sdk/clients/ecs"));
8
+ const cloudwatchlogs_1 = __importDefault(require("aws-sdk/clients/cloudwatchlogs"));
9
+ const assert_1 = __importDefault(require("assert"));
10
+ const infra_aws_1 = require("@goldstack/infra-aws");
11
+ const infra_1 = require("@goldstack/infra");
12
+ const createECS = async (deployment) => {
13
+ const awsUser = await (0, infra_aws_1.getAWSUser)(deployment.awsUser);
14
+ return new ecs_1.default({
15
+ apiVersion: '2014-11-13',
16
+ credentials: awsUser,
17
+ });
18
+ };
19
+ const createCloudWatchLogs = async (deployment) => {
20
+ const awsUser = await (0, infra_aws_1.getAWSUser)(deployment.awsUser);
21
+ return new cloudwatchlogs_1.default({
22
+ credentials: awsUser,
23
+ });
24
+ };
25
+ const getLogs = async (params) => {
26
+ const ecs = await createECS(params.deployment);
27
+ const deploymentState = params.deploymentState;
28
+ const taskId = params.taskId;
29
+ const tasks = await ecs
30
+ .describeTasks({
31
+ tasks: [taskId],
32
+ cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
33
+ })
34
+ .promise();
35
+ (0, assert_1.default)(tasks.tasks);
36
+ const task = tasks.tasks[0];
37
+ (0, assert_1.default)(task.taskDefinitionArn);
38
+ const taskDefinitionResponse = await ecs
39
+ .describeTaskDefinition({
40
+ taskDefinition: task.taskDefinitionArn.split('/')[1],
41
+ })
42
+ .promise();
43
+ const taskDefinition = taskDefinitionResponse.taskDefinition;
44
+ (0, assert_1.default)(taskDefinition);
45
+ const containerDefinitions = taskDefinition.containerDefinitions;
46
+ (0, assert_1.default)(containerDefinitions);
47
+ const logConfiguration = containerDefinitions[0].logConfiguration;
48
+ (0, assert_1.default)(logConfiguration);
49
+ (0, assert_1.default)(logConfiguration.options);
50
+ const awsLogsGroup = logConfiguration.options['awslogs-group'];
51
+ const awsLogsPrefix = logConfiguration.options['awslogs-stream-prefix'];
52
+ const cwlogs = await createCloudWatchLogs(params.deployment);
53
+ const logEvents = await cwlogs
54
+ .getLogEvents({
55
+ logGroupName: awsLogsGroup,
56
+ logStreamName: `${awsLogsPrefix}/main/${taskId}`,
57
+ limit: params.limit,
58
+ nextToken: params.nextToken,
59
+ startTime: params.startTime,
60
+ endTime: params.endTime,
61
+ })
62
+ .promise();
63
+ return logEvents.events || [];
64
+ };
65
+ exports.getLogs = getLogs;
66
+ const getTaskStatus = async (deployment, taskExecutionArn) => {
67
+ const ecs = await createECS(deployment);
68
+ const tasksState = await ecs
69
+ .describeTasks({ tasks: [taskExecutionArn] })
70
+ .promise();
71
+ if (tasksState.failures && tasksState.failures.length > 0) {
72
+ throw new Error(`Cannot determine state of launched tast. ${tasksState.failures[0].reason}`);
73
+ }
74
+ (0, assert_1.default)(tasksState.tasks);
75
+ return tasksState.tasks[0];
76
+ };
77
+ exports.getTaskStatus = getTaskStatus;
78
+ const startTask = async (params) => {
79
+ const deployment = params.deployment;
80
+ const ecs = await createECS(params.deployment);
81
+ const config = params.config;
82
+ const deploymentState = params.deploymentState;
83
+ if (!deploymentState) {
84
+ throw new Error(`Deployment state for '${params.deployment.name}' is not defined. Make sure to have deployed the image to this environment.`);
85
+ }
86
+ const repo = (0, infra_1.readTerraformStateVariable)(deploymentState, 'repo_url');
87
+ let imageName;
88
+ let imageHash = params.imageHash;
89
+ if (!params.imageHash) {
90
+ if (!deploymentState['latest']) {
91
+ throw new Error(`Cannot run image since image has not been deployed for deployment '${params.deployment.name}'.`);
92
+ }
93
+ imageName = deploymentState['latest'];
94
+ imageHash = deploymentState['latest'].split(':')[1];
95
+ }
96
+ else {
97
+ imageName = `${repo}:${imageHash}`;
98
+ }
99
+ const awsLogsGroup = '/ecs/' + repo + '/' + imageHash;
100
+ const taskDefinition = (await ecs
101
+ .registerTaskDefinition({
102
+ containerDefinitions: [
103
+ {
104
+ name: 'main',
105
+ command: params.cmd,
106
+ environment: params.env,
107
+ image: imageName,
108
+ logConfiguration: {
109
+ logDriver: 'awslogs',
110
+ options: {
111
+ 'awslogs-create-group': 'true',
112
+ 'awslogs-region': deployment.awsRegion,
113
+ 'awslogs-group': awsLogsGroup,
114
+ 'awslogs-stream-prefix': 'ecs',
115
+ },
116
+ },
117
+ },
118
+ ],
119
+ taskRoleArn: (0, infra_1.readTerraformStateVariable)(deploymentState, 'ecs_task_role_arn'),
120
+ networkMode: 'awsvpc',
121
+ cpu: '1 vcpu',
122
+ memory: '4 GB',
123
+ executionRoleArn: (0, infra_1.readTerraformStateVariable)(deploymentState, 'ecs_task_execution_role_arn'),
124
+ requiresCompatibilities: ['FARGATE'],
125
+ family: `temp-${config.configuration.imageTag}-${new Date().getTime()}-${imageHash}`,
126
+ })
127
+ .promise()).taskDefinition;
128
+ (0, assert_1.default)(taskDefinition);
129
+ const clusterName = (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name');
130
+ const runTaskResponse = await ecs
131
+ .runTask({
132
+ cluster: clusterName,
133
+ count: 1,
134
+ launchType: 'FARGATE',
135
+ networkConfiguration: {
136
+ awsvpcConfiguration: {
137
+ subnets: [(0, infra_1.readTerraformStateVariable)(deploymentState, 'subnet')],
138
+ assignPublicIp: 'ENABLED',
139
+ securityGroups: [
140
+ (0, infra_1.readTerraformStateVariable)(deploymentState, 'container_security_group'),
141
+ ],
142
+ },
143
+ },
144
+ taskDefinition: `${taskDefinition.family}:${taskDefinition.revision}`,
145
+ // command does not need to overriden here since it is defined in the task definition
146
+ overrides: {},
147
+ })
148
+ .promise();
149
+ const tasks = runTaskResponse.tasks;
150
+ if (!tasks) {
151
+ throw new Error(`Task definitions not supplied after running define tasks for ${imageName}`);
152
+ }
153
+ const taskExecution = tasks[0];
154
+ (0, assert_1.default)(taskExecution.taskArn);
155
+ const taskId = taskExecution.taskArn.split('/')[1];
156
+ const cloudWatchLink = `https://${deployment.awsRegion}.console.aws.amazon.com/cloudwatch/home?region=${deployment.awsRegion}#logsV2:log-groups/log-group/${awsLogsGroup.replace(/\//g, '$252F')}/log-events/${`ecs/main/${taskExecution.taskArn.split('/')[2]}`
157
+ .replace('$', '$2524')
158
+ .replace('[', '$255B')
159
+ .replace(']', '$255D')
160
+ .replace(/\//g, '$252F')}`;
161
+ const ecsConsoleLink = `https://${deployment.awsRegion}.console.aws.amazon.com/ecs/home?region=${deployment.awsRegion}#/clusters/${clusterName}/tasks/${taskExecution.taskArn.split('/')[2]}/details`;
162
+ return {
163
+ taskArn: taskExecution.taskArn,
164
+ taskId,
165
+ awsLogsGroup,
166
+ ecsConsoleLink,
167
+ awsLogsConsoleLink: cloudWatchLink,
168
+ };
169
+ };
170
+ exports.startTask = startTask;
171
+ const runTask = async (params) => {
172
+ var _a, _b;
173
+ const deployment = params.deployment;
174
+ const ecs = await createECS(deployment);
175
+ const result = await (0, exports.startTask)(params);
176
+ const taskId = result.taskArn.split('/')[1];
177
+ console.log(`Started task ${result.taskArn}`);
178
+ const deploymentState = params.deploymentState;
179
+ let tasks = await ecs
180
+ .describeTasks({
181
+ tasks: [taskId],
182
+ cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
183
+ })
184
+ .promise();
185
+ (0, assert_1.default)(tasks.tasks);
186
+ let task = tasks.tasks[0];
187
+ console.log(`Task status: ${task.lastStatus}`);
188
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
189
+ const waitForStateRunning = 'tasksRunning';
190
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
191
+ const waitForParams = {
192
+ tasks: [taskId],
193
+ cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
194
+ };
195
+ await ecs.waitFor(waitForStateRunning, waitForParams).promise();
196
+ console.log('Task started up successfully ...');
197
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
198
+ const waitForStateStopped = 'tasksStopped';
199
+ await ecs.waitFor(waitForStateStopped, waitForParams).promise();
200
+ console.log('Task stopped on ECS.');
201
+ tasks = await ecs
202
+ .describeTasks({
203
+ tasks: [taskId],
204
+ cluster: (0, infra_1.readTerraformStateVariable)(deploymentState, 'cluster_name'),
205
+ })
206
+ .promise();
207
+ (0, assert_1.default)(tasks.tasks);
208
+ task = tasks.tasks[0];
209
+ const taskDefinition = {
210
+ family: (_a = task.taskDefinitionArn) === null || _a === void 0 ? void 0 : _a.split('/')[1].split(':')[0],
211
+ revision: (_b = task.taskDefinitionArn) === null || _b === void 0 ? void 0 : _b.split('/')[1].split(':')[1],
212
+ };
213
+ const logEvents = await (0, exports.getLogs)({
214
+ deployment,
215
+ taskId,
216
+ deploymentState,
217
+ config: params.config,
218
+ });
219
+ console.log('Logs from container:');
220
+ for (const event of logEvents) {
221
+ console.log(`> ${event.timestamp} ${event.message}`);
222
+ }
223
+ await ecs
224
+ .deregisterTaskDefinition({
225
+ taskDefinition: `${taskDefinition.family}:${taskDefinition.revision}`,
226
+ })
227
+ .promise();
228
+ (0, assert_1.default)(task.containers);
229
+ const taskContainer = task.containers[0];
230
+ const exitCode = taskContainer.exitCode;
231
+ console.log(`Container exited with code ${exitCode}`);
232
+ if (exitCode !== 0) {
233
+ throw new Error(`Error running container: ${taskContainer.reason}`);
234
+ }
235
+ return result;
236
+ };
237
+ exports.runTask = runTask;
238
+ const apiDockerImageAwsCli = async (config, deployment, args) => {
239
+ if (args.length < 1) {
240
+ throw new Error('Please specify an operation along with the image command. Supported operations ["run"]');
241
+ }
242
+ const [, deploymentName] = args;
243
+ const deploymentState = (0, infra_1.readDeploymentState)('./', deploymentName);
244
+ const operation = args[0];
245
+ if (operation === 'run') {
246
+ const [, , ...remainingArgs] = args;
247
+ const taskArn = await (0, exports.runTask)({
248
+ cmd: remainingArgs,
249
+ deployment,
250
+ deploymentState,
251
+ config,
252
+ });
253
+ console.log(taskArn);
254
+ return;
255
+ }
256
+ if (operation === 'start') {
257
+ const [, , ...remainingArgs] = args;
258
+ const taskArn = await (0, exports.startTask)({
259
+ cmd: remainingArgs,
260
+ deployment,
261
+ deploymentState,
262
+ config,
263
+ });
264
+ console.log(taskArn);
265
+ return;
266
+ }
267
+ if (operation === 'logs') {
268
+ const [, , taskArn] = args;
269
+ const logEvents = await (0, exports.getLogs)({
270
+ deployment,
271
+ taskId: taskArn.split('/')[1],
272
+ deploymentState,
273
+ config,
274
+ });
275
+ for (const event of logEvents) {
276
+ console.log(`${event.timestamp} ${event.message}`);
277
+ }
278
+ return;
279
+ }
280
+ throw new Error(`Unknown operation for image command: ${operation}`);
281
+ };
282
+ exports.apiDockerImageAwsCli = apiDockerImageAwsCli;
283
283
  //# sourceMappingURL=apiDockerImageAws.js.map