Skip to main content
 首页 » 编程设计

postgresql之使用 S3 和 aws_s3 将 Postgres 数据导入 RDS

2024年10月17日30shanyou

我很难将数据从 S3 导入 RDS postgres 实例。 According to the docs ,您可以使用以下语法:

aws_s3.table_import_from_s3 ( 
   table_name text,  
   column_list text,  
   options text,  
   bucket text,  
   file_path text,  
   region text,  
   access_key text,  
   secret_key text,  
   session_token text  
)  

所以,在 pgAdmin 中,我这样做了:
SELECT aws_s3.table_import_from_s3( 
  'contacts_1',  
  'firstname,lastname,imported',  
  '(format csv)', 
  'com.foo.mybucket',  
  'mydir/subdir/myfile.csv',  
  'us-east-2', 
  'AKIAYYXUMxxxxxxxxxxx', 
  '3zB4S5jb1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 
); 

我还对最后一个参数使用显式 NULL 进行了尝试。

我得到的错误信息是:
NOTICE:  CURL error code: 51 when attempting to validate pre-signed URL, 1 attempt(s) remaining 
NOTICE:  CURL error code: 51 when attempting to validate pre-signed URL, 0 attempt(s) remaining 
 
ERROR:  Unable to generate pre-signed url, look at engine log for details. 
SQL state: XX000 

我检查了服务器日志,没有进一步的信息。

我已经三重检查了所有参数的正确性。我如何使这项工作?

更新:

我可以确认我可以使用这些相同的凭据在 Java aws sdk 中执行 s3.getObject()。

请您参考如下方法:

这里的主要问题是您需要 1) 向 RDS 实例添加一个 IAM 角色以访问 S3 存储桶,以及 2) 向运行 RDS 实例的 VPC 添加一个 S3 端点以允许通信。

这是我为使其工作而遵循的过程,在 shell 中使用 AWS cli 命令(正确处理所涉及的环境变量的值),希望它可以帮助:

  • 创建 IAM 角色:
  • $ aws iam create-role \ 
        --role-name $ROLE_NAME \ 
        --assume-role-policy-document '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"Service": "rds.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' 
    
  • 创建将附加到 IAM 角色的 IAM 策略:
  • $ aws iam create-policy \ 
        --policy-name $POLICY_NAME \ 
        --policy-document '{"Version": "2012-10-17", "Statement": [{"Sid": "s3import", "Action": ["s3:GetObject", "s3:ListBucket"], "Effect": "Allow", "Resource": ["arn:aws:s3:::${BUCKET_NAME}", "arn:aws:s3:::${BUCKET_NAME}/*"]}]}' 
    
  • 附上政策:
  • $ aws iam attach-role-policy \ 
        --policy-arn arn:aws:iam::$AWS_ACCOUNT_ID:policy/$POLICY_NAME \ 
        --role-name $ROLE_NAME 
    
  • 将角色添加到特定实例 - 需要为每个新实例重复此步骤:
  • $ aws rds add-role-to-db-instance \ 
        --db-instance-identifier $RDS_INSTANCE_NAME \ 
        --feature-name s3Import \ 
        --role-arn arn:aws:iam::$AWS_ACCOUNT_ID:role/$ROLE_NAME \ 
        --region $REGION 
    
  • 为 S3 服务创建 VPC 端点:
  • $ aws ec2 create-vpc-endpoint \ 
        --vpc-id $VPC_ID \ 
        --service-name com.amazonaws.$REGION.s3 
        --route-table-ids $ROUTE_TABLE_ID 
    

    可以通过命令获取与创建端点的VPC相关的路由表id
    $ aws ec2 describe-route-tables | jq -r '.RouteTables[] | "\(.VpcId) \(.RouteTableId)"'