> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-trino-dialect.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Configure o Amazon RDS Postgres como origem para o ClickPipes

# Guia de configuração da origem RDS Postgres

export const IAMAuthentication = ({engine, service, children}) => {
  const services = {
    aurora: {
      name: 'Aurora',
      resource: 'cluster',
      id: 'cluster-xxxxxxxxxxxxxx'
    },
    rds: {
      name: 'RDS',
      resource: 'instance',
      id: 'db-xxxxxxxxxxxxxx'
    }
  };
  const createUserStatements = {
    postgres: `CREATE USER clickpipes_iam_user;
GRANT rds_iam TO clickpipes_iam_user;`,
    mysql: `CREATE USER 'clickpipes_iam_user' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';`
  };
  const svc = services[String(service).toLowerCase()];
  const createUserSql = createUserStatements[String(engine).toLowerCase()];
  if (!svc) throw new Error(`Unsupported IAM authentication service: ${service}`);
  if (!createUserSql) throw new Error(`Unsupported IAM authentication engine: ${engine}`);
  return <>
      <p>
        Instead of a password, you can authenticate the ClickPipes user with an AWS IAM role. This lets ClickPipes connect to your Amazon {svc.name} {svc.resource} without storing database credentials.
      </p>

      <h4 id="enable-iam-authentication">Enable IAM authentication</h4>

      <ol>
        <li>Log in to your AWS account and go to the {svc.name} {svc.resource} you want to configure.</li>
        <li>Click <strong>Modify</strong>.</li>
        <li>Scroll to the <strong>Database authentication</strong> section.</li>
        <li>Select <strong>Password and IAM database authentication</strong>.</li>
        <li>Click <strong>Continue</strong>.</li>
        <li>Review the changes and select <strong>Apply immediately</strong>.</li>
      </ol>

      <h4 id="create-database-user">Create the ClickPipes user</h4>

      <p>Create the ClickPipes user with IAM authentication enabled, then grant it the same schema and replication privileges shown above:</p>

      <CodeBlock language="sql">{createUserSql}</CodeBlock>

      {children}

      <h4 id="obtaining-the-clickhouse-service-iam-role-arn">Obtain the ClickHouse service IAM role ARN</h4>

      <ol>
        <li>Log in to your ClickHouse Cloud account.</li>
        <li>Select the ClickHouse service you want to connect.</li>
        <li>Select the <strong>Settings</strong> tab.</li>
        <li>Scroll to the <strong>Network security information</strong> section at the bottom of the page.</li>
        <li>Copy the service's <strong>Service role ID (IAM)</strong> value, shown below.</li>
      </ol>

      <Frame>
        <img src="/images/cloud/security/secures3_arn.webp" alt="Service role ID (IAM) value in the Network security information section" />
      </Frame>

      <p>This value is your <code>{'{ClickHouse_IAM_ARN}'}</code> — the role ClickPipes uses to access your {svc.name} {svc.resource}.</p>

      <h4 id="obtaining-the-rds-resource-id">Obtain the resource ID</h4>

      <ol>
        <li>Log in to your AWS account and go to the {svc.name} {svc.resource} you want to configure.</li>
        <li>Select the <strong>Configuration</strong> tab.</li>
        <li>Note the <strong>Resource ID</strong> value — it looks like <code>{svc.id}</code>. This is your <code>{'{RDS_RESOURCE_ID}'}</code>, which you reference in the permissions policy.</li>
      </ol>

      <h4 id="manually-create-iam-role">Create the IAM role</h4>

      <ol>
        <li>Log in to your AWS account with an IAM user that has permission to create and manage IAM roles.</li>
        <li>Open the IAM console.</li>
        <li>
          Create a new IAM role with the following trust and permissions policies.

          <p>Trust policy (replace <code>{'{ClickHouse_IAM_ARN}'}</code> with the IAM role ARN of your ClickHouse instance):</p>

          <CodeBlock language="json">{`{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "{ClickHouse_IAM_ARN}"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:TagSession"
      ]
    }
  ]
}`}</CodeBlock>

          <p>Permissions policy (replace <code>{'{RDS_RESOURCE_ID}'}</code> with the resource ID of your {svc.name} {svc.resource}, <code>{'{RDS_REGION}'}</code> with its region, and <code>{'{AWS_ACCOUNT}'}</code> with your AWS account ID):</p>

          <CodeBlock language="json">{`{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "rds-db:connect"
      ],
      "Resource": [
        "arn:aws:rds-db:{RDS_REGION}:{AWS_ACCOUNT}:dbuser:{RDS_RESOURCE_ID}/clickpipes_iam_user"
      ]
    }
  ]
}`}</CodeBlock>
        </li>
        <li>Once the role is created, copy its ARN. This is your <code>{'{RDS_ACCESS_IAM_ROLE_ARN}'}</code>.</li>
      </ol>

      <p>You can now use this IAM role to authenticate with your {svc.name} {svc.resource} from ClickPipes.</p>
    </>;
};

