LoginSignup
2
0

ibm-cloud-sdk-coreのIAMAuthenticatorを使って IAM トークンの生成(python)

Last updated at Posted at 2023-12-08

IBM Cloud サービス API の呼び出しには通常IBM Cloud Identity and Access Management (IAM) トークンが必要です(参考: IBM Cloud サービス API の呼び出し)。

このIAMトークンを取得するは、APIキーを使用して、RESTサービスにアクセスして取得します。

上記のLinkにはCurlでの取得方法、そしてpythonでの取得コードサンプルがあります。
がしかし、pythonでの取得コードサンプルは以下のようにIBM Cloud SDKのサービス利用前提となっていて、単独でIAMトークン文字列を取得するコードになっていません。

from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from <sdk-package-name>.example_service_v1 import *

# Create the authenticator.
authenticator = IAMAuthenticator('myapikey')

# Construct the service instance.
service = ExampleServiceV1(authenticator=authenticator)

# 'service' can now be used to invoke operations.

よってIAMトークン文字列のみをpythonで取得したい時は、Curlを参考にRESTリスクエストをpythonで書いてました。

でもせっかくIAMAuthenticatorでおそらくIAMトークン文字列を取得しているはずなので、中にあるんだろうということで、調べました。RESTで書くよりは簡単になります。

1. 事前準備

ibm_cloud_sdk_coreが未導入の場合はpip等で導入してください。

python -m pip install --upgrade ibm-cloud-sdk-core

またAPIKEYが必要なのでない場合は以下を参考に取得して下さい。

2. ibm-cloud-sdk-coreのIAMAuthenticatorを使って IAM トークンの生成

以下のコードを実行すればaccess_tokenにIAMトークンが入ります。
<ここにAPIKEYを入れる>にAPIKEYの文字列をコピーしてください。前後の<>は不要なので含めないようにしてください。
例: authenticator = IAMAuthenticator('xxxxxxxxxx')

from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('<ここにAPIKEYを入れる>')
access_token=authenticator.token_manager.get_token()

# 参考までに表示してみます
print(access_token)

上記はエラーハンドリングなしなので、本気で使う場合は追加でエラーハンドリングが必要です。Jupyter Notebookなんかで軽く使うならこのまま使えて、RESTで書くより簡単だと思います。

以上です。

2
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
2
0