LoginSignup
8
6

More than 5 years have passed since last update.

IAM Database AuthenticationをPythonから試す

Posted at

背景

RDS for MySQLとAuroraのDB接続にIAMが使えるようになったそうです。
Manage access to your RDS for MySQL and Amazon Aurora databases using AWS IAM
IAM Database Authentication for MySQL and Amazon Aurora
サンプルがJavaだったのでPythonから試してみました。

環境

  • Amazon Linux 2017.03
  • Aurora 1.12
  • Python 2.7.12
  • boto3-1.4.4

準備

Aurora

RDSのクラスターから「クラスターの変更」を開き「IAMのDB認証を有効にする」を「はい」に設定します。Auroraの場合db.t2.smallはIAMデータベース認証をサポートしていないためdb.t2.medium以上で試してください。
RDS_·_AWS_Console.png

DBユーザーの作成

IAMアクセス用のDBユーザーを作成し、必要な権限を付与します。

mysql> CREATE USER iam_auth_user@'testdb-cluster.cluster-abcdefghijkl.ap-northeast-1.rds.amazonaws.com' IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS';
mysql> GRANT SELECT ON `testdb`.* TO iam_auth_user@'%';

公開鍵のダウンロード

IAMデータベース認証はSSL接続が必須という事なので公開鍵をダウンロードしてec2上の適当なパスに配置しておきます
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Overview.html#Aurora.Overview.Security.SSL

IAM

ドキュメントを参考にIAM Roleに権限を付与します。リソースIDはクラスターのものを指定しています。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "rds-db:connect"
      ],
      "Resource": [
        "arn:aws:rds-db:ap-northeast-1:12345678:dbuser:cluster-12ABC34DEFG5HIJ6KLMNOP78QR/iam_auth_user"
      ]
    }
  ]
}

接続

iam_db_auth.py
#  -*- coding: utf-8 -*-
from __future__ import print_function
import boto3
import mysql.connector
from mysql.connector.constants import ClientFlag

rds = boto3.client('rds', region_name='ap-northeast-1')

user = 'iam_auth_user'
host = 'testdb-cluster.cluster-abcdefghijkl.ap-northeast-1.rds.amazonaws.com'
db_auth_token = rds.generate_db_auth_token(host, 3306, user, 'ap-northeast-1')

config = {
    'user': user,
    'password': db_auth_token,
    'host': host,
    'db': 'testdb',
    'client_flags': [ClientFlag.SSL],
    'ssl_ca': 'rds-combined-ca-bundle.pem'
}

cnx = mysql.connector.connect(**config)
cur = cnx.cursor(buffered=True)

cur.execute('SELECT AURORA_VERSION();')
print(cur.fetchone())

cur.close()
cnx.close()
$ python iam_db_auth.py 
[(u'1.12',)]

以上です。

参考

8
6
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
8
6