Skip to main content
Version: sdf-beta5

Environment Variables

Environment variables can be used to pass configuration information to the operators. The environment variables are defined in the operator definition and can be accessed in the operator code.

They are useful for passing configuration information such as API keys, database connection strings, and other configuration information.

Defining Environment Variables

You can define environment variables in the run command similar to Docker. The -e flag is used to define environment variables.

sdf run -e VAR1=value1 -e VAR2=value2

Accessing Environment Variables in operator code

Once the environment variables are defined thru CLI, they are available in every operator user code. In the Rust code, you can access the environment variables using thestd::env module.

Follow code snippet illustration filter that reject a word starts with prefix defined in environment variable.

- operator: filter-map
  run: |
    fn filter(input: word) -> Result<Option<String>> {
      let block_word = std::env::var("BLOCKED_PREFIX")?;
      if input.starts_with(&block_word) {
        Ok(None)
      } else {
        Ok(Some(input))
      }
    }

They are also useful for passing configuration information such as API keys. For example, following show how to encode bearer token in environment variable and access it in the operator code.

- operator: map
  dependencies:
    - name: sdf-http
      git: "https://github.com/infinyon/sdf-http-guest"
      tag: "v0.4.0"
  run: |
    fn filter(input: sentence) -> Result<Option<String>> {
      let auth_key = std::env::var("MY_API_KEY")?;
      let auth_bearer = format!("Bearer {}", auth_key);
      let request = sdf_http::http::Request::builder()
            .uri("https://myapi.com/api/v1/sentences")
            .method("POST")
            .header("Content-Type", "application/json")
            .header("Authorization", auth_bearer)
            .body(body)?;
      let response = sdf_http::blocking::send(request)?;
      let body: Vec<u8> = response.into_body();
      Ok(String::from_utf8(body)?);
    }