Home > front end >  How do I use two AWS IAM accounts in a single program?
How do I use two AWS IAM accounts in a single program?

Time:10-12

I've been trying transfer some data in bulk between DynamoDB Tables on two different accounts and I haven't been able to do so because I can't use another account in the same program since it just defaults to my main account I use in the AWS CLI.

Here's my code for accessing the two different IAM accounts.

Destination_acc.js

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const CONFIG = {
  region: "us-east-1",
  accessKeyId: "x",
  secretAccessKey: "y",
};
const dest = new DynamoDBClient(CONFIG);
export { dest };

Source_acc.js

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const CONFIG = {
  region: "us-east-1",
  accessKeyId: "x",
  secretAccessKey: "y",
};
const source = new DynamoDBClient(CONFIG);
export { source };

test.js

export const scanTable = async () => {
  const params = {
    TableName: "table",
  };

  var scanResults = [];
  var items = [];
  do {
    items = await dest.send(new ScanCommand(params));
    items.Items.forEach((item) => {
      console.log(item);
      scanResults.push(item);
    });
    params.ExclusiveStartKey = items.LastEvaluatedKey;
  } while (typeof items.LastEvaluatedKey !== "undefined");

  return scanResults;
};

scanTable(); //Returns the data in the table of `source` account instead of the data in `dest` account.

CodePudding user response:

DynamoDB picks the account and region based on IAM role. You first need to set up a role in the second account which you are allowed to assume from the first account: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html

After that, in your code you need to call sts assumeRole and create a second client based on that role: https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html

Now when you assume the role and create a client with that role you can access DynamoDB tables/ other resources in the second account.

  • Related