Skip to content

Commit

Permalink
feat(custom-resource): migrate AWS SDK for JavaScript v2 APIs to v3
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed May 24, 2024
1 parent 9375a0a commit 547d614
Showing 1 changed file with 33 additions and 20 deletions.
53 changes: 33 additions & 20 deletions source/custom-resource/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import EC2, { DescribeRegionsRequest } from "aws-sdk/clients/ec2";
import S3, { CreateBucketRequest, PutBucketEncryptionRequest, PutBucketPolicyRequest } from "aws-sdk/clients/s3";
import SecretsManager from "aws-sdk/clients/secretsmanager";
import EC2 from "aws-sdk/clients/ec2";
import { DescribeRegionsCommandInput, EC2 } from "@aws-sdk/client-ec2";

import {
CreateBucketCommandInput,
PutBucketEncryptionCommandInput,
PutBucketPolicyCommandInput,
S3,
} from "@aws-sdk/client-s3";

import { SecretsManager } from "@aws-sdk/client-secrets-manager";
import S3 from "aws-sdk/clients/s3";
import axios, { RawAxiosRequestConfig, AxiosResponse } from "axios";
import { createHash } from "crypto";
import moment from "moment";
Expand Down Expand Up @@ -345,12 +354,12 @@ async function putConfigFile(
try {
console.info(`Putting ${DestS3key}... Try count: ${retry}`);

await s3Client.putObject(params).promise();
await s3Client.putObject(params);

console.info(`Putting ${DestS3key} completed.`);
break;
} catch (error) {
if (retry === RETRY_COUNT || error.code !== ErrorCodes.ACCESS_DENIED) {
if (retry === RETRY_COUNT || error.name !== ErrorCodes.ACCESS_DENIED) {
console.info(`Error occurred while putting ${DestS3key} into ${DestS3Bucket} bucket.`, error);
throw new CustomResourceError(
"ConfigFileCreationFailure",
Expand Down Expand Up @@ -392,12 +401,12 @@ async function copyS3Assets(
Bucket: SourceS3Bucket,
Key: ManifestKey,
};
const response = await s3Client.getObject(getParams).promise();
const response = await s3Client.getObject(getParams);
manifest = JSON.parse(response.Body.toString());

break;
} catch (error) {
if (retry === RETRY_COUNT || error.code !== ErrorCodes.ACCESS_DENIED) {
if (retry === RETRY_COUNT || error.name !== ErrorCodes.ACCESS_DENIED) {
console.error("Error occurred while getting manifest file.");
console.error(error);

Expand All @@ -422,7 +431,7 @@ async function copyS3Assets(
};

console.debug(`Copying ${fileName} to ${DestS3Bucket}`);
return s3Client.copyObject(copyObjectParams).promise();
return s3Client.copyObject(copyObjectParams);
})
);

Expand Down Expand Up @@ -463,7 +472,7 @@ async function validateBuckets(requestProperties: CheckSourceBucketsRequestPrope
for (const bucket of checkBuckets) {
const params = { Bucket: bucket };
try {
await s3Client.headBucket(params).promise();
await s3Client.headBucket(params);

console.info(`Found bucket: ${bucket}`);
} catch (error) {
Expand Down Expand Up @@ -507,7 +516,7 @@ async function checkSecretsManager(

for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
const response = await secretsManager.getSecretValue({ SecretId: SecretsManagerName }).promise();
const response = await secretsManager.getSecretValue({ SecretId: SecretsManagerName });
const secretString = JSON.parse(response.SecretString);

if (!Object.prototype.hasOwnProperty.call(secretString, SecretsManagerKey)) {
Expand Down Expand Up @@ -562,10 +571,10 @@ async function checkFallbackImage(

for (let retry = 1; retry <= RETRY_COUNT; retry++) {
try {
data = await s3Client.headObject({ Bucket: FallbackImageS3Bucket, Key: FallbackImageS3Key }).promise();
data = await s3Client.headObject({ Bucket: FallbackImageS3Bucket, Key: FallbackImageS3Key });
break;
} catch (error) {
if (retry === RETRY_COUNT || ![ErrorCodes.ACCESS_DENIED, ErrorCodes.FORBIDDEN].includes(error.code)) {
if (retry === RETRY_COUNT || ![ErrorCodes.ACCESS_DENIED, ErrorCodes.FORBIDDEN].includes(error.name)) {
console.error(
`Either the object does not exist or you don't have permission to access the object: ${FallbackImageS3Bucket}/${FallbackImageS3Key}`
);
Expand Down Expand Up @@ -611,16 +620,20 @@ async function createCloudFrontLoggingBucket(requestProperties: CreateLoggingBuc
try {
const s3Client = new S3({
...awsSdkOptions,

// The key apiVersion is no longer supported in v3, and can be removed.
// @deprecated The client uses the "latest" apiVersion.
apiVersion: "2006-03-01",

region: targetRegion,
});

const createBucketRequestParams: CreateBucketRequest = {
const createBucketRequestParams: CreateBucketCommandInput = {
Bucket: bucketName,
ACL: "log-delivery-write",
ObjectOwnership: "ObjectWriter",
};
await s3Client.createBucket(createBucketRequestParams).promise();
await s3Client.createBucket(createBucketRequestParams);

console.info(`Successfully created bucket '${bucketName}' in '${targetRegion}' region`);
} catch (error) {
Expand All @@ -633,14 +646,14 @@ async function createCloudFrontLoggingBucket(requestProperties: CreateLoggingBuc
// add encryption to bucket
console.info("Adding Encryption...");
try {
const putBucketEncryptionRequestParams: PutBucketEncryptionRequest = {
const putBucketEncryptionRequestParams: PutBucketEncryptionCommandInput = {
Bucket: bucketName,
ServerSideEncryptionConfiguration: {
Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }],
},
};

await s3Client.putBucketEncryption(putBucketEncryptionRequestParams).promise();
await s3Client.putBucketEncryption(putBucketEncryptionRequestParams);

console.info(`Successfully enabled encryption on bucket '${bucketName}'`);
} catch (error) {
Expand All @@ -666,12 +679,12 @@ async function createCloudFrontLoggingBucket(requestProperties: CreateLoggingBuc
Version: "2012-10-17",
Statement: [bucketPolicyStatement],
};
const putBucketPolicyRequestParams: PutBucketPolicyRequest = {
const putBucketPolicyRequestParams: PutBucketPolicyCommandInput = {
Bucket: bucketName,
Policy: JSON.stringify(bucketPolicy),
};

await s3Client.putBucketPolicy(putBucketPolicyRequestParams).promise();
await s3Client.putBucketPolicy(putBucketPolicyRequestParams);

console.info(`Successfully added policy added to bucket '${bucketName}'`);
} catch (error) {
Expand All @@ -690,11 +703,11 @@ async function createCloudFrontLoggingBucket(requestProperties: CreateLoggingBuc
* @returns The result of check.
*/
async function checkRegionOptInStatus(region: string): Promise<boolean> {
const describeRegionsRequestParams: DescribeRegionsRequest = {
const describeRegionsRequestParams: DescribeRegionsCommandInput = {
RegionNames: [region],
Filters: [{ Name: "opt-in-status", Values: ["opted-in"] }],
};
const describeRegionsResponse = await ec2Client.describeRegions(describeRegionsRequestParams).promise();
const describeRegionsResponse = await ec2Client.describeRegions(describeRegionsRequestParams);

return describeRegionsResponse.Regions.length > 0;
}

0 comments on commit 547d614

Please sign in to comment.