从 AWS ECS Fargate 访问 AWS RDS 的最佳方式

Best way to access AWS RDS from AWS ECS Fargate

我有 Java 基于容器 运行 AWS ECS Fargate。现在我们通过用户名密码组合访问 AWS RDS Postgres 数据库,但我想知道如何使这个过程更安全。

但我有一个问题:如何避免在 .psql 脚本中存储用户密码 (CREATE USER username WITH PASSWORD 'xxx')?我认为更好的选择是完全避免使用密码,但我不确定该怎么做...

从 AWS Secrets Manager 向 Fargate 容器加载密码 - 这没问题。

请问您有什么建议吗?


编辑:我会在这里分享我的进步,这样任何人都可以重现
文档:https://docs.aws.amazon.com/.../.../.../UsingWithRDS.IAMDBAuth.html

- 第一阶段 -
目标:IAM Auth 的 PoC(使用 IAM 用户)

  1. I have prepared my RDS instance to allow IAM Auth
  2. 我已经创建了 IAM 用户,attached new IAM Policy to it 并创建了一个访问密钥。
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "rds-db:*",
            "Resource": "arn:aws:rds-db:eu-central-1:666:dbuser:db-YFVS/iam_user"
        }
    ]
}

注意:资源中使用的是resourceId,不是arn! (这可以在rds实例的配置选项卡中找到)

  1. I have created user in my database
CREATE USER iam_user; 
GRANT rds_iam TO iam_user;
  1. I tested the connection(导出访问密钥后)
# Generate token
export RDSHOST="dev.aaaaa.eu-central-1.rds.amazonaws.com"
export PGPASSWORD="$(aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --region eu-central-1 --username iam_user )"

#Connect
psql "host=$RDSHOST port=5432 dbname=mydb user=iam_user password=$PGPASSWORD"

mydb->

现在我想继续 Java 实施并进一步转移到 Fargate

- 第二阶段 -
目标:在 Python 应用中实施 IAM Auth 我已经按照这里的教程进行操作并且效果很好。我使用了我在上一步中创建的 IAM 用户的 IAM 凭证(密钥、机密)。另外,我已经从 ENVs 而不是配置文件加载了 creds。

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.Python.html

import psycopg2
import sys
import boto3

ENDPOINT="postgresmydb.123456789012.us-east-1.rds.amazonaws.com"
PORT="5432"
USR="jane_doe"
REGION="us-east-1"
DBNAME="mydb"

session = boto3.Session(region_name='us-east-1',
                        aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
                        aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])

token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USR, Region=REGION)

try:
    conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USR, password=token)
    cur = conn.cursor()
    cur.execute("""SELECT now()""")
    query_results = cur.fetchall()
    print(query_results)
except Exception as e:
    print("Database connection failed due to {}".format(e))                
                

根据评论。

一种不使用密码访问 RDS PostgreSQL 的方法是使用 IAM Database Authentication:

With this authentication method, you don't need to use a password when you connect to a DB instance. Instead, you use an authentication token.

有一些 limitations 需要考虑,其中之一是:

The maximum number of connections per second for your DB instance might be limited depending on its DB instance class and your workload.