LoginSignup
18
11

More than 5 years have passed since last update.

AWS SDK for RubyでMFA認証とAssumeRole

Last updated at Posted at 2018-12-24

さまざまな事情で、IAM Roleを介してリソース操作が必要になることがあると思います。その際にMFA認証必須のIAM Roleのクレデンシャルを取得しリソースへアクセスする際の書き方です。

credentials

AWSのcredentialsは下記のように設定されていると仮定します。
リージョンは例としてap-northeast-1としていますが、適宜使用しているリージョンに置き換えてください。

access_keyやsecrete_access_keyの取得方法はここでは説明しません。

~/.aws/credentials
[hoge]
aws_access_key_id = AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Aws::STS::Client

AWS Security Token Service(STS)を使用して一時的セキュリティ認証情報を作成し、AssumeRoleを行います
https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/STS/Client.html#assume_role-instance_method

~/.aws / credentialsに定義している共有資格情報ファイルから資格情報をロードするときはprofileオプションを使います。

sts_client = Aws::STS::Client.new(profile: hoge, region: 'ap-northeast-1')

Aws::AssumeRoleCredentials

AssumeRoleCredentialsを用いて、AssumeRoleを行いロールのcredentialを取得します。
https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/AssumeRoleCredentials.html
MFA認証を設定している場合はserial_numberにMFAデバイスのARN、token_codeにMFAコード(6桁)を設定する必要があります。
MFAコードは定期的に変わるため、実行時に引数で与えるようにするなど工夫が必要です。

sts_client = Aws::STS::Client.new(profile: 'hoge', region: 'ap-northeast-1')
role_credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: ロールのARN, role_session_name: ロールのセッション名(任意の名前), serial_number: MFAデバイスのARN, token_code: MFAコード)

AssumeRoleCredentialsで取得したcredentialを元にAWSリソースを扱います。

# 作成したロールのcredentialでリソースにアクセス
Aws::S3::Resource.new(region: 'ap-northeast-1', credentials: role_credentials)

参考

https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_credentials_temp.html
https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/STS.html
https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/AssumeRoleCredentials.html
https://dev.classmethod.jp/cloud/aws/aws-cli-supports-assume-role-credentials-provider-and-mfa/

18
11
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
18
11