RousselTMLEARNING

Article · Alloy: From Discovery to Expertise

Variables and Functions

3. Variables and Functions #

Types, value sources, built-in functions and five concrete examples to make an Alloy configuration dynamic and reusable.

Value types #

An Alloy configuration handles typed values: numbers, strings, booleans, null, arrays [ ] and objects { }. Alloy adds two types of its own: secret, for passwords and tokens, and capsule, for internal values such as receivers or targets.

// Numbers, strings, booleans, null
scrape_interval = "30s"
sample_limit    = 5000
enabled         = true

// Array: trailing comma recommended
enable_collectors = ["cpu", "meminfo", "filesystem",]

// Object: identifier or string keys
targets = [
  { "__address__" = "app-1:8080", env = "prod" },
  { "__address__" = "app-2:8080", env = "prod" },
]

// Reference to a value exported by another component
forward_to = [prometheus.remote_write.mimir.receiver]

Type errors are caught at load time, for example a string passed where a number is expected. The message gives the file, line and faulty attribute.

Where do “variables” come from? #

There is no variable or locals block as in Terraform. A reusable value always comes from one of these sources:

SourceTypical useExample
sys.env("NAME")Tell environments apart (URL, tenant, cluster)sys.env("MIMIR_URL")
constants.*Machine informationconstants.hostname, constants.os
local.fileRead a file (mounted secret, target list)local.file.token.content
remote.http, remote.s3Read a value over the network, polled periodicallyremote.http.config.content
remote.kubernetes.secret, remote.vaultRead a Kubernetes or Vault secretremote.vault.creds.data.password
argument (inside declare)Parameter of a custom componentargument.url.value

The local.* and remote.* sources are components themselves. When their content changes, every component reading them is re-evaluated automatically.

For details on what Alloy reads from the environment, including OTEL_RESOURCE_ATTRIBUTES, see the Environment variables and OpenTelemetry lesson.

Operators and built-in functions #

Expressions accept arithmetic (+ - * / % ^), comparison (== != < <= > >=) and logical (&& || !) operators. The + operator also concatenates strings. Standard library functions are grouped by namespace:

FunctionPurposeExample
sys.envRead an environment variable (empty string if missing)sys.env("CLUSTER")
coalesceFirst non-empty value: ideal for defaultscoalesce(sys.env("ENV"), "dev")
string.formatBuild a string (%s, %d… verbs)string.format("%s:%d", host, 9100)
string.join / string.splitJoin or splitstring.split("a,b", ",")
string.to_lower / to_upper / trim_spaceNormalise a valuestring.to_lower("PROD")
string.replace, trim_prefix, trim_suffixClean a stringstring.trim_suffix(url, "/")
array.concatMerge target listsarray.concat(a.targets, b.targets)
encoding.from_json / from_yaml / from_base64Decode contentencoding.from_json(local.file.t.content)
json_pathExtract a value from JSONjson_path(doc, ".endpoints[0]")
convert.nonsensitiveMake a secret readable (avoid)convert.nonsensitive(secret)
Old names: in Grafana Agent Flow (River), these functions were called env(), format(), join(), concat(), json_decode() or nonsensitive(). If an example found online fails with “unknown function”, rename them with their namespace.

Example 1: one configuration per environment #

The same config.alloy file is deployed everywhere; environment-specific values are passed as environment variables (Docker, Helm, systemd).

// One file for staging and production:
// only the environment variables change.
prometheus.remote_write "mimir" {
  endpoint {
    // coalesce: first non-empty value (default when the variable is missing)
    url = coalesce(sys.env("MIMIR_URL"), "http://mimir:9009/api/v1/push")

    headers = {
      "X-Scope-OrgID" = coalesce(sys.env("MIMIR_TENANT"), "anonymous"),
    }
  }

  external_labels = {
    cluster     = coalesce(sys.env("CLUSTER_NAME"), "local"),
    environment = string.to_lower(coalesce(sys.env("ENV"), "DEV")),
    host        = constants.hostname,
  }
}
# Staging
MIMIR_URL=https://mimir-staging.example.com/api/v1/push CLUSTER_NAME=staging ENV=STAGING alloy run config.alloy

# Docker Compose
services:
  alloy:
    image: grafana/alloy:latest
    environment:
      MIMIR_URL: https://mimir.example.com/api/v1/push
      CLUSTER_NAME: prod-eu
      ENV: PROD

Example 2: a secret read from a file #

// The password is read from a mounted file (Kubernetes secret, Vault agent…)
local.file "mimir_password" {
  filename  = "/var/run/secrets/mimir/password"
  is_secret = true              // the value has the secret type: never shown in the UI
}

prometheus.remote_write "mimir" {
  endpoint {
    url = "https://mimir.example.com/api/v1/push"
    basic_auth {
      username = sys.env("MIMIR_USER")
      password = local.file.mimir_password.content
    }
  }
}

With is_secret = true, the exported value has the secret type: it never shows up in the Alloy UI or in logs. If the file is updated (password rotation), Alloy re-reads it and reconfigures the output without a restart.

