> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getunblocked.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Amazon Aurora PostgreSQL

> Connect Aurora PostgreSQL to Unblocked over AWS PrivateLink and grant read-only database access

Use AWS PrivateLink to connect your Aurora PostgreSQL database to Unblocked without VPC peering or internet exposure. You publish a VPC endpoint service in front of your database. Unblocked verifies that you own the service, creates an interface endpoint from its AWS account, and you approve the connection.

Unblocked reaches only the database port on the IP addresses you register. Complete both parts to connect your database and grant read-only access.

1. [Set up AWS PrivateLink](#part-1-set-up-aws-privatelink).
2. [Set up a read-only role](#part-2-set-up-a-read-only-role).

## Part 1: Set up AWS PrivateLink

Choose one setup option:

* [Terraform](#option-1-terraform)
* [AWS CLI](#option-2-aws-cli)
* [AWS console](#option-3-aws-console)

### Before you start

Use an AWS identity that can describe your VPC and database instances, manage security groups, create Network Load Balancers and target groups, manage VPC endpoint services, and create IAM roles and inline policies. For cross-region access, it also needs `vpce:AllowMultiRegion`.

| Value | Setting |
| - | - |
| Unblocked endpoint-manager role | `arn:aws:iam::029574882031:role/ExternalConnectionsEndpointManager` |
| Unblocked AWS account | `029574882031` |
| Unblocked region | `us-west-2` |
| Your VPC | The VPC of your database. |
| Private subnets | One private subnet per Availability Zone for the load balancer. Use at least two Availability Zones. |
| Database security group | The security group attached to your Aurora cluster. |
| Database port | Usually `5432`. |
| Target IPs | The private IPv4 addresses of the database instances Unblocked should reach. |
| External ID | Copy the value under **External ID generated by Unblocked** in the Aurora PostgreSQL PrivateLink connection setup. Unique to your Unblocked organization. |

#### What you will build

Each option creates:

* A security group for the load balancer with no inbound rules and outbound access only to your database security group on the database port.
* An inbound rule on your database security group that allows the load balancer on that port.
* A TCP target group containing the private IP addresses you register and maintain.
* An internal Network Load Balancer (NLB) in your private subnets, forwarding the database port to the target group.
* A VPC endpoint service that allows only Unblocked's endpoint-manager role to connect.
* A verification role in the account that owns the endpoint service. Unblocked assumes it with your organization's external ID to confirm ownership. It can read only the endpoint service's allowed principals and its own trust policy.

#### Finding the target IPs

An NLB forwards to IP addresses, not RDS endpoint names. Find each database instance's endpoint, then resolve its private IPv4 address. Replace `INSTANCE_ID` with your instance identifier and `DATABASE_REGION` with its AWS region.

```bash theme={null}
INSTANCE_ENDPOINT=$(aws rds describe-db-instances \
  --db-instance-identifier INSTANCE_ID \
  --region DATABASE_REGION \
  --query 'DBInstances[0].Endpoint.Address' --output text)

dig +short A "$INSTANCE_ENDPOINT"
```

Register the reader instances if Unblocked should connect only to replicas. Keep the target list current when instance roles change; TCP health checks do not distinguish readers from writers.

#### Keeping the target IPs current

You own the target group and must update it when instance IP addresses or reader roles change. Unblocked cannot see or change your targets. Check them after:

* Failover, when a reader becomes the writer and the old writer may return as a reader.
* AWS maintenance or hardware recovery that moves an instance to a new host.
* Changes to instance classes or the number of readers.

Stale IP addresses can interrupt connectivity. Do not rely on health checks to block traffic: an NLB [fails open when all targets are unhealthy](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html).

You can automate updates with an EventBridge rule on RDS events and a Lambda function that resolves instance endpoints and updates the target group. AWS provides a sample in [Access Amazon RDS across VPCs using AWS PrivateLink and Network Load Balancer](https://aws.amazon.com/blogs/database/access-amazon-rds-across-vpcs-using-aws-privatelink-and-network-load-balancer/). The sample tracks the writer's IP; extend it if you register readers.

#### Same region or cross-region

If your database is in `us-west-2`, Unblocked matches your NLB's Availability Zones by AZ ID, such as `usw2-az1`.

For a database in another region, add `us-west-2` as a supported region of the endpoint service. The Terraform module does this automatically. AWS charges inter-region data transfer to the sending side. Choose NLB subnets in Availability Zones that support [cross-region PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-share-your-services.html#endpoint-service-cross-region).

> [accordion] Option 1: Terraform
>
> Use Terraform when you manage your AWS infrastructure with Terraform. The [Unblocked PrivateLink module](https://github.com/unblocked/terraform-aws-privatelink-integration) creates the network resources and verification role in your AWS provider's region. It requires Terraform 1.5 or later and AWS provider 6.0 or later.
>
> #### Add the module
>
> Add this configuration to your Terraform project. Replace the VPC, subnet, security group, and external ID values. Configure your AWS provider for the database's region.
>
> In the Aurora PostgreSQL PrivateLink connection setup in Unblocked, click **Copy** under **External ID generated by Unblocked**. Use the full copied value for `verification_external_id`, replacing `YOUR_EXTERNAL_ID` below.
>
> ![External ID generated by Unblocked with the organization-specific suffix masked and a Copy button](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-external-id.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=740fc0f0c96b756315992dd4b4b752d5)
>
> ```hcl theme={null}
> module "unblocked_privatelink_connection" {
>   source = "git::https://github.com/unblocked/terraform-aws-privatelink-integration.git?ref=v0.1.0"
>
>   name                       = "unblocked-privatelink"
>   vpc_id                     = "VPC_ID"
>   subnet_ids                 = ["SUBNET_ID_1", "SUBNET_ID_2"]
>   database_security_group_id = "DATABASE_SECURITY_GROUP_ID"
>
>   allowed_principals       = ["arn:aws:iam::029574882031:role/ExternalConnectionsEndpointManager"]
>   verification_external_id = "YOUR_EXTERNAL_ID"
>   verification_role_name   = "verification"
> }
>
> output "unblocked_endpoint_service_name" {
>   value = module.unblocked_privatelink_connection.endpoint_service_name
> }
>
> output "unblocked_endpoint_service_id" {
>   value = module.unblocked_privatelink_connection.endpoint_service_id
> }
>
> output "unblocked_verification_role_arn" {
>   value = module.unblocked_privatelink_connection.verification_role_arn
> }
>
> output "unblocked_target_group_arn" {
>   value = module.unblocked_privatelink_connection.target_group_arn
> }
> ```
>
> The module prefixes the verification role name with `UnblockedPrivateLink-`, so this example creates `UnblockedPrivateLink-verification`. Set `port` if your database uses a port other than `5432`. Set `auto_accept_connections = true` to accept connections from the allowed principal automatically.
>
> > [!NOTE]
> >
> > If Terraform manages your database security group with inline `ingress` blocks, omit `database_security_group_id` and allow the module's `nlb_security_group_id` output on the database port in your own configuration. Otherwise, the next apply of that security group removes the module's rule. When you omit this input, the NLB's outbound access uses the VPC CIDR, or the CIDRs you specify in `target_cidr_blocks`, on the database port.
>
> #### Apply and register the targets
>
> Apply the configuration:
>
> ```bash theme={null}
> terraform init
> terraform plan
> terraform apply
> ```
>
> The module creates an empty target group. Register your target IPs in the database's region. Replace the example IPs and adjust the port if needed.
>
> ```bash theme={null}
> aws elbv2 register-targets \
>   --region DATABASE_REGION \
>   --target-group-arn "$(terraform output -raw unblocked_target_group_arn)" \
>   --targets Id=10.0.1.25,Port=5432 Id=10.0.2.31,Port=5432
> ```
>
> Keep the IPs current as described [above](#keeping-the-target-ips-current). Do not manage targets with `aws_lb_target_group_attachment` resources alongside external target updates: a later apply can restore stale IPs and remove targets added by your automation.
>
> Print the service name and verification role ARN, and save the service ID for accepting the connection:
>
> ```bash theme={null}
> terraform output -raw unblocked_endpoint_service_name
> terraform output -raw unblocked_verification_role_arn
> SERVICE_ID=$(terraform output -raw unblocked_endpoint_service_id)
> ```
>
> Continue with [Connect in Unblocked](#connect-in-unblocked).

> [accordion] Option 2: AWS CLI
>
> Run these commands in Bash with AWS credentials for the account that owns your database. If you use zsh, including the default macOS shell, start `bash` first. These examples rely on Bash splitting the subnet and target IP lists into separate arguments.
>
> In the Aurora PostgreSQL PrivateLink connection setup in Unblocked, click **Copy** under **External ID generated by Unblocked**. Use the full copied value for `EXTERNAL_ID`, replacing `YOUR_EXTERNAL_ID` below.
>
> ![External ID generated by Unblocked with the organization-specific suffix masked and a Copy button](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-external-id.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=740fc0f0c96b756315992dd4b4b752d5)
>
> Replace the example region, resource IDs, and target IPs with your values:
>
> ```bash theme={null}
> REGION="us-west-2"
> VPC_ID="vpc-0123456789abcdef0"
> SUBNET_IDS="subnet-0123456789abcdef0 subnet-0fedcba9876543210"
> DB_SG_ID="sg-0123456789abcdef0"
> TARGET_IPS="10.0.1.25 10.0.2.31"
> PORT=5432
> NAME="unblocked-privatelink"
> UNBLOCKED_ROLE="arn:aws:iam::029574882031:role/ExternalConnectionsEndpointManager"
> EXTERNAL_ID="YOUR_EXTERNAL_ID"
> VERIFY_ROLE="UnblockedPrivateLinkVerification"
> export AWS_REGION="$REGION"
> ```
>
> #### Create the security groups
>
> Create the NLB security group. It starts with no inbound rules. Remove its default outbound rule, then allow only the database port to your database security group. Allow that traffic into your database security group:
>
> ```bash theme={null}
> NLB_SG_ID=$(aws ec2 create-security-group \
>   --group-name "$NAME-nlb" \
>   --description "Unblocked PrivateLink NLB" \
>   --vpc-id "$VPC_ID" \
>   --query GroupId --output text)
>
> aws ec2 revoke-security-group-egress --group-id "$NLB_SG_ID" \
>   --ip-permissions '[{"IpProtocol":"-1","IpRanges":[{"CidrIp":"0.0.0.0/0"}]}]'
>
> aws ec2 authorize-security-group-egress --group-id "$NLB_SG_ID" \
>   --ip-permissions "IpProtocol=tcp,FromPort=$PORT,ToPort=$PORT,UserIdGroupPairs=[{GroupId=$DB_SG_ID}]"
>
> aws ec2 authorize-security-group-ingress --group-id "$DB_SG_ID" \
>   --protocol tcp --port "$PORT" --source-group "$NLB_SG_ID"
> ```
>
> #### Create the target group
>
> Create a TCP target group with IP targets and TCP health checks every 10 seconds. Set a 30-second deregistration delay and register your target IPs:
>
> ```bash theme={null}
> TG_ARN=$(aws elbv2 create-target-group \
>   --name "$NAME" \
>   --protocol TCP --port "$PORT" \
>   --target-type ip \
>   --vpc-id "$VPC_ID" \
>   --health-check-protocol TCP \
>   --health-check-interval-seconds 10 \
>   --healthy-threshold-count 2 \
>   --unhealthy-threshold-count 2 \
>   --query 'TargetGroups[0].TargetGroupArn' --output text)
>
> aws elbv2 modify-target-group-attributes --target-group-arn "$TG_ARN" \
>   --attributes Key=deregistration_delay.timeout_seconds,Value=30
>
> aws elbv2 register-targets --target-group-arn "$TG_ARN" \
>   --targets $(for ip in $TARGET_IPS; do echo "Id=$ip,Port=$PORT"; done)
> ```
>
> #### Create the Network Load Balancer
>
> Create an internal NLB in your private subnets with the security group you created:
>
> ```bash theme={null}
> NLB_ARN=$(aws elbv2 create-load-balancer \
>   --name "$NAME" \
>   --type network \
>   --scheme internal \
>   --ip-address-type ipv4 \
>   --subnets $SUBNET_IDS \
>   --security-groups "$NLB_SG_ID" \
>   --query 'LoadBalancers[0].LoadBalancerArn' --output text)
>
> aws elbv2 wait load-balancer-available --load-balancer-arns "$NLB_ARN"
> ```
>
> Disable inbound security group enforcement for PrivateLink traffic. Without this setting, the empty inbound rules block Unblocked's connections. Enable cross-zone load balancing and forward the database port to your target group:
>
> ```bash theme={null}
> aws elbv2 set-security-groups --load-balancer-arn "$NLB_ARN" \
>   --security-groups "$NLB_SG_ID" \
>   --enforce-security-group-inbound-rules-on-private-link-traffic off
>
> aws elbv2 modify-load-balancer-attributes --load-balancer-arn "$NLB_ARN" \
>   --attributes Key=load_balancing.cross_zone.enabled,Value=true
>
> aws elbv2 create-listener --load-balancer-arn "$NLB_ARN" \
>   --protocol TCP --port "$PORT" \
>   --default-actions Type=forward,TargetGroupArn="$TG_ARN"
>
> aws elbv2 describe-target-health --target-group-arn "$TG_ARN" \
>   --query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output table
> ```
>
> Wait until every target shows `healthy`.
>
> #### Create the endpoint service
>
> Create a service that requires you to accept each connection. For automatic acceptance instead, replace `--acceptance-required` with `--no-acceptance-required`.
>
> For a database in `us-west-2`:
>
> ```bash theme={null}
> SERVICE_ID=$(aws ec2 create-vpc-endpoint-service-configuration \
>   --network-load-balancer-arns "$NLB_ARN" \
>   --acceptance-required \
>   --query 'ServiceConfiguration.ServiceId' --output text)
> ```
>
> For a database in another region, run this version instead to add `us-west-2` as a supported region:
>
> ```bash theme={null}
> SERVICE_ID=$(aws ec2 create-vpc-endpoint-service-configuration \
>   --network-load-balancer-arns "$NLB_ARN" \
>   --acceptance-required \
>   --supported-regions us-west-2 \
>   --query 'ServiceConfiguration.ServiceId' --output text)
> ```
>
> Allow only Unblocked's endpoint-manager role to create endpoints, then print the service details:
>
> ```bash theme={null}
> aws ec2 modify-vpc-endpoint-service-permissions --service-id "$SERVICE_ID" \
>   --add-allowed-principals "$UNBLOCKED_ROLE"
>
> aws ec2 describe-vpc-endpoint-service-configurations --service-ids "$SERVICE_ID" \
>   --query 'ServiceConfigurations[0].[ServiceName,ServiceId,AvailabilityZones]'
> ```
>
> #### Create the verification role
>
> Unblocked assumes this role to confirm that you own the endpoint service before it creates its endpoint. The role name must start with `UnblockedPrivateLink`. Use the `EXTERNAL_ID` value you copied from Unblocked earlier, including the `unblocked_privatelink_` prefix.
>
> Create a trust policy allowing only Unblocked's endpoint-manager role, with your external ID:
>
> ```bash theme={null}
> TRUST_POLICY=$(cat <<EOF
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Effect": "Allow",
>       "Principal": {"AWS": "$UNBLOCKED_ROLE"},
>       "Action": "sts:AssumeRole",
>       "Condition": {"StringEquals": {"sts:ExternalId": "$EXTERNAL_ID"}}
>     }
>   ]
> }
> EOF
> )
>
> aws iam create-role --role-name "$VERIFY_ROLE" \
>   --assume-role-policy-document "$TRUST_POLICY"
> ```
>
> Allow the role to read only your endpoint service's allowed principals and its own trust policy:
>
> ```bash theme={null}
> ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
> ROLE_POLICY=$(cat <<EOF
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Sid": "ReadOwnEndpointService",
>       "Effect": "Allow",
>       "Action": "ec2:DescribeVpcEndpointServicePermissions",
>       "Resource": "arn:aws:ec2:$REGION:$ACCOUNT_ID:vpc-endpoint-service/$SERVICE_ID"
>     },
>     {
>       "Sid": "ReadOwnTrustPolicy",
>       "Effect": "Allow",
>       "Action": "iam:GetRole",
>       "Resource": "arn:aws:iam::$ACCOUNT_ID:role/$VERIFY_ROLE"
>     }
>   ]
> }
> EOF
> )
>
> aws iam put-role-policy --role-name "$VERIFY_ROLE" \
>   --policy-name verify-endpoint-service \
>   --policy-document "$ROLE_POLICY"
>
> aws iam get-role --role-name "$VERIFY_ROLE" --query Role.Arn --output text
> ```
>
> Continue with [Connect in Unblocked](#connect-in-unblocked).

> [accordion] Option 3: AWS console
>
> Work in your database's region. These steps use port `5432`; substitute your database port if it differs.
>
> **1. Create the security groups**
>
> Open **EC2** › **Security Groups** and choose **Create security group**. Name it `unblocked-privatelink-nlb` and select your database's VPC.
>
> Leave **Inbound rules** empty. Under **Outbound rules**, delete the default **All traffic** rule. Add **Custom TCP**, port `5432`, with your database security group as the destination. Create the group.
>
> Open your database security group and edit its inbound rules. Add **Custom TCP**, port `5432`, with the NLB security group as the source. Save.
>
> **2. Create the target group**
>
> Open **EC2** › **Target Groups** and choose **Create target group**. Choose **IP addresses**, name it `unblocked-privatelink`, and select **TCP**, port `5432`, and your database's VPC.
>
> Set the health check protocol to **TCP**. Under advanced health check settings, set the healthy and unhealthy thresholds to `2` and the interval to `10` seconds.
>
> Choose **Next**, enter each target IP on port `5432`, and choose **Include as pending below**. Create the target group. On its **Attributes** tab, set the deregistration delay to `30` seconds.
>
> **3. Create the Network Load Balancer**
>
> Open **EC2** › **Load Balancers** and create a **Network Load Balancer** named `unblocked-privatelink`. Choose **Internal** and **IPv4**.
>
> Select your database's VPC and at least two Availability Zones with private subnets. Select the NLB security group instead of the default group. Configure a **TCP** listener on port `5432` that forwards to your target group. Create the load balancer and wait for **Active**.
>
> On the **Security** tab, edit the security settings and clear **Enforce inbound rules on PrivateLink traffic**. Save. On the **Attributes** tab, enable **Cross-zone load balancing**.
>
> Open your target group's **Targets** tab and wait for every target to become **Healthy**.
>
> **4. Create the endpoint service**
>
> Open **VPC** › **Endpoint services** and choose **Create endpoint service**. Choose **Network** and select your NLB.
>
> Keep **Require acceptance for endpoint** selected, or clear it to accept connections from allowed principals automatically. Leave **Enable private DNS name** cleared. For cross-region access, add `us-west-2` under **Supported Regions**. Choose **IPv4** and create the service.
>
> On **Allow principals**, add `arn:aws:iam::029574882031:role/ExternalConnectionsEndpointManager`.
>
> Copy the **Service name** and **Service ID** from **Details**.
>
> **5. Create the verification role**
>
> In the Aurora PostgreSQL PrivateLink connection setup in Unblocked, click **Copy** under **External ID generated by Unblocked**.
>
> ![External ID generated by Unblocked with the organization-specific suffix masked and a Copy button](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-external-id.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=740fc0f0c96b756315992dd4b4b752d5)
>
> Open **IAM** › **Roles** and choose **Create role**. Choose **Custom trust policy** to trust only Unblocked's endpoint-manager role. Replace `YOUR_EXTERNAL_ID` in this policy with the full copied value:
>
> ```json theme={null}
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Effect": "Allow",
>       "Principal": {"AWS": "arn:aws:iam::029574882031:role/ExternalConnectionsEndpointManager"},
>       "Action": "sts:AssumeRole",
>       "Condition": {"StringEquals": {"sts:ExternalId": "YOUR_EXTERNAL_ID"}}
>     }
>   ]
> }
> ```
>
> Choose **Next**, leave **Add permissions** empty, then choose **Next** again. Name the role `UnblockedPrivateLinkVerification` and create it. If you choose another name, it must start with `UnblockedPrivateLink`.
>
> Open the role and choose **Add permissions** › **Create inline policy**. Choose **JSON** and enter this policy with your region, account ID, service ID, and role name:
>
> ```json theme={null}
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Sid": "ReadOwnEndpointService",
>       "Effect": "Allow",
>       "Action": "ec2:DescribeVpcEndpointServicePermissions",
>       "Resource": "arn:aws:ec2:REGION:ACCOUNT_ID:vpc-endpoint-service/SERVICE_ID"
>     },
>     {
>       "Sid": "ReadOwnTrustPolicy",
>       "Effect": "Allow",
>       "Action": "iam:GetRole",
>       "Resource": "arn:aws:iam::ACCOUNT_ID:role/UnblockedPrivateLinkVerification"
>     }
>   ]
> }
> ```
>
> Name the policy `verify-endpoint-service` and create it. Copy the role's ARN from its summary.

### Connect in Unblocked

Provide these values in your Aurora PostgreSQL PrivateLink setup:

![Aurora PostgreSQL settings in Unblocked showing the new PrivateLink connection form with external ID, endpoint service name, AWS account ID, and verification role ARN](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-privatelink-connection.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=969522924e134633906ea87632ad4a32)

| Value | Description |
| - | - |
| Endpoint service name | For example, `com.amazonaws.vpce.us-west-2.vpce-svc-0123456789abcdef0`. |
| AWS account ID | The account that owns the endpoint service. |
| Verification role ARN | For example, `arn:aws:iam::ACCOUNT_ID:role/UnblockedPrivateLinkVerification`. |
| Region | The endpoint service's AWS region. |
| Port | Your database port, usually `5432`. |
| Database hostname | Your Aurora cluster reader endpoint. Unblocked verifies the database's TLS certificate against this name. Use the RDS endpoint name, not an IP address or custom DNS name. |

#### Accept Unblocked's connection

After Unblocked verifies the service and creates its endpoint, the connection waits in **Pending acceptance**. Check that its owner is Unblocked's account, `029574882031`, before accepting. With automatic acceptance enabled, the connection becomes **Available** without this step.

In the console, open **VPC** › **Endpoint services**, select your service, and open **Endpoint connections**. Select Unblocked's pending connection, then choose **Actions** › **Accept endpoint connection request**.

With the CLI, set the database region and service ID if they are not already set, then list requests:

```bash theme={null}
export AWS_REGION="DATABASE_REGION"
SERVICE_ID="vpce-svc-0123456789abcdef0"

aws ec2 describe-vpc-endpoint-connections \
  --filters "Name=service-id,Values=$SERVICE_ID" \
  --query 'VpcEndpointConnections[].[VpcEndpointId,VpcEndpointOwner,VpcEndpointState]' --output table
```

Accept the endpoint owned by `029574882031`, replacing the example endpoint ID:

```bash theme={null}
aws ec2 accept-vpc-endpoint-connections --service-id "$SERVICE_ID" \
  --vpc-endpoint-ids vpce-0123456789abcdef0
```

Wait for the connection to become **Available**, then tell Unblocked it is accepted.

### Removing access

Reject Unblocked's endpoint connection to cut off access. Removing its role from the allowed principals stops new endpoints but does not revoke an accepted connection.

```bash theme={null}
aws ec2 reject-vpc-endpoint-connections --service-id "$SERVICE_ID" \
  --vpc-endpoint-ids vpce-0123456789abcdef0
```

In the console, select the connection on **Endpoint connections** and choose **Actions** › **Reject endpoint connection request**.

To remove the resources, delete the endpoint service, NLB, target group, inbound rule on your database security group, NLB security group, and verification role, in that order. For Terraform, remove the module and apply. Use `terraform destroy` only if the Terraform configuration is dedicated to this integration.

### Troubleshooting

| Problem | Check |
| - | - |
| Targets are unhealthy. | Confirm that your database security group admits the NLB security group on the database port and that the target IPs are current. |
| Unblocked cannot create its endpoint. | Add the endpoint-manager role to **Allow principals**. For cross-region access, include `us-west-2` in the supported regions. |
| Setup fails during verification. | Confirm that the verification role belongs to the service owner's account, its name starts with `UnblockedPrivateLink`, and its trust policy requires your exact external ID and Unblocked's endpoint-manager role. Its permissions must allow `ec2:DescribeVpcEndpointServicePermissions` on your service and `iam:GetRole` on itself. IAM changes can take time to propagate; retry after a short wait if you just created the role. |
| The connection is accepted but traffic fails. | Clear **Enforce inbound rules on PrivateLink traffic** on the NLB. |

## Part 2: Set up a read-only role

> [!NOTE]
>
> If you already have a read-only role with access to the data you want Unblocked to read, and have granted it to a login user, skip the role and user setup below. Use that user's credentials and continue to [Enter database details in Unblocked](#enter-database-details-in-unblocked).

With PrivateLink configured, provide your database's hostname, port, and name, and create a dedicated login for Unblocked. Unblocked opens connections with `default_transaction_read_only=on` and a statement timeout. Give its login read permissions on only the data you want it to access.

### Database prerequisites

| Value | Where to find it |
| - | - |
| Aurora cluster | Your DB cluster identifier. In **RDS** › **Databases**, choose the row whose role is **Regional cluster**. |
| Region | The AWS region of your cluster. |
| Administrator | Your cluster's master user, plus the roles that own the schemas and tables you want to expose. |
| SQL access | `psql` on a host that can reach your cluster, such as an EC2 instance in its VPC or AWS CloudShell in a VPC environment. You can also use the RDS Query Editor with RDS Data API enabled. |
| PrivateLink | Unblocked's endpoint connection must be **Available**. |

### Find the hostname, port, and database name

Use your cluster's reader endpoint as the hostname, in the format `CLUSTER.cluster-ro-ID.REGION.rds.amazonaws.com`. Unblocked routes traffic through PrivateLink and verifies the database's TLS certificate against this hostname using the Amazon RDS certificate authority. Provide the RDS reader endpoint, rather than an IP address, NLB or VPC endpoint DNS name, custom endpoint, or your own DNS alias.

#### AWS console

1. Open **RDS** in your database's region and choose **Databases**.
2. Select your cluster's identifier, whose role is **Regional cluster**.
3. On **Connectivity & security**, under **Connect using**, choose **Endpoints**. Note the **Database name**, **Master username**, and **Port**. Copy the endpoint whose **Type** is **Reader**; its name contains `.cluster-ro-`. Also note the **Writer** endpoint for creating the database user. If the database name is empty, see [If there is no database name](#if-there-is-no-database-name).

![Aurora cluster connection details showing database name, master username, port, and writer and reader endpoints](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-endpoints.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=0df4ae8a9e05460578e8a59cba33f1c1)

#### AWS CLI

Run these commands in Bash with AWS credentials for your account. Replace the cluster identifier and region:

```bash theme={null}
CLUSTER_ID="YOUR_CLUSTER_ID"
REGION="us-west-2"
export AWS_REGION="$REGION"
```

If you do not know your cluster identifier, list the Aurora PostgreSQL clusters in the region:

```bash theme={null}
aws rds describe-db-clusters --filters Name=engine,Values=aurora-postgresql \
  --query 'DBClusters[].DBClusterIdentifier' --output text
```

Get the reader hostname, port, and database name. The database name is `None` if none was specified when the cluster was created:

```bash theme={null}
READER_HOST=$(aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" \
  --query 'DBClusters[0].ReaderEndpoint' --output text)
PORT=$(aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" \
  --query 'DBClusters[0].Port' --output text)
DB_NAME=$(aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" \
  --query 'DBClusters[0].DatabaseName' --output text)
echo "$READER_HOST" "$PORT" "$DB_NAME"
```

Get the writer hostname and master username for the next step:

```bash theme={null}
WRITER_HOST=$(aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" \
  --query 'DBClusters[0].Endpoint' --output text)
ADMIN_USER=$(aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" \
  --query 'DBClusters[0].MasterUsername' --output text)
echo "$WRITER_HOST" "$ADMIN_USER"
```

#### If there is no database name

The cluster's database name is specified at creation time. If it is empty, connect to the `postgres` database using one of the methods below and list the databases:

```sql theme={null}
SELECT datname FROM pg_database WHERE NOT datistemplate ORDER BY datname;
```

In `psql`, you can also use `\l`. Choose the database containing your data. Set `DB_NAME` to that name before continuing with the CLI examples.

### Create a read-only role and user

Create database users with SQL inside PostgreSQL. Run the following SQL as your cluster's master user, with schema and table owners applying grants where required. Connect to the **writer endpoint** and to the **database Unblocked will read**. Readers cannot create roles, and schema and table grants apply within the database you connect to.

#### Connect with RDS Query Editor

The Query Editor requires [RDS Data API](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.enabling.html), which is not supported on T instance classes such as `db.t3` and `db.t4g`. Your AWS identity needs `AmazonRDSDataFullAccess` or the permissions listed in [Using the Aurora query editor](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/query-editor.html).

1. If Data API is disabled, open your cluster and choose **Actions** › **Enable RDS Data API**. You can also enable it with the CLI, replacing `CLUSTER_ARN`:

   ```bash theme={null}
   aws rds enable-http-endpoint --resource-arn CLUSTER_ARN
   ```

2. On **Connectivity & security**, under **Connect using**, choose **Query Editor**, then **Navigate to Query Editor**. You can also choose **Query editor** in the RDS navigation.

3. In **Connect to database**, choose your cluster. Under **Database username**, choose **Add new database credentials** and enter your master username and password. Enter your database name, then connect. Query Editor stores these credentials in AWS Secrets Manager.

   ![RDS Query Editor Connect to database dialog with cluster, username, password, and database name fields](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-query-editor-connect.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=7da07efef2116894861c4be987e1c7ac)

4. Run the statements in [Run the SQL](#run-the-sql) in order.

#### Connect with psql

From a host that can reach the cluster, download the [RDS certificate bundle](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.SSL.html):

```bash theme={null}
curl -fsSLo global-bundle.pem https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
```

Using the values you collected earlier, connect to the writer endpoint as your administrator. `psql` prompts for your password:

```bash theme={null}
psql "host=$WRITER_HOST port=$PORT dbname=$DB_NAME user=$ADMIN_USER sslmode=verify-full sslrootcert=global-bundle.pem"
```

#### Run the SQL

The role `unblocked_readonly` holds read permissions; the login `unblocked` inherits them. You can choose other names. Replace `<database>`, `<schema>`, `<table>`, and `<password>` with your own values wherever they appear.

**1. Create the read-only role**

This role cannot log in. You grant it to the login user later.

```sql theme={null}
CREATE ROLE unblocked_readonly NOLOGIN;
```

**2. Allow database connections**

```sql theme={null}
GRANT CONNECT ON DATABASE <database> TO unblocked_readonly;
```

**3. List your schemas**

Exclude PostgreSQL's system schemas:

```sql theme={null}
SELECT nspname FROM pg_namespace
WHERE nspname <> 'information_schema' AND nspname !~ '^pg_'
ORDER BY nspname;
```

**4. Grant read access**

Run this block to grant schema usage and read access to existing tables and views, plus tables created later by the role running it:

```sql theme={null}
DO $$
DECLARE
  s text;
BEGIN
  FOR s IN
    SELECT nspname FROM pg_namespace
    WHERE nspname <> 'information_schema' AND nspname !~ '^pg_'
  LOOP
    EXECUTE format('GRANT USAGE ON SCHEMA %I TO unblocked_readonly', s);
    EXECUTE format('GRANT SELECT ON ALL TABLES IN SCHEMA %I TO unblocked_readonly', s);
    EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT ON TABLES TO unblocked_readonly', s);
  END LOOP;
END
$$;
```

To choose schemas individually, or if Query Editor rejects the block, run these statements for each schema instead:

```sql theme={null}
GRANT USAGE ON SCHEMA <schema> TO unblocked_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA <schema> TO unblocked_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT SELECT ON TABLES TO unblocked_readonly;
```

Apply existing-object grants as an owner or a role with the required grant options. Missing grant authority can produce permission errors or warnings that no privileges were granted.

Default privileges apply only to objects created by the specified role, or the current role when none is specified. If an application or migration role creates tables, configure its defaults too: run the statements as that role, or use `ALTER DEFAULT PRIVILEGES FOR ROLE` with the appropriate role name and permissions. Repeat the schema grants for schemas added later. See [PostgreSQL default privileges](https://www.postgresql.org/docs/current/sql-alterdefaultprivileges.html).

**5. Create the login user**

Use a strong password. If you plan to test this login through Query Editor on Aurora PostgreSQL 14 or later, its password must use SCRAM-SHA-256. This is the default for new clusters on these versions. See [Aurora password encryption](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/PostgreSQL_Password_Encryption_configuration.html) if you use a custom configuration.

```sql theme={null}
CREATE USER unblocked WITH PASSWORD '<password>';
```

In `psql`, you can omit the password from `CREATE USER` and set it with `\password unblocked` to keep it out of command history.

**6. Grant the role to the user**

```sql theme={null}
GRANT unblocked_readonly TO unblocked;
```

**7. Make sessions read-only by default (optional)**

Unblocked already sets this on its connections. Set it on the login too if you want the same default for other clients. The read-only default does not replace permission grants.

```sql theme={null}
ALTER ROLE unblocked SET default_transaction_read_only = on;
```

> [accordion] Alternative: use pg\_read\_all\_data on PostgreSQL 14 or later
>
> Instead of creating and granting the custom role, create the login user as above and grant the predefined `pg_read_all_data` role:
>
> ```sql theme={null}
> GRANT pg_read_all_data TO unblocked;
> ```
>
> This grants read access to tables, views, and sequences in every schema, including ones created later. It applies across every database in the cluster that the login can connect to. Use it only if that scope is appropriate. Row-level security policies still apply. See [PostgreSQL predefined roles](https://www.postgresql.org/docs/14/predefined-roles.html).

> [accordion] Restrict access to specific tables or columns
>
> Instead of the schema-wide table grants, grant schema usage:
>
> ```sql theme={null}
> GRANT USAGE ON SCHEMA <schema> TO unblocked_readonly;
> ```
>
> To expose all columns from specific tables:
>
> ```sql theme={null}
> GRANT SELECT ON <schema>.<table>, <schema>.<other_table> TO unblocked_readonly;
> ```
>
> To expose only selected columns from a table instead:
>
> ```sql theme={null}
> GRANT SELECT (<column>, <other_column>) ON <schema>.<table> TO unblocked_readonly;
> ```
>
> Table-level `SELECT` allows every column. Use column grants on a table only when you have not also granted table-level `SELECT`. Unblocked lists ordinary and partitioned tables, and exposes only columns its user can read. It does not list views.
>
> See [Managing PostgreSQL users and roles](https://aws.amazon.com/blogs/database/managing-postgresql-users-and-roles/) and [PostgreSQL GRANT](https://www.postgresql.org/docs/current/sql-grant.html).

### Check the database user

Use `psql` from the host you used for setup. Query Editor can check permissions and list tables, but it cannot test the reader hostname or the PrivateLink network path.

1. Connect to the reader endpoint as `unblocked` with TLS certificate verification:

   ```bash theme={null}
   psql "host=$READER_HOST port=$PORT dbname=$DB_NAME user=unblocked sslmode=verify-full sslrootcert=global-bundle.pem"
   ```

2. If you set the login's read-only default, confirm that it returns `on`:

   ```sql theme={null}
   SELECT current_setting('transaction_read_only');
   ```

3. List the tables Unblocked can see:

   ```sql theme={null}
   SELECT n.nspname, c.relname
   FROM pg_catalog.pg_class c
   JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE c.relkind IN ('r', 'p')
     AND n.nspname <> 'information_schema'
     AND n.nspname !~ '^pg_'
     AND pg_catalog.has_schema_privilege(n.oid, 'USAGE')
     AND pg_catalog.has_any_column_privilege(c.oid, 'SELECT')
   ORDER BY n.nspname COLLATE "C", c.relname COLLATE "C";
   ```

4. Check write privileges on a table, including column-level grants. Replace `<schema>.<table>`. The result should be `f`:

   ```sql theme={null}
   SELECT has_table_privilege('<schema>.<table>', 'INSERT, UPDATE, DELETE, TRUNCATE')
     OR has_any_column_privilege('<schema>.<table>', 'INSERT, UPDATE') AS can_write;
   ```

5. Optionally, connect to the writer endpoint as `unblocked` and try this against a disposable test table. The insert should fail with `permission denied for table`:

   ```sql theme={null}
   BEGIN READ WRITE;
   INSERT INTO <schema>.<table> DEFAULT VALUES;
   ROLLBACK;
   ```

### Enter database details in Unblocked

Enter these values in the Aurora PostgreSQL connection settings, alongside your PrivateLink values:

![Aurora PostgreSQL settings in Unblocked showing the database connection fields for Aurora hostname, port, database, username, and password](https://mintcdn.com/unblocked/VxXzoYZ1jpVhd8Q8/img/aurora-database-connection.png?fit=max\&auto=format\&n=VxXzoYZ1jpVhd8Q8\&q=85\&s=752b63f73989d72071d7bccf7e5076ee)

| Field | Value |
| - | - |
| Aurora hostname | The cluster reader endpoint, such as `mycluster.cluster-ro-abc123example.us-west-2.rds.amazonaws.com`. |
| Port | Your database port, usually `5432`. |
| Database | The database containing the data you want to access. |
| Username | `unblocked`, or the login name you chose. |
| Password | The login's password. Enter it only in the Unblocked settings form. |

Complete connection verification in Unblocked to check the PrivateLink path as well as your database credentials and TLS configuration.

### Choose your environment

After verifying the connection, open **Settings** › **Data Sources** › **Aurora PostgreSQL**. Under **Environment**, choose **Production** for real business data or **Development** for test and sample data. If you change the environment, click **Save Settings**.

Check **Exposed tables** to see which tables Unblocked can read with the configured database role.

![Aurora PostgreSQL settings with the Environment dropdown, Exposed tables list, and Save Settings button](https://mintcdn.com/unblocked/USjkacQOZ7fvSVWH/img/aurora-environment.png?fit=max\&auto=format\&n=USjkacQOZ7fvSVWH\&q=85\&s=c617161545fc3a64adf8aa7a72b829a8)

### Database troubleshooting

| Problem | Check |
| - | - |
| Database verification fails. | Confirm that PrivateLink is **Available**, the hostname is your reader endpoint, the database name matches exactly, and the username and password are correct. |
| Tables or columns are missing, or a query reports permission denied. | Check schema `USAGE` and table or column `SELECT` grants. Run the table-list query as `unblocked`. Apply grants for additional table-creating roles and newly added schemas. Views are not listed. |

## References

* [Share your services through AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-share-your-services.html).
* [Configure an endpoint service](https://docs.aws.amazon.com/vpc/latest/privatelink/configure-endpoint-service.html).
* [Target groups for your Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html).
* [Update the security groups for your Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html).
* [Amazon Aurora endpoint connections](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html).
* [Understanding PostgreSQL roles and permissions](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Appendix.PostgreSQL.CommonDBATasks.Roles.html).
