LoginSignup
0
0

More than 3 years have passed since last update.

JavaScript/TypeScriptでAWSのARNをパースする方法

Last updated at Posted at 2020-12-22

JavaScript/TypeScriptでAWSのARNをパースして、サービス、リージョン、アカウントID、リソースIDなどを取得する方法をご紹介します。

ARNとは

ARNはAWS上のリソースを一意に識別するための識別子のことで、arn:aws:s3:us-west-2:123456789012:accesspoint:myendpointのような文字列で表されます。
単純そうに見えてそのフォーマットにはいくつかのバリエーションがあり、自前でパースしようとするのはバグの温床となりえます。

パッケージをインストール

ARNをパースするためのnpmパッケージはいくつかあるようですが、AWSが公式に提供している@aws-sdk/util-arn-parserを使うのがいいでしょう。

$ npm i @aws-sdk/util-arn-parser

ARNをパース

JavaScriptの場合:

const { parse } = require('@aws-sdk/util-arn-parser')

const arn = 'arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint'
const {
  partition,
  service,
  region,
  accountId,
  resource
} = parse(arn)
console.log(partition)  // aws
console.log(service)  // s3
console.log(region)  // us-west-2
console.log(accountId)  // 123456789012
console.log(resource)  // accesspoint:myendpoint

TypeScriptの場合:

import { parse } from '@aws-sdk/util-arn-parser'

const arn = 'arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint'
const {
  partition,
  service,
  region,
  accountId,
  resource
} = parse(arn)
console.log(partition)  // aws
console.log(service)  // s3
console.log(region)  // us-west-2
console.log(accountId)  // 123456789012
console.log(resource)  // accesspoint:myendpoint

参考リンク

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