How to get AWS security keys from EKS POD in NodeJS

How to get AWS security keys from EKS POD in NodeJS Hrtsachdeva Just now·2 min read

Sometimes, security is one of the major concern of an application, so rather than passing the AWS credentials directly in the code from .env file we have have them configured on EKS PODs and fetch them directly from the POD itself whenever required.

This will not only help us to secure the credentials but also allow us to change the credentials with time without changing anything in our code

Steps to be implemented in AWS

Prerequisites

->Your application should be deployed on EKS.

->Here, we are using S3 for demonstration purposes

Please refer to the below link

https://levelup.gitconnected.com/using-iam-roles-to-allow-the-pods-in-aws-eks-to-read-the-aws-s3-bucket-be493fbdda84

Steps to be implemented in NodeJS

Step 1

npm i @aws-sdk/client-sts

Step 2

import the following into your service

import * as fs from ‘fs’; import { promisify } from ‘util’; import {STSClient,AssumeRoleWithWebIdentityCommand,} from ‘@aws-sdk/client-sts’; import type { Credentials } from ‘@aws-sdk/types’;

Step 3

Add the following code

const readAsync = promisify(fs.readFile);

const client = new STSClient({region: process.env.AWS_REGION || process.env.DEFAULT_REGION || 'us-east-1');

const AWS_S3_BUCKET_NAME = "BucketName";\

const sts = new AWS.STS();

Now create a function to get the credentials

async webIdentityTokenProvider(): Promise { const tokenFilePath = process.env.AWS_WEB_IDENTITY_TOKEN_FILE; if (!tokenFilePath) { throw new Error( 'AWS_WEB_IDENTITY_TOKEN_FILE must be provided.', ); } const token = await readAsync(tokenFilePath, { encoding: 'ascii' }); const res = await client.send( new AssumeRoleWithWebIdentityCommand({ RoleArn:process.env.AWS_ROLE_ARN, WebIdentityToken: token, RoleSessionName: 'assumed-role-session-name', }), ); const { Credentials } = res; if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) { throw new Error('Credentials could not be retrieved.'); } return { accessKeyId: Credentials.AccessKeyId, secretAccessKey: Credentials.SecretAccessKey, expiration: Credentials.Expiration, sessionToken: Credentials.SessionToken, }; }

Don't worry about these env parameters in the above code, if your EKS is configured correctly, all the parameters will be automatically added in env by EKS.

How to use the Service

While creating an object for S3 to upload file, just call the above function like this

const s3 = new AWS.S3({ credentials: await this.webIdentityTokenProvider() }); const params = { Bucket: AWS_S3_BUCKET_NAME, Key: file.originalname, Body: Buffer.from(file.buffer, 'binary'), ContentType: request.mimetype }; const fileUploadResponse = await s3.upload(params).promise();

References