export const Image = ({img, alt, size = "lg"}) => {
  const normalizedSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
  return <div className={`ch-image-${normalizedSize}`}>
      <Frame>
        <img src={img} alt={alt} />
      </Frame>
    </div>;
};

<div id="supported-postgres-versions">
  ## Versões compatíveis do Postgres
</div>

O ClickPipes oferece suporte ao Postgres versão 12 e posteriores.

<div id="enable-logical-replication">
  ## Habilite a replicação lógica
</div>

Você pode pular esta seção se a sua instância do RDS já tiver a seguinte configuração definida:

* `rds.logical_replication = 1`

Essa configuração geralmente já vem pré-configurada se você já usou outra ferramenta de replicação de dados.

```text theme={null}
postgres=> SHOW rds.logical_replication ;
 rds.logical_replication
-------------------------
 on
(1 row)
```

Caso ainda não esteja configurado, siga estas etapas:

1. Crie um novo grupo de parâmetros para a sua versão do Postgres com as configurações necessárias:
   * Defina `rds.logical_replication` como 1

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/parameter_group_in_blade.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=fc09fae739bd271f51157b919ec4079e" alt="Onde encontrar grupos de parâmetros no RDS?" size="lg" border width="1800" height="819" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/parameter_group_in_blade.webp" />

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/change_rds_logical_replication.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=ab9ebf451918ea46d2f3696e36e5b332" alt="Alterando rds.logical_replication" size="lg" border width="1800" height="795" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/change_rds_logical_replication.webp" />

2. Aplique o novo grupo de parâmetros ao seu banco de dados RDS Postgres

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/modify_parameter_group.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=28151b7458c492a53092c800d6c70c35" alt="Modificando o RDS Postgres com o novo grupo de parâmetros" size="lg" border width="1800" height="1352" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/modify_parameter_group.webp" />

3. Reinicie a sua instância do RDS para aplicar as alterações

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/reboot_rds.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=9189cc820a053ed0de6f77234abcff75" alt="Reiniciando o RDS Postgres" size="lg" border width="1800" height="757" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/reboot_rds.webp" />

<div id="configure-database-user">
  ## Configurar o usuário do banco de dados
</div>

Conecte-se à sua instância do RDS Postgres como usuário administrador e execute os seguintes comandos:

1. Crie um usuário dedicado para o ClickPipes:

   ```sql theme={null}
   CREATE USER clickpipes_user PASSWORD 'some-password';
   ```

2. Conceda acesso somente leitura no nível do schema ao usuário criado na etapa anterior. O exemplo abaixo mostra as permissões para o schema `public`. Repita esses comandos para cada schema que contenha tabelas que você deseja replicar:

   ```sql theme={null}
   GRANT USAGE ON SCHEMA "public" TO clickpipes_user;
   GRANT SELECT ON ALL TABLES IN SCHEMA "public" TO clickpipes_user;
   ALTER DEFAULT PRIVILEGES IN SCHEMA "public" GRANT SELECT ON TABLES TO clickpipes_user;
   ```

3. Conceda privilégios de replicação ao usuário:

   ```sql theme={null}
   GRANT rds_replication TO clickpipes_user;
   ```

