

# Integrating with Snowflake Horizon Catalog

You can sync metadata from a Snowflake Horizon Catalog into the AWS Glue Data Catalog. You create a Snowflake connection and register it with Lake Formation. Then you create a federated catalog on it and turn on sync. You can also set up query access so that analytics engines query the Snowflake data through the catalog. This topic uses the AWS CLI. For more information, see [Integrating with external catalogs](catalog-external-catalogs.md).

Before you start, complete the prerequisites, including the two IAM roles and the Secrets Manager permissions. For more information about the prerequisites, see [Prerequisites for integrating with external catalogs](catalog-external-catalogs-prerequisites.md).

## Create the connection
<a name="catalog-external-catalogs-snowflake-connection"></a>

A Snowflake connection has the type `SNOWFLAKE`. It stores the host and warehouse for your Snowflake account and the ARN of an AWS Secrets Manager secret that holds your credentials. The connection stores only the secret ARN, not the secret value. You can authenticate with key pair authentication or with the OAuth 2.0 authorization code grant.

Set the following properties in the connection:
+ `HOST`. The host for your Snowflake account, in the form `{{account}}.snowflakecomputing.com`. Don't include a scheme such as `https://`.
+ `WAREHOUSE`. The Snowflake warehouse that runs the queries. Athena requires a warehouse to query the data.
+ `TABLE_DEPTH`. Set this to `3`. This integration requires a table depth of 3.
+ `DATABASE`. Optional at a table depth of 3. Set it only when you use a table depth of 2.

Table depth sets how AWS Glue maps Snowflake objects to the catalog name. A depth of 2 maps `schema.table` and needs a `DATABASE` value to fix the database. A depth of 3 maps `database.schema.table` and brings the whole database, with all of its schemas and tables, into scope. This integration uses a depth of 3, so set `TABLE_DEPTH` to `3`.

**Protect secret values**  
The secret holds credentials. Create it from a file, keep the file out of shared logs, and delete the file after the secret exists.

### Key pair authentication
<a name="catalog-external-catalogs-snowflake-connection-key-pair"></a>

For key pair authentication, store the Snowflake user name and an unencrypted PKCS\#8 private key in a secret. Then create a connection that uses the `CUSTOM` authentication type.

1. Save the secret value to a file named `key-pair-secret.json`.

   ```json
   {
       "sfUser": "{{snowflake-user}}",
       "pem_private_key": "-----BEGIN PRIVATE KEY-----\n{{private-key-body}}\n-----END PRIVATE KEY-----"
   }
   ```

   Create the secret. Note the secret ARN from the response.

   ```bash
   aws secretsmanager create-secret \
       --name {{snowflake-secret-name}} \
       --secret-string file://key-pair-secret.json
   ```

1. Save the following connection definition to a file named `connection.json`. Use the secret ARN from the previous step.

   ```json
   {
       "CatalogId": "{{account-id}}",
       "ConnectionInput": {
           "Name": "{{connection-name}}",
           "ConnectionType": "SNOWFLAKE",
           "ConnectionProperties": {
               "HOST": "{{account}}.snowflakecomputing.com",
               "PORT": "443",
               "WAREHOUSE": "{{warehouse}}",
               "TABLE_DEPTH": "3"
           },
           "AuthenticationConfiguration": {
               "AuthenticationType": "CUSTOM",
               "SecretArn": "{{secret-arn}}"
           }
       }
   }
   ```

   Create the connection. Note the connection ARN for the next steps.

   ```bash
   aws glue create-connection --cli-input-json file://connection.json
   ```

### OAuth 2.0 authorization code authentication
<a name="catalog-external-catalogs-snowflake-connection-oauth"></a>

For OAuth 2.0, store the client secret of your Snowflake OAuth integration in a secret. Then create a connection that uses the `OAUTH2` authentication type with the authorization code grant.

1. Save the secret value to a file named `oauth-secret.json`.

   ```json
   {
       "USER_MANAGED_CLIENT_APPLICATION_CLIENT_SECRET": "{{client-secret}}"
   }
   ```

   Create the secret. Note the secret ARN from the response.

   ```bash
   aws secretsmanager create-secret \
       --name {{snowflake-secret-name}} \
       --secret-string file://oauth-secret.json
   ```

