# Connect Snowflake

Costfluent reads your Snowflake spend from the organization's daily usage in currency, signed in as
a service user you create for it with a key pair. One connection is one Snowflake organization, and
the cost of every account in it.

## How Costfluent connects

Costfluent stores the private key encrypted and never sends it anywhere: it signs a short-lived
token with it, valid for at most an hour, and runs read-only queries with that token over
Snowflake's SQL API. The queries read the view `SNOWFLAKE.ORGANIZATION_USAGE.USAGE_IN_CURRENCY_DAILY`
on the warehouse the setup script creates, as the service user's default role. The organization's
name is the connection's identity, so you do not enter it.

:::caution
Every query runs on your warehouse and uses your credits. The setup script creates an X-Small
warehouse that suspends after 60 seconds and puts it under a resource monitor, so a sync costs
about a minute of that warehouse and nothing can run it past its monthly quota
([What syncing costs](#what-syncing-costs)).
:::

## Prerequisites

1. The Owner or Integration owner organization role in Costfluent.
2. A Snowflake organization billed by Snowflake. An organization that signed its contract through a
   Snowflake reseller cannot read its usage in currency; upload its cost to a
   [custom provider](/connect/custom-provider) instead.
3. The organization account, which needs Enterprise Edition or higher, and a user there who holds
   the **GLOBALORGADMIN** and **ACCOUNTADMIN** roles. Without an organization account, an account
   with the ORGADMIN role enabled and a user there who holds **ACCOUNTADMIN** works too. Snowflake
   is phasing out ORGADMIN in such an account in favour of GLOBALORGADMIN in the organization
   account.
4. OpenSSL, to generate the key pair.

## Prepare Snowflake

### Generate the key pair

Generate a 2048-bit private key without a passphrase, `rsa_key.p8`, and its public key,
`rsa_key.pub`, on your own machine:

```bash
openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt
openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub
```

Costfluent needs the key unencrypted, because it signs with it on every sync. Keep `rsa_key.p8`
until you have pasted it into Costfluent, then delete it: Costfluent never shows it again, and
Snowflake holds only the public key. Print the public key on one line, without its first and last
lines, for the script:

```bash
grep -v -- '-----' rsa_key.pub | tr -d '\n'
```

### Run the setup script

<Stepper>

1. Sign in to Snowsight in the organization account, or in the ORGADMIN-enabled account, and open a
   SQL worksheet.
2. Run this script, with the one-line public key in place of `<PUBLIC_KEY>`. It creates a role, an
   X-Small warehouse under a monthly resource monitor of 20 credits, and the service user
   `COSTFLUENT`, which signs in with the key pair alone and runs every query as that role on that
   warehouse.

   ```sql
   USE ROLE ACCOUNTADMIN;

   CREATE ROLE COSTFLUENT_BILLING;

   CREATE WAREHOUSE COSTFLUENT_WH
     WAREHOUSE_SIZE = XSMALL
     AUTO_SUSPEND = 60
     AUTO_RESUME = TRUE
     INITIALLY_SUSPENDED = TRUE;

   CREATE RESOURCE MONITOR COSTFLUENT_MONITOR WITH
     CREDIT_QUOTA = 20
     TRIGGERS ON 100 PERCENT DO SUSPEND;

   ALTER WAREHOUSE COSTFLUENT_WH SET RESOURCE_MONITOR = COSTFLUENT_MONITOR;

   GRANT USAGE ON WAREHOUSE COSTFLUENT_WH TO ROLE COSTFLUENT_BILLING;

   CREATE USER COSTFLUENT
     TYPE = SERVICE
     DEFAULT_ROLE = COSTFLUENT_BILLING
     DEFAULT_WAREHOUSE = COSTFLUENT_WH
     RSA_PUBLIC_KEY = '<PUBLIC_KEY>';

   GRANT ROLE COSTFLUENT_BILLING TO USER COSTFLUENT;
   ```

3. Let the role read the organization's billing. In the organization account, the
   **GLOBALORGADMIN** role grants Snowflake's application role:

   ```sql
   USE ROLE GLOBALORGADMIN;

   GRANT APPLICATION ROLE SNOWFLAKE.ORGANIZATION_BILLING_VIEWER TO ROLE COSTFLUENT_BILLING;
   ```

   In an ORGADMIN-enabled account, **ACCOUNTADMIN** grants the database role of the same name
   instead:

   ```sql
   USE ROLE ACCOUNTADMIN;

   GRANT DATABASE ROLE SNOWFLAKE.ORGANIZATION_BILLING_VIEWER TO ROLE COSTFLUENT_BILLING;
   ```

4. Copy the account identifier, your organization's name and the account's name joined by a hyphen,
   which this query returns:

   ```sql
   SELECT CURRENT_ORGANIZATION_NAME() || '-' || CURRENT_ACCOUNT_NAME();
   ```

</Stepper>

The role can read the organization's billing views and use its own warehouse, and nothing else: no
database, schema or table of yours.

### What syncing costs

An X-Small warehouse uses one credit an hour, billed by the second with a minimum of 60 seconds each
time it resumes, and the script's warehouse suspends after 60 idle seconds. A sync therefore costs
about a minute of the warehouse, a sixtieth of a credit. At the daily default that is about half a
credit a month; syncing every hour, the most often a connection can, it is about twelve. The
monitor's 20 credits cover hourly syncs with room to spare and only ever stop runaway use: when the
warehouse reaches them, Snowflake suspends it until the first of the next month, and Costfluent's
syncs fail until then. You can lower the quota if you keep the daily default.

## Connect

<Stepper>

1. Open **Settings**, then **Integrations**, select **Snowflake**, and open the **Connect** tab.
2. Select "Add key pair", keep the suggested **Display name** or enter your own, and enter the
   account identifier into **Account identifier**, `COSTFLUENT` into **User name**, and the whole
   contents of `rsa_key.p8` into **Private key**. The account's URL works as the identifier too,
   and capitals are sent in lowercase.
3. Select "Test connection" to see each check, or "Connect" to save.

</Stepper>

Costfluent signs in, reads the organization's name and a row of its usage from the last year
before storing anything, so a connection that saves can read your cost. A second connection of the same
organization is refused. If Snowflake does not answer during that check, the connection is saved
anyway and checked again automatically.

## Data and freshness

Connecting imports as far back as your plan's backfill reaches, and at most six months
([Manage connections](/connect/manage-connections#how-it-behaves)). Older months collected on
request reach one year back, which is as long as Snowflake's documentation promises to keep the
view. Cost arrives by UTC day, in the currency your organization is billed in.

:::note
Snowflake publishes a day's usage up to 72 hours after the day ends, so the newest days arrive about
three days late, and a connection is not reported as late until then.
:::

:::note
Until Snowflake closes a month, its days can still change, for end-of-month adjustments and
credits, contract amendments or an account moving to another organization. Each sync reads the
running month again, and the previous month until the 15th of the month after it.
:::

:::caution
Customers who signed their Snowflake contract through a reseller cannot read the organization's
usage in currency: the view is empty for them. Upload that cost to a
[custom provider](/connect/custom-provider) instead.
:::

## Reporting dimensions

- **Account** is the Snowflake account the usage was consumed in, by its locator and name.
- **Region** is the account's region as Snowflake names it, such as `AWS_EU_CENTRAL_1`.
- **SKU** is Snowflake's service type, such as `WAREHOUSE_METERING`, `STORAGE` or `SNOWPIPE`, and
  **Service** the same type in words, such as `Warehouse Metering`.
- **Service category** follows the rating type: `Analytics` for compute, `Storage` for storage,
  `Networking` for data transfer, and `Other` for everything else.
- The quantity is in credits for compute and in terabytes for storage and data transfer.
- A rebate or support credit is a cost with the charge type `Credit`, priority support and a
  deployment fee are `Purchase`, and an adjustment is `Adjustment`.
- The tags `snowflake:balance_source` (such as `capacity`, `free usage` or `overage`) and
  `snowflake:service_level` (the account's edition) say how Snowflake drew and rated the usage.
- The billing account is the organization, and the billing period is the calendar month.

## Update or disconnect

### After connecting

The **Manage** tab lists the connection by its display name, with the organization's name under
**Organization ID**. Open the gear icon beside it to see whether the usage is still readable, which
workspaces the connection feeds, and which months have been imported. **Run checks** runs the
checks again on request.

### Rotating or removing access

A user holds two public keys at once, so a key is rotated without a gap. Generate a new key pair
as above, then, as **ACCOUNTADMIN**, give the user the new public key as its second key:

```sql
ALTER USER COSTFLUENT SET RSA_PUBLIC_KEY_2 = '<NEW_PUBLIC_KEY>';
```

Select **Update credentials** on the connection page and enter the same account identifier and
user name with the new private key. Once the checks pass, remove the old key:

```sql
ALTER USER COSTFLUENT UNSET RSA_PUBLIC_KEY;
```

For the next rotation, set `RSA_PUBLIC_KEY` and unset `RSA_PUBLIC_KEY_2`. Another organization's
account is refused.

To retire the connection, remove it in Costfluent, then drop the user, the warehouse, the resource
monitor and the role in Snowflake. Removing it erases the cost it imported
([Remove a connection](/connect/manage-connections#remove-a-connection)).

```sql
USE ROLE ACCOUNTADMIN;

DROP USER COSTFLUENT;
DROP WAREHOUSE COSTFLUENT_WH;
DROP RESOURCE MONITOR COSTFLUENT_MONITOR;
DROP ROLE COSTFLUENT_BILLING;
```

## Troubleshooting

- **A Snowflake account identifier, user name and private key are required.** One of the three
  fields is empty. Fill in all three.
- **A Snowflake account identifier is written `<organization name>-<account name>`, as
  `SELECT CURRENT_ORGANIZATION_NAME() || '-' || CURRENT_ACCOUNT_NAME()` returns it; a legacy account locator or a private link address is not
  supported.** The identifier field holds a legacy locator with a region (`xy12345.eu-central-1`),
  a private link address or the dotted form `myorg.myaccount`. Run the query in the setup steps and
  paste what it returns.
- **A Snowflake user name holds only letters, digits and the characters `_ $ . @ -`. Enter the name
  of the Costfluent service user.** The user name field holds a space or a quote. Enter
  `COSTFLUENT`, or the name you gave the user.
- **The private key is not a PEM key. Paste the whole contents of rsa_key.p8, from
  -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----.** Part of the key is missing. Paste the
  whole file.
- **The private key is encrypted. Generate it without a passphrase (openssl pkcs8 -topk8 -nocrypt)
  and paste that key.** The key was generated with a passphrase. Generate a new key pair as above,
  set its public key on the user, and paste the new private key.
- **The private key is in PKCS#1 form (BEGIN RSA PRIVATE KEY). Convert it with openssl pkcs8 -topk8
  -nocrypt and paste that key.** Convert it with
  `openssl pkcs8 -topk8 -inform PEM -in rsa_key.pem -out rsa_key.p8 -nocrypt` and paste
  `rsa_key.p8`.
- **The text is not a private key. Paste the contents of rsa_key.p8, not the public key.** The
  public key was pasted. Paste `rsa_key.p8`.
- **The private key has 1024 bits; Snowflake needs at least 2048.** Generate a new key pair with
  `openssl genrsa 2048` as above.
- **Snowflake refused this user and private key. Check the user name, and that the user's
  RSA_PUBLIC_KEY or RSA_PUBLIC_KEY_2 is the public half of this private key.** The user name is
  wrong, or the user holds another public key. Compare the user's `RSA_PUBLIC_KEY_FP` in
  `DESC USER COSTFLUENT` with
  `openssl rsa -pubin -in rsa_key.pub -outform DER | openssl dgst -sha256 -binary | openssl enc -base64`.
- **Snowflake refused the sign-in to account ... as ... Check the account identifier, and that no
  network policy blocks the user.** The message names the account, the user and Snowflake's error
  code. The identifier names another account, or a network policy on the account or the user lets
  it sign in only from your own addresses.
- **Snowflake did not name the organization of this account, so the connection cannot be
  identified.** Snowflake answered without the organization's name. Check that the identifier is the
  one the setup query returned.
- **The Snowflake user ... has no warehouse to run the read on ... Set its DEFAULT_WAREHOUSE to a
  warehouse its default role may use.** The user's default warehouse is missing, or its role may not
  use it. Run the script's `GRANT USAGE ON WAREHOUSE` statement, and check the user's
  `DEFAULT_WAREHOUSE` with `DESC USER COSTFLUENT`.
- **The default role of Snowflake user ... cannot read
  SNOWFLAKE.ORGANIZATION_USAGE.USAGE_IN_CURRENCY_DAILY ... Grant it the ORGANIZATION_BILLING_VIEWER
  role as the setup script does, in the organization account or an ORGADMIN-enabled account.** The
  role lacks the billing viewer role, or the account is neither the organization account nor
  ORGADMIN-enabled. Run step 3 of the setup script in that account, then select **Run checks**.
- **Snowflake returned no usage in currency for this organization in the last year. Organizations
  with a contract through a Snowflake reseller cannot read it; connect an organization billed by
  Snowflake directly, or upload its costs as a custom provider CSV.** A contract signed through a
  reseller hides the view's data. Upload the cost to a [custom provider](/connect/custom-provider)
  instead.
- **The supplied Snowflake key belongs to another organization than the one this connection was
  validated against.** Shown when updating credentials. Connect that organization as a new
  connection.
- **Syncs stop and the warehouse is suspended.** The resource monitor reached its quota. Raise it
  with `ALTER RESOURCE MONITOR COSTFLUENT_MONITOR SET CREDIT_QUOTA = <CREDITS>`, or wait for it to
  reset on the first of the month.
