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

# Download S3 objects with a Function

> Store AWS credentials in a Secret, bind them to a Function, and download S3 text into a computed column with Boto3.

Enterprise only

This tutorial downloads a small UTF-8 text object from a private S3 bucket into
a LanceDB column. You create a Secret, register a Python Function that reads it,
then refresh the column and read the downloaded text.

The AWS credentials authorize the Function's requests to your source bucket.
LanceDB manages access to the table's own storage separately. Registering this
Secret does not configure table storage or a storage integration.

## Prepare the deployment and source object

You need:

* A LanceDB Enterprise deployment with Functions and Secrets enabled, including
  [KMS configuration](https://docs.lancedb.com/oss/v0-42-1/enterprise/deployment/kms) for Secrets.
* The Python SDK version supported by your deployment, with `pyarrow` installed
  in your local Python environment.
* An existing database and root namespace (`public`). Use new object names for
  this tutorial; creating an existing Secret or table fails.
* A small UTF-8 text object in S3. The AWS identity needs `s3:GetObject` on that
  object. For an object encrypted with SSE-KMS, it also needs `kms:Decrypt` and
  permission through the key policy. Workers need network access to S3.

Set these variables in the process running the Python examples, loading
credentials from your credential manager rather than placing values in source:

| Variable | Value |
| - | - |
| `LANCEDB_URI` | `db://s3_tutorial`, using your existing database name |
| `LANCEDB_API_KEY` | Your LanceDB credential |
| `LANCEDB_REGION` | Your LanceDB deployment region |
| `LANCEDB_HOST_OVERRIDE` | Your HTTPS Enterprise endpoint |
| `LANCEDB_SQL_HOST_OVERRIDE` | Your Flight SQL endpoint, such as `grpc+tls://your-sql-endpoint:10026` |
| `AWS_ACCESS_KEY_ID` | The source bucket identity's access key ID |
| `AWS_SECRET_ACCESS_KEY` | Its secret access key |
| `AWS_SESSION_TOKEN` | Its session token, required for temporary AWS credentials; omit for long-lived keys |
| `S3_REGION` | The source bucket's AWS region |
| `S3_BUCKET` | The source bucket name |
| `S3_KEY` | The text object's key, such as `examples/hello.txt` |

Run the Python blocks in order in the same script or session. The worker installs
Boto3 from the Function's dependency declaration below; your local process does
not need Boto3.

## Grant access

An administrator grants the tutorial principal access to the existing database
and namespace, and permission to create its objects. For an existing role named
`s3_ingest`, run this SQL in the tutorial database, replacing the database and
role names as needed:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
GRANT USAGE ON DATABASE s3_tutorial TO ROLE s3_ingest;
GRANT USAGE, CREATE TABLE, CREATE SECRET, CREATE FUNCTION ON SCHEMA public TO ROLE s3_ingest;
```

Use a LanceDB credential acting under that role for the Python steps. The creator
owns the new Secret, Function, and table. When different principals own or use
these objects, the required privileges are:

| Operation | Required object privilege |
| - | - |
| Register a Function bound to a Secret | `CREATE FUNCTION` on the namespace and `USAGE` on the Secret |
| Add a Function column | `OWNERSHIP` on the table, `USAGE` on the Function and its Secret |
| Refresh that column | `UPDATE` on the table, `USAGE` on the Function and its Secret |
| Read the populated column | `SELECT` on the table |
| Alter the Secret | `UPDATE` on the Secret |

All operations also require `USAGE` on the containing database and namespaces.
For example, after creating the objects, grant another existing role permission
to use the Secret with:

```sql theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
GRANT USAGE ON SECRET public.s3_download_credentials TO ROLE s3_refresh;
```

A role reading a populated column does not run the Function or need its Secret.
See [privileges](https://docs.lancedb.com/oss/v0-42-1/governance/privileges.md#sql) for the remaining grant syntax.

## Connect and create the Secret

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
import json
import os

import lancedb
import pyarrow as pa
from lancedb import EnvVarSecret, col, function

db = lancedb.connect(
    uri=os.environ["LANCEDB_URI"],
    api_key=os.environ["LANCEDB_API_KEY"],
    region=os.environ["LANCEDB_REGION"],
    host_override=os.environ["LANCEDB_HOST_OVERRIDE"],
    sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"],
)


def aws_credentials_json():
    credentials = {
        "aws_access_key_id": os.environ["AWS_ACCESS_KEY_ID"],
        "aws_secret_access_key": os.environ["AWS_SECRET_ACCESS_KEY"],
    }
    if os.environ.get("AWS_SESSION_TOKEN"):
        credentials["aws_session_token"] = os.environ["AWS_SESSION_TOKEN"]
    return json.dumps(credentials)


db.create_secret("s3_download_credentials", aws_credentials_json())
```

The Secret contains one JSON string so the key pair and session token can be
altered together. Its value must fit your deployment's
[Secret size limit](https://docs.lancedb.com/oss/v0-42-1/management/secret.md#limits). The Function definition below
contains only the environment variable name; it does not capture this local
dictionary or its values.

## Define and register the Function

A class Function creates one S3 client per worker instance and reuses it for
that instance's rows. It reads credentials through its declared Secret binding.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
@function(
    name="download_s3_text",
    pip=["boto3==1.40.0", "pyarrow"],
    python_version="3.12",
)
class DownloadS3Text:
    def __init__(self, region: str):
        import json
        import os

        import boto3

        credentials = json.loads(os.environ["S3_DOWNLOAD_CREDENTIALS"])
        session = boto3.session.Session(
            region_name=region,
            aws_access_key_id=credentials["aws_access_key_id"],
            aws_secret_access_key=credentials["aws_secret_access_key"],
            aws_session_token=credentials.get("aws_session_token"),
        )
        self.s3 = session.client("s3")

    def __call__(self, bucket: str, key: str) -> str:
        from contextlib import closing

        response = self.s3.get_object(Bucket=bucket, Key=key)
        with closing(response["Body"]) as body:
            return body.read().decode("utf-8")


download = db.create_function_async(
    DownloadS3Text,
    secrets=[
        EnvVarSecret(
            secret_name="s3_download_credentials",
            env_variable="S3_DOWNLOAD_CREDENTIALS",
        )
    ],
).wait()
```

Registration builds the remote environment and returns an immutable Function
version after the build succeeds. Imports and credential reads happen inside
the worker, after Secret delivery. The explicit Boto3 session uses the bound
credentials for source downloads. It does not rely on a worker role, a local
AWS profile, or table storage credentials.

## Add, refresh, and read the column

The Function's `str` parameters require non-nullable string input columns.
Its `region` initialization parameter is a fixed value for this column binding.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
schema = pa.schema(
    [
        pa.field("bucket", pa.string(), nullable=False),
        pa.field("key", pa.string(), nullable=False),
    ]
)
table = db.create_table(
    "s3_text_objects",
    [{"bucket": os.environ["S3_BUCKET"], "key": os.environ["S3_KEY"]}],
    schema=schema,
)
table.add_columns(
    {
        "content": download(
            bucket=col("bucket"),
            key=col("key"),
            region=os.environ["S3_REGION"],
        )
    },
    auto_refresh_enabled=False,
)

result = table.refresh_column_async("content").wait()
assert result.rows_failed == 0
assert result.rows_remaining == 0

table.checkout_latest()
rows = table.search().select(["bucket", "key", "content"]).to_arrow().to_pylist()
print(rows)
```

If the source object contains `Hello from S3!`, the row's `content` contains
that text. `add_columns` declares an empty output column; automatic refresh is
disabled here so the explicit refresh performs the download. Subsequent reads
return the stored text without contacting S3. Updating the source object does
not automatically update an already populated column.

This example reads each complete object into worker memory and decodes UTF-8.
Use small text objects for the tutorial. Binary files need a different output
schema and decoding logic; large objects need a suitable streaming or blob
workflow. AWS request errors and invalid UTF-8 propagate as Function failures.

## Alter credentials and handle expiry

After loading a complete replacement credential set into this Python process's
environment, replace the Secret's JSON value:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
db.alter_secret("s3_download_credentials", aws_credentials_json())
```

Set `AWS_SESSION_TOKEN` from the same temporary credential set as the new keys.
Remove an old session token when switching to long-lived keys. Updating a
parent shell's environment does not update an already running Python process.

Alteration keeps the same Secret name, Function version, and column binding.
Future jobs capture the replacement value. A running job and its retries keep
the credential value captured for that job; alteration does not replace their
client credentials or recompute existing output rows.

Temporary credentials passed explicitly to Boto3 do not renew automatically.
Choose a credential lifetime that covers the complete refresh, including
retries. If AWS expires or revokes those credentials, subsequent S3 requests
can fail even after the Secret has been altered. Split long backfills into jobs
that fit the credential lifetime, renewing credentials between jobs.
After replacing an expired credential, submit a new refresh for unfilled rows
so it captures the new value. See
[refresh behavior](https://docs.lancedb.com/oss/v0-42-1/feature-engineering/refresh-column.md) for recomputation and
retry controls.

Dropping a Secret prevents future jobs from resolving it, but does not recall
credentials already delivered to running work. Revoke the credential in AWS
when immediate revocation is required. Never print, return, or log the Secret's
JSON or its fields; redaction does not protect transformed values. See
[Secret delivery](https://docs.lancedb.com/oss/v0-42-1/curation/vend-secret.md) for more detail.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.