1. Save the following connection definition to a file named `connection.json`. Use the secret ARN from the previous step.

   ```json
   {
       "CatalogId": "{{account-id}}",
       "ConnectionInput": {
           "Name": "{{connection-name}}",
           "ConnectionType": "SNOWFLAKE",
           "ConnectionProperties": {
               "HOST": "{{account}}.snowflakecomputing.com",
               "PORT": "443",
               "WAREHOUSE": "{{warehouse}}",
               "TABLE_DEPTH": "3"
           },
           "AuthenticationConfiguration": {
               "AuthenticationType": "OAUTH2",
               "SecretArn": "{{secret-arn}}",
               "OAuth2Properties": {
                   "OAuth2GrantType": "AUTHORIZATION_CODE",
                   "TokenUrl": "https://{{account}}.snowflakecomputing.com/oauth/token-request",
                   "OAuth2ClientApplication": {
                       "UserManagedClientApplicationClientId": "{{client-id}}"
                   },
                   "TokenUrlParametersMap": {
                       "scope": "refresh_token"
                   },
                   "AuthorizationCodeProperties": {
                       "AuthorizationCode": "{{authorization-code}}",
                       "RedirectUri": "{{redirect-uri}}"
                   }
               }
           }
       }
   }
   ```

   You provide the OAuth tokens in one of two ways. In the preceding example, you send an `AuthorizationCodeProperties` object with an authorization code and redirect URI, and AWS Glue exchanges them for the tokens. To receive a refresh token, request the `refresh_token` scope in `TokenUrlParametersMap`. Without it, Snowflake doesn't issue a refresh token.

   If you already have an access token and a refresh token, add them to the secret as `ACCESS_TOKEN` and `REFRESH_TOKEN`, and omit the `AuthorizationCodeProperties` object. AWS Glue refreshes the access token and stores it in the same secret.

   Create the connection. Note the connection ARN for the next steps.

   ```bash
   aws glue create-connection --cli-input-json file://connection.json
   ```

**Note**  
If you plan to turn on lineage sync for this connection, set `HOST` to the organization and account name form `{{orgname}}-{{accountname}}.snowflakecomputing.com`. Lineage sync doesn't accept a Snowflake connection that uses the account locator host. For more information about lineage sync, see [Managing an external catalog integration](catalog-external-catalogs-manage.md).

## Set up discovery and asset cataloging
<a name="catalog-external-catalogs-snowflake-cataloging"></a>

After you create the connection, register it with Lake Formation, create a top-level catalog on it, grant the crawler role access, and turn on sync. AWS Glue then runs a managed crawler that writes the Snowflake metadata into the Data Catalog as synced assets. Follow the steps in order. The crawler role needs access to the catalog before AWS Glue creates the managed crawler.

1. Register the connection with Lake Formation for federation. You must register the connection before you can create a federated catalog on it. If you skip this step, `create-catalog` fails with the error `The data source [{{connection-arn}}] is not registered.` Save the following to a file named `register.json`.

   ```json
   {
       "ResourceArn": "{{connection-arn}}",
       "RoleArn": "{{credential-vending-role-arn}}",
       "UseServiceLinkedRole": false,
       "WithFederation": true,
       "WithPrivilegedAccess": true
   }
   ```

   ```bash
   aws lakeformation register-resource --cli-input-json file://register.json
   ```

1. Create the top-level catalog for the connection. AWS Glue creates one top-level catalog for each connection. Each Snowflake database that the connection can access appears as a child catalog under it. Create the catalog without a `SyncConfiguration` first, so that you can grant the crawler role access before sync starts. Save the following to a file named `catalog.json`.

   ```json
   {
       "Name": "{{catalog-name}}",
       "CatalogInput": {
           "CreateTableDefaultPermissions": [],
           "CreateDatabaseDefaultPermissions": [],
           "FederatedCatalog": {
               "ConnectionName": "{{connection-name}}",
               "ConnectionType": "SNOWFLAKE"
           }
       }
   }
   ```

   ```bash
   aws glue create-catalog --cli-input-json file://catalog.json
   ```

1. Grant the crawler role the Lake Formation `DESCRIBE` permission on the catalog. Do this before you turn on sync, because the crawler role needs access to the catalog before AWS Glue creates the managed crawler.

   ```bash
   aws lakeformation grant-permissions \
       --principal DataLakePrincipalIdentifier={{crawler-role-arn}} \
       --resource '{"Catalog": {"Id": "{{account-id}}:{{catalog-name}}"}}' \
       --permissions DESCRIBE
   ```

   For more information about granting Lake Formation permissions, see [Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html) in the *Lake Formation Developer Guide*.

1. Turn on sync by adding a `SyncConfiguration` to the catalog with `update-catalog`. Include `ConnectionName` and `ConnectionType` in the update, along with the `SyncConfiguration`. Set `RefreshIntervalMinutes` to `1440` for a 24-hour interval or `10080` for a 7-day interval. Save the following to a file named `update-catalog.json`.

   ```json
   {
       "CatalogId": "{{account-id}}:{{catalog-name}}",
       "CatalogInput": {
           "CreateTableDefaultPermissions": [],
           "CreateDatabaseDefaultPermissions": [],
           "FederatedCatalog": {
               "ConnectionName": "{{connection-name}}",
               "ConnectionType": "SNOWFLAKE",
               "SyncConfiguration": {
                   "RoleArn": "{{crawler-role-arn}}",
                   "AssetsSyncConfiguration": {
                       "Status": "ENABLED",
                       "RefreshIntervalMinutes": 1440
                   }
               }
           }
       }
   }
   ```

   ```bash
   aws glue update-catalog --cli-input-json file://update-catalog.json
   ```

