0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS SDK for JavaScript v3 - クレデンシャル取得

Posted at

目的

AWS SDK for JavaScript v3 で、
共有認証情報ファイル(~/.aws/credentials)と共有設定ファイル(~/.aws/config)から認証情報を取得する
@aws-sdk/credential-providersのfromIniを使用して、
MFA 設定あり profile のクレデンシャル取得
取得したクレデンシャルを使用してサービスクライアント実行

実装

import * as readline from "readline";

import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
import { fromIni } from "@aws-sdk/credential-providers";
import { program } from "commander";

program.option("-p --profile <s>", "set switch role profile");

const prompt = (query) => {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  return new Promise((resolve) =>
    rl.question(query, (ans) => {
      rl.close();
      resolve(ans);
    })
  );
};

const getAccountId = async (credentials) => {
  const client = new STSClient({ credentials });
  const command = new GetCallerIdentityCommand({});
  const response = await client.send(command);
  return response.Account;
};

const getCredentials = async (profile) => {
  const params = {
    mfaCodeProvider: async (serial) =>
      await prompt(`Type the mfa token for the following account: ${serial}: `),
  };
  if (profile !== undefined) {
    params.profile = profile;
  }
  const provider = fromIni(params);
  return await provider();
};

const main = async () => {
  program.parse(process.argv);
  const options = program.parse(process.argv).opts();
  const credentials = await getCredentials(options.profile);
  const accountId = await getAccountId(credentials);
  console.log(accountId);
};

await main();

スクリプト実行時のコマンドライン引数(--profile <profile名>)でprofileを指定できるようにしている
profile指定がない場合は、defaultのprofileで実行する

クレデンシャル取得関数(getCredentials)について、
const client = new STSClient({ credentials: provider });のように
fromIniの戻り値(provider)をクライアントにクレデンシャルとして指定できるが、
クライアントを生成するたびにMFA codeを聞かれるため、
await provider()としている

参考

How to use MFA in Javascript aws-sdk?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?