本文介绍了如何使用 Django 进行 RDS IAM 身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 django 应用程序使用 IAM 身份验证连接到 RDS postgres.这意味着数据库密码每 15 分钟过期一次,应该重新生成.问题是如何在运行时更改数据库密码?还是应该更新我的数据库 URL 环境?

I want my django application connect to RDS postgres using IAM authentication. That means the db password expires every 15min and should be re-generated. The problem is how can I change the database password in the runtime? Or should I update my database URL environment?

推荐答案

我们为此功能实现了一个包并发布到 PyPi.你可以在这里查看https://github.com/labd/django-iam-dbauth

We implemented a package for this functionality and published to PyPi. You can check it here https://github.com/labd/django-iam-dbauth

但原则上步骤如下:

首先启用 IAM 身份验证.

然后添加策略并附加 连接到数据库的角色或用户.

Then add the policy and attach it to the role or user that connects to the DB.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "rds-db:connect"
        ],
        "Resource": [
            "arn:aws:rds-db:us-east-2:1234567890:dbuser:db-ABCDEFGHIJKL01234/db_userx"
        ]
    }
]
}

然后在您的 AWS postgres 上创建一个用户并为其授予 rds_iam 角色:

Then create a user on your AWS postgres and grant rds_iam role to it:

CREATE USER db_userx WITH LOGIN;
GRANT rds_iam TO db_userx;

对于 Django,您需要一个自定义后端以允许即时生成凭据.

For Django, you need a custom backend to allow generating credentials on the fly.

创建一个包,例如 your.package.postgresql,其中包含 base.py

Create a package such as your.package.postgresql with a base.py in it

import boto3
from django.db.backends.postgresql import base

class DatabaseWrapper(base.DatabaseWrapper):
    def get_connection_params(self):
        params = super().get_connection_params()
        rds_client = boto3.client("rds")
        params["password"] = rds_client.generate_db_auth_token(
            DBHostname=params.get("host", "localhost"),
            Port=params.get("port", 5432),
            DBUsername=params.get("user") or getpass.getuser(),
        )

        return params

然后使用如下设置:

DATABASES = {
    "default": {
        "HOST": "<hostname>",
        "USER": "<user>",
        "PORT": 5432,
        "ENGINE": "your.package.postgresql"
    }
}

这篇关于如何使用 Django 进行 RDS IAM 身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 20:09