1. AWS Glue creates a managed crawler for the catalog. Check the crawler status with `get-catalog` until it reaches `PROVISIONED`. The crawler takes about 20 seconds to reach `PROVISIONED`.

   ```bash
   aws glue get-catalog \
       --catalog-id {{account-id}}:{{catalog-name}} \
       --query 'Catalog.FederatedCatalog.SyncConfiguration.AssetsSyncConfiguration.ManagedCrawlerDetails'
   ```

   The response shows the crawler ARN and status.

   ```json
   {
       "CrawlerArn": "arn:aws:glue:{{region}}:{{account-id}}:crawler/catalog-sync-assets-{{id}}",
       "Status": "PROVISIONED"
   }
   ```

After the crawler reaches `PROVISIONED`, AWS Glue starts the first crawl automatically. The crawler then runs on the interval you set and writes synced assets to the Data Catalog. The start time of a crawl isn't guaranteed. For more information about finding synced assets, see [Integrating with external catalogs](catalog-external-catalogs.md). To change the interval, turn off sync, or turn on lineage sync, see [Managing an external catalog integration](catalog-external-catalogs-manage.md).

## Set up query access from analytics engines
<a name="catalog-external-catalogs-snowflake-query-access"></a>

After the metadata is in the Data Catalog, analytics engines such as Athena, Amazon EMR, and AWS Glue with Spark can query the Snowflake data through the federated catalog. The way AWS Glue provides credentials to the engine depends on the credential vending mode of the connection.

Set the `CREDENTIAL_VENDING_MODE` property in the connection to one of the following values:
+ `AWS_VENDED` (default). Lake Formation assumes the role that you registered with it and vends temporary credentials to the engine.
+ `SOURCE_VENDED`. Snowflake vends the credentials. Source-vended credentials are available to first-party engines only. Amazon EMR and AWS Glue with Spark act as third-party engines and can't use source-vended credentials.

Set the mode in the connection properties when you create or update the connection. The following example uses AWS-vended credentials.

```json
"ConnectionProperties": {
    "CREDENTIAL_VENDING_MODE": "AWS_VENDED"
}
```

The following example uses source-vended credentials.

```json
"ConnectionProperties": {
    "CREDENTIAL_VENDING_MODE": "SOURCE_VENDED"
}
```

### Query from Athena
<a name="catalog-external-catalogs-snowflake-query-access-athena"></a>

**Important**  
To query a Snowflake federated catalog with Athena, the connection must include a spill bucket and prefix. Athena writes intermediate results to this location in Amazon S3. Without a spill bucket and prefix, Athena federated queries on the catalog fail.

Set the `AthenaProperties` object in the connection with the spill bucket and prefix.

```json
"AthenaProperties": {
    "spill_bucket": "{{amzn-s3-demo-bucket}}",
    "spill_prefix": "{{athena-spill-prefix}}"
}
```

Athena can query all Snowflake object types, including native tables, views, and Iceberg tables.

### Query from Spark
<a name="catalog-external-catalogs-snowflake-query-access-spark"></a>

AWS Glue with Spark and Amazon EMR don't support multi-catalog access to a third-party federated catalog directly. To query Snowflake data from Spark, create a database resource link that points to a database in the child catalog, then query the resource link. Save the following to a file named `resource-link.json`.

```json
{
    "CatalogId": "{{account-id}}",
    "DatabaseInput": {
        "Name": "{{resource-link-name}}",
        "TargetDatabase": {
            "CatalogId": "{{account-id}}:{{catalog-name}}:{{snowflake-database-name}}",
            "DatabaseName": "{{snowflake-schema-name}}"
        }
    }
}
```

```bash
aws glue create-database --cli-input-json file://resource-link.json
```

From Spark, you can query Iceberg tables in the Snowflake data. You can't query native Snowflake tables or views from Spark. Use Athena for those object types.

## Considerations and limitations
<a name="catalog-external-catalogs-snowflake-considerations"></a>

Consider the following when you integrate with a Snowflake Horizon Catalog:
+ This integration uses a table depth of 3, which maps `database.schema.table` and brings the whole database into scope. A table depth of 2 maps `schema.table` and needs a `DATABASE` value in the connection.
+ Athena can query all Snowflake object types, including native tables, views, and Iceberg tables.
+ Athena federated queries on a Snowflake catalog require a spill bucket and prefix in the connection. For more information, see [Set up query access from analytics engines](#catalog-external-catalogs-snowflake-query-access).
+ AWS Glue with Spark and Amazon EMR require a database resource link to query Snowflake data. From Spark, you can query Iceberg tables only, not native tables or views.
+ Crawls retrieve all targets regardless of the casing set in the connection.
+ Source-vended credentials aren't available to AWS Glue with Spark or Amazon EMR.

For considerations that apply to all external catalog integrations, see [Considerations and limitations](catalog-external-catalogs-considerations.md).