代码之家  ›  专栏  ›  技术社区  ›  injoy

如何使用terraform为RDS postgres db用户提供AWS IAM auth?

  •  0
  • injoy  · 技术社区  · 5 年前

    https://aws.amazon.com/premiumsupport/knowledge-center/users-connect-rds-iam/ 我注意到我需要在使用主用户名和密码登录后创建一个DB用户:

    CREATE USER {dbusername} IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS';
    

    mysql_user 配置mysql db用户: https://www.terraform.io/docs/providers/mysql/r/user.html

    postgres_user

    0 回复  |  直到 5 年前
        1
  •  1
  •   brietsparks    4 年前

    在Postgres中,用户被称为“角色”。这个 Postgres docs

    因此,要创建的TF资源是 postgresql_role

    resource "postgresql_role" "my_replication_role" {
      name             = "replication_role"
      replication      = true
      login            = true
      connection_limit = 5
      password         = "md5c98cbfeb6a347a47eb8e96cfb4c4b890"
    }
    

    要使IAM用户承担此角色, follow the steps in the AWS docs

    module "db" {
      source = "terraform-aws-modules/rds/aws"
      // ...
    }
    
    provider "postgresql" {
     // ...
    }
    
    resource "postgresql_role" "pguser" {
      login    = true
      name     = var.pg_username
      password = var.pg_password
      roles = ["rds_iam"]
    }
    
    resource "aws_iam_user" "pguser" {
      name = var.pg_username
    }
    
    resource "aws_iam_user_policy" "pguser" {
      name = var.pg_username
      user = aws_iam_user.pguser.id
      policy = <<EOF
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "rds-db:connect"
          ],
          "Resource": [
            "arn:aws:rds-db:${var.region}:${data.aws_caller_identity.current.account_id}:dbuser:${module.db.this_db_instance_resource_id}/${var.pg_username}"
          ]
        }
      ]
    }
    EOF
    }