Never write a plain-text password in config.alloy: the file almost always ends up in a Git repository. Use local.file, remote.kubernetes.secret or remote.vault instead.

Example 3: targets described in a JSON file #

// targets.json, maintained by another tool (CMDB, script, Ansible…):
// [{"__address__": "db-1:9187", "role": "primary"}, {"__address__": "db-2:9187", "role": "replica"}]
local.file "targets" {
  filename = "/etc/alloy/targets.json"
}

prometheus.scrape "postgres" {
  // encoding.from_json turns the file content into an array of objects
  targets    = encoding.from_json(local.file.targets.content)
  forward_to = [prometheus.remote_write.mimir.receiver]
}
// The file is re-read automatically when it changes: new targets are scraped without a restart.

This pattern lets a team declare its targets in a simple file without touching the Alloy configuration. Fields other than __address__ (here role) become labels on the collected metrics.

Example 4: building strings and labels #

loki.process "normalize" {
  forward_to = [loki.write.default.receiver]

  stage.static_labels {
    values = {
      // Concatenation with +
      service = "checkout-" + coalesce(sys.env("REGION"), "eu"),
      // Formatting
      team    = string.to_upper("payments"),
      // Joining a list
      zones   = string.join(["eu-west-3a", "eu-west-3b"], ","),
    }
  }
}

There is no ${...} interpolation as in HCL: + concatenation is enough for simple cases, and string.format reads better as soon as several values are involved.

Example 5: factoring with declare and import #

To avoid copy-pasting the same block, Alloy offers custom components with declare. They are the equivalent of Terraform modules: input parameters (argument), internal components and exported values (export).

// Reusable custom component: the equivalent of a Terraform module
declare "mimir_writer" {
  argument "url" {}
  argument "tenant" {
    optional = true
    default  = "anonymous"
  }

  prometheus.remote_write "default" {
    endpoint {
      url     = argument.url.value
      headers = { "X-Scope-OrgID" = argument.tenant.value }
    }
  }

  export "receiver" {
    value = prometheus.remote_write.default.receiver
  }
}

// Two instances, two tenants, without duplicating the configuration
mimir_writer "prod" {
  url    = "https://mimir.example.com/api/v1/push"
  tenant = "prod"
}
mimir_writer "audit" {
  url    = "https://mimir.example.com/api/v1/push"
  tenant = "audit"
}

prometheus.scrape "app" {
  targets    = [{ "__address__" = "app:8080" }]
  forward_to = [mimir_writer.prod.receiver, mimir_writer.audit.receiver]
}

To share these components across teams or servers, put them in a separate file and load them with import.file, import.http or import.git:

// Load shared components from a Git repository (re-read every 5 minutes)
import.git "shared" {
  repository     = "https://github.com/acme/alloy-modules.git"
  revision       = "main"
  path           = "modules/mimir.alloy"
  pull_frequency = "5m"
}

shared.mimir_writer "prod" {
  url = sys.env("MIMIR_URL")
}
Best practices: one file per role (collection, processing, output); defaults with coalesce; secrets in local.file or a vault; alloy fmt in CI; and a look at the UI graph after every change.

📄 Grafana Alloy: Syntax and Configuration (Alloy Language: River) →

My progress

  • ⏱ Estimated time : ≈ 19 min

Sign in to track your progress and take notes. Sign in

⭐ Rate this lesson

3.0 initial rating from the teaching team

Sign in to rate this lesson →

💬 Recent discussions about this course

Ask a question about this lesson →See all discussions about this course

Course Glossary

Grafana Alloy

An open-source, vendor-neutral telemetry collector designed to replace Grafana Agent, fully compatible with OpenTelemetry (OTel).

Recommended Articles

Grafana Alloy best practices: optimizing your telemetry collection

Discover the golden rules for configuring Grafana Alloy robustly: modularity, secrets management,...

Grafana Alloy environment variables: GOMEMLIMIT, sys.env and OTEL_RESOURCE_ATTRIBUTES

Which variables does Grafana Alloy actually read? GOMEMLIMIT, HTTP_PROXY, sys.env, OTEL_RESOURCE_...

Grafana Alloy: The importance of Self-Monitoring

Discover why and how to configure Grafana Alloy so that it monitors itself, collecting its own lo...

Grafana Alloy: collecting system metrics and local logs

Learn how to configure Grafana Alloy to monitor the server it runs on, with a focus on configurat...

Grafana Alloy: collecting and transforming telemetry

Learn how to use Grafana Alloy to collect, transform and route logs, metrics and traces. Discover...

Grafana Alloy components reference

A complete reference guide to all the components available in Grafana Alloy, organized by categor...

Grafana Alloy vs OpenTelemetry Collector: Which One Should You Choose?

A detailed comparison between Grafana Alloy and the OpenTelemetry Collector. Discover the strengt...

OpenTelemetry Collector, Grafana Alloy and Bindplane: comparing three approaches to telemetry pipelines

Detailed comparison of three ways to manage telemetry pipelines: the OpenTelemetry Collector in Y...

Grafana Alloy: Understanding and exploiting the User Interface (UI)

Discover how to enable, secure, and use Grafana Alloy's built-in web interface to visualize your ...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!