4. Crie uma [publicação](https://www.postgresql.org/docs/current/logical-replication-publication.html) com as tabelas que você deseja replicar. Recomendamos fortemente incluir na publicação apenas as tabelas necessárias para evitar sobrecarga de desempenho.

<Warning>
  Qualquer tabela incluída na publicação deve ter uma **chave primária** definida *ou* ter a **identidade de réplica** configurada como `FULL`. Consulte as [FAQs do Postgres](/pt-BR/integrations/clickpipes/postgres/faq#how-should-i-scope-my-publications-when-setting-up-replication) para ver orientações sobre escopo.
</Warning>

* Para criar uma publicação para tabelas específicas:

  ```sql theme={null}
  CREATE PUBLICATION clickpipes FOR TABLE table_to_replicate, table_to_replicate2;
  ```

  * Para criar uma publicação para todas as tabelas em um schema específico:

    ```sql theme={null}
    CREATE PUBLICATION clickpipes FOR TABLES IN SCHEMA "public";
    ```

A publicação `clickpipes` define o conjunto de tabelas cujos eventos de alteração serão transmitidos ao ClickPipes. Recomendamos não usar `FOR ALL TABLES`, a menos que você pretenda replicar todas as tabelas, pois incluir tabelas desnecessárias aumenta o tráfego de WAL do Postgres para o ClickPipes e reduz a eficiência geral da replicação.

<div id="iam-authentication">
  ### Usando autenticação IAM (opcional)
</div>

<IAMAuthentication engine="postgres" service="rds">
  <Note>
    A autenticação IAM para replicação exige que o parâmetro `rds.iam_auth_for_replication` esteja definido como `1`. Há suporte para isso a partir do PostgreSQL 11; em versões anteriores, só é possível executar `Initial Load Only` no ClickPipes.
  </Note>
</IAMAuthentication>

<div id="configure-network-access">
  ## Configurar o acesso à rede
</div>

<div id="ip-based-access-control">
  ### Controle de acesso por IP
</div>

Se você quiser restringir o tráfego para sua instância do RDS, adicione os [IPs NAT estáticos documentados](/pt-BR/integrations/clickpipes/networking/static-ips) às `Inbound rules` do grupo de segurança do RDS.

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/security_group_in_rds_postgres.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=94cc4fa3069d9cd9a68aef2be77d731a" alt="Onde encontrar o grupo de segurança no RDS Postgres?" size="lg" border width="1800" height="707" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/security_group_in_rds_postgres.webp" />

<Image img="https://mintcdn.com/private-7c7dfe99-trino-dialect/ZEyvJTCdFXKmprnu/images/integrations/data-ingestion/clickpipes/postgres/source/rds/edit_inbound_rules.webp?fit=max&auto=format&n=ZEyvJTCdFXKmprnu&q=85&s=7e5852a4a8a42c9a438075b917532273" alt="Editar as regras de entrada do grupo de segurança acima" size="lg" border width="1800" height="935" data-path="images/integrations/data-ingestion/clickpipes/postgres/source/rds/edit_inbound_rules.webp" />

<div id="private-access-via-aws-privatelink">
  ### Acesso privado via AWS PrivateLink
</div>

Para se conectar à sua instância do RDS por uma rede privada, você pode usar o AWS PrivateLink. Siga nosso [guia de configuração do AWS PrivateLink para ClickPipes](/pt-BR/resources/support-center/knowledge-base/cloud-services/aws-privatelink-setup-for-clickpipes) para configurar a conexão.

<div id="workarounds-for-rds-proxy">
  ### Soluções alternativas para o RDS Proxy
</div>

O RDS Proxy não oferece suporte a conexões de replicação lógica. Se você tiver endereços IP dinâmicos no RDS e não puder usar um nome DNS ou uma função Lambda, aqui estão algumas alternativas:

1. Usando um cron job, resolva periodicamente o IP do endpoint do RDS e atualize o NLB se ele tiver mudado.
2. Usando notificações de eventos do RDS com EventBridge/SNS: acione atualizações automaticamente com notificações de eventos do AWS RDS.
3. EC2 estável: implante uma instância do EC2 para atuar como um serviço de polling ou proxy baseado em IP.
4. Automatize o gerenciamento de endereços IP usando ferramentas como Terraform ou CloudFormation.

<div id="whats-next">
  ## Próximos passos
</div>

Agora você pode [criar seu ClickPipe](/pt-BR/integrations/clickpipes/postgres/index) e começar a fazer a ingestão de dados da sua instância do Postgres para o ClickHouse Cloud.
Anote os detalhes da conexão que você usou ao configurar sua instância do Postgres, pois precisará deles durante o processo de criação do ClickPipe.
