Updated on 2026-11-06 GMT+08:00

Environment Variable Configuration

env_vars allows dynamic injection of environment variables into the Actor process during UDF invocation. This eliminates the need for creating redundant UDF definitions for different environment variables.

Basic Usage

The following code snippet shows only the usage of the env_vars parameter:

# Dataset API — Input dict.
ds = ds.map(
    fn="my_schema.data_loader",
    on=["url_col"],
    env_vars={"DATA_SOURCE": "obs://bucket/path", "REGION": "cn-north-4"},
)

# with_arguments — Input dict or a JSON string.
result = my_udf(t.col_a).with_arguments(
    env_vars={"DATA_SOURCE": "obs://bucket/path"},
)

Access the environment variables in the UDF using os.environ:

def my_udf(url: str) -> str:
    import os
    data_source = os.environ.get("DATA_SOURCE", "")
    return load_from(url, base=data_source)

Type Verification

Verify types in with_arguments() in Python.

Input

Behavior

env_vars={"KEY": "VALUE"}

Normal. Both the key and value are of the str type.

env_vars={1: "val"}

TypeError: keys must be str

env_vars={"key": 123}

TypeError: values must be str

env_vars={}

Equivalent to not setting the key. No ENV_VARS clause is generated.

env_vars='{"K":"V"}'

JSON string passthrough

env_vars='not json'

TypeError: must be valid JSON

env_vars=None

Default value. No ENV_VARS clause will be generated.

Key Format Constraints

The key of env_vars must comply with the POSIX specifications ^[a-zA-Z_][a-zA-Z0-9_]*$. The maximum length is 1,022 bytes. If the kernel is invalid, ERROR is returned.

Example Key

Valid

Description

MY_KEY

Yes

Standard POSIX key

_UNDERSCORE_KEY

Yes

It starts with an underscore (_).

KEY123

Yes

It contains digits, but the first character cannot be a digit.

1KEY

No

It starts with a digit.

MY-KEY

No

It contains hyphens (-).

MY.KEY

No

It contains periods (.).

MY=KEY

No

It contains equal signs (=).

my key

No

It contains spaces.

Safety Precautions

Avoiding sensitive credentials such as AK/SK in env_vars

# Forbidden — Transmitting credentials in plaintext through SQL statements may cause leaks.
my_udf(t.col).with_arguments(
    env_vars={"ACCESS_KEY_ID": "xxx", "SECRET_ACCESS_KEY": "yyy"}
)

# Forbidden — UDF_TEMP_AK/UDF_TEMP_SK is a reserved key for server credentials. Setting it will trigger an error.
my_udf(t.col).with_arguments(
    env_vars={"UDF_TEMP_AK": "xxx", "UDF_TEMP_SK": "yyy"}
)
# ERROR: env_vars key "UDF_TEMP_AK" conflicts with reserved server credentials. UDF invocation is terminated.

Using the Kernel IAM agency token for automatic injection

The kernel automatically obtains the temporary AK/SK using the IAM agency token and injects them as environment variables UDF_TEMP_AK, UDF_TEMP_SK, and UDF_TEMP_SECURITY_TOKEN. Non-credential configurations such as the OBS endpoint are passed through env_vars. The UDF reads the values through os.environ and uses them together with the esdk-obs-python SDK.
class ObsDataReader:
    """Read data from OBS.

    Credentials (UDF_TEMP_AK/SK/TOKEN) are automatically injected by
    the kernel via IAM delegation token — no client-side setup needed.
    UDF_OBS_ENDPOINT must be provided by the user via env_vars.
    """

    def __init__(self, bucket: str):
        self.bucket = bucket

    def _get_obs_config(self) -> tuple:
        """Read OBS config from env vars."""
        import os

        # Credentials — auto-injected by kernel, do NOT set these yourself
        ak = os.environ.get("UDF_TEMP_AK", "")
        sk = os.environ.get("UDF_TEMP_SK", "")
        token = os.environ.get("UDF_TEMP_SECURITY_TOKEN", "")

        # Endpoint — user-provided via env_vars
        endpoint = os.environ.get("UDF_OBS_ENDPOINT", "")

        if not ak or not sk:
            raise RuntimeError(
                "OBS credentials not available. "
                "Ensure IAM delegation token is configured on the server."
            )
        if not endpoint:
            raise RuntimeError(
                "OBS endpoint not configured. "
                "Pass it via env_vars: with_arguments(env_vars={'UDF_OBS_ENDPOINT': '...'})"
            )

        return ak, sk, token, endpoint

    def __call__(self, object_key: str) -> str:
        """Read an object from OBS and return its content as string."""
        from obs import ObsClient

        ak, sk, token, endpoint = self._get_obs_config()

        obs_client = ObsClient(
            access_key_id=ak,
            secret_access_key=sk,
            security_token=token,
            server=endpoint,
        )

        try:
            resp = obs_client.getObject(
                self.bucket, object_key, loadStreamInMemory=True
            )
            if resp.status >= 300:
                raise RuntimeError(
                    f"OBS read failed: status={resp.status}, reason={resp.reason}"
                )
            return resp.body.buffer.decode("utf-8")
        finally:
            obs_client.close()
Use method:
import pandas as pd
from aura_frame.multimodal import ai_lake

con = ai_lake.connect(
    aura_endpoint="*",
    aura_workspace_id="*",
    lf_catalog_name="*",
    access_key="*",
    secret_key="*",
    default_database="my_schema",
    use_single_cn_mode=True,
)
# Register the UDFs
try:
    con.create_scalar_function(ObsDataReader, name="obs_reader", database="my_schema")
    # --- Direct expression API ---
    t = con.from_pandas(pd.DataFrame({"object_key": [""]}))._table
    result = con.get_function("obs_reader", database="my_schema")(
        t.object_key
    ).with_arguments(
        bucket="my-data-bucket",
        env_vars={"UDF_OBS_ENDPOINT": "obs.cn-north-4.myhuaweicloud.com"},
    )
    # --- Dataset API ---
    ds = con.from_pandas(pd.DataFrame({"object_key": [""]}))
    ds = ds.map(
        fn="my_schema.obs_reader",
        on=["object_key"],
        bucket="my-data-bucket",
        as_col="content",
        env_vars={"UDF_OBS_ENDPOINT": "obs.cn-north-4.myhuaweicloud.com"},
    )
    ds.show()
finally:
    con.close()

Reserved keys for server credentials (Setting them in env_vars will trigger an error.)

Reserved Key

Purpose

UDF_TEMP_AK

Temporary access key

UDF_TEMP_SK

Temporary secret key

UDF_TEMP_SECURITY_TOKEN

Temporary security token

SHARED_WORK_DIR

Path for session-level shared storage. All UDF instances in the same session can access this path for read and write operations.

These reserved keys are automatically injected by the kernel and cannot be manually set by users.

Risks:

  • The frontend env_vars are transmitted in plaintext JSON format through SQL.
  • They may be captured by audit logs, slow query logs, and error logs.
  • If a preset environment variable conflicts with a user key, the kernel returns an error and stops calling the UDF.

Risks of overwriting system variables: Overwriting variables such as PATH, LD_PRELOAD, PYTHONPATH, HOME, and PYTHONHOME may lead to unexpected results.