如何使用 boto3 更改 RDS 安全组?

How to change RDS Security Group using boto3?

我正在使用 boto3 恢复 (=创建新实例) RDS MySQL 快照。不幸的是,安全组没有被复制,而是被分配了 default 安全组,它对传入流量没有限制。

查看源 RDS 实例,我可以看到附加到 RDS 实例的正确安全组 (sg-a247eec5)。此安全组在 EC2 - Security Groups and VPC - Security Groups 下可见,但在 RDS - 安全组

我正在使用 restore_db_instance_from_db_snapshot,但我看不到将安全组附加到新实例的位置。

我可以使用 AWS UI(修改我的 RDS 实例)轻松附加正确的安全组。

EC2 客户端上有 modify_instance_attribute 可以更改安全组,但它需要一个 InstanceId,我无法从我的 RDS 实例中获取它。我唯一能找到的是 DBInstanceIdentifier.

尝试设置正确的 IAM 权限也让我感到困惑。我有一个 RDS ARN:arn:aws:rds:ap-southeast-2::db: 但 ModifyInstanceAttribute 列在 Amazon EC2 下。在策略编辑器中同时选择两者都会给我一个错误,指出 ARN 无效(这是有道理的)。

每当您使用 restore_db_instance_from_db_snapshot api 时,默认行为是应用 default security groupdefault parameter groupRDS API reference.

中也有同样的记录

The target database is created from the source database restore point with the most of original configuration with the default security group and the default DB parameter group.

解决方法是在还原完成后使用 modify_db_instance api。 DBInstanceIdentifier 之于 RDS 实例,InstanceId 之于 EC2 实例

传递您在上面使用的相同 DBInstanceIdentifier 作为此 api.

的输入
response = client.modify_db_instance(
    DBInstanceIdentifier='string',
    DBSecurityGroups=[
        'string',
    ], /* If you are using ec2 security groups then remove this and use VpcSecurityGroupIds. */

    VpcSecurityGroupIds=[
        'string',
    ],
    DBParameterGroupName='string',
    ApplyImmediately=True,

)

我相信您需要同时更改安全组和参数组(除非您对默认组没问题)。如果要更改参数组,则还需要重新启动数据库实例才能使设置生效。

response = client.reboot_db_instance(
    DBInstanceIdentifier='string',
)

此外,执行上述数据库操作的角色需要具有以下策略权限。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1507879517000",
            "Effect": "Allow",
            "Action": [
                "rds:CreateDBInstance",
                "rds:ModifyDBInstance",
                "rds:RebootDBInstance",
                "rds:RestoreDBInstanceFromDBSnapshot"
            ],
            "Resource": [
                "arn:aws:rds:*:XXXXXXXXXX:db:*"
            ]
        }
    ]
}