Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install alloy@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin alloy v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install alloy

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/alloy/

Extract the ZIP to .github/skills/ in your repo. The folder name must match alloy for Copilot to auto-discover it.

Skill Files (4)

SKILL.md 5.2 KB
---
name: alloy
license: Apache-2.0
description: Build a unified telemetry pipeline with Grafana Alloy — one OpenTelemetry-compatible binary that collects metrics, logs, traces, and profiles and ships to Grafana Cloud / Prometheus / Loki / Tempo / Pyroscope. Covers the Alloy config language (blocks, `sys.env`, component refs), `prometheus.scrape` → `remote_write`, `loki.source.file` + `loki.process` → `loki.write`, `otelcol.receiver.otlp` → `otelcol.exporter.otlp`, `pyroscope.scrape`, K8s / Docker / EC2 discovery, relabeling, modules (`import.file/git/http`), clustering, Fleet Management `remotecfg`, the Alloy UI at `:12345`, and `alloy fmt` / `alloy validate`. Use when writing a `config.alloy`, replacing Grafana Agent / OTel Collector, scraping K8s pods, parsing logs, ingesting OTLP, or debugging "Alloy isn't sending anything" — even when the user says "set up the agent", "write me a scrape config", "drop these logs before sending", or "OTel collector config" without naming Alloy.
---

# Grafana Alloy

> **Docs**: https://grafana.com/docs/alloy/latest/

OpenTelemetry-compatible collector — one binary for metrics + logs + traces + profiles.

## Prerequisites

- `alloy` CLI installed (`brew install grafana/grafana/alloy`, `apt install alloy`, or `grafana/alloy` Docker image)
- An endpoint to ship to (Grafana Cloud, Prometheus, Loki, Tempo, Pyroscope)
- API key + username for that endpoint, exported as `GRAFANA_API_KEY` etc.

## Common Workflows

### 1. Write + validate a config locally

```alloy
// config.alloy — metrics → Grafana Cloud
prometheus.scrape "app" {
  targets = [{"__address__" = "localhost:9090"}]
  forward_to = [prometheus.remote_write.cloud.receiver]
  scrape_interval = "30s"
}

prometheus.remote_write "cloud" {
  endpoint {
    url = sys.env("PROMETHEUS_URL")
    basic_auth {
      username = sys.env("PROM_USER")
      password = sys.env("GRAFANA_API_KEY")
    }
  }
}
```

```bash
# 1. Format + syntax-check (catches typos before run)
alloy fmt config.alloy
alloy validate config.alloy

# 2. Run it
alloy run config.alloy
# or as a service: systemctl restart alloy

# 3. Verify all components are healthy via the UI on port 12345
curl -s http://localhost:12345/api/v0/web/components \
  | jq '.[] | select(.health.state != "healthy") | {id, state:.health.state, msg:.health.message}'
# Expect: empty (nothing unhealthy). Otherwise the row shows the failing component + reason.

# 4. Verify samples are flowing
curl -s http://localhost:12345/metrics \
  | grep -E '^prometheus_remote_storage_(samples_total|enqueue_retries_total)' | head
# samples_total should be > 0 and rising; retries should be 0.
```

### 2. Add log shipping (file → Loki)

```alloy
loki.source.file "app_logs" {
  targets    = [{ __path__ = "/var/log/app/*.log", job = "app" }]
  forward_to = [loki.write.cloud.receiver]
}

loki.write "cloud" {
  endpoint {
    url = sys.env("LOKI_URL")
    basic_auth {
      username = sys.env("LOKI_USER")
      password = sys.env("GRAFANA_API_KEY")
    }
  }
}
```

```bash
# Verify in Grafana → Explore → Loki:
#   {job="app"}
# Expect lines streaming. If empty:
#   - check /var/log/app/*.log actually exists + readable by the alloy user
#   - http://localhost:12345 → loki.source.file.app_logs → "Targets" tab
```

### 3. Receive OTLP traces and ship to Tempo

```alloy
otelcol.receiver.otlp "default" {
  grpc { endpoint = "0.0.0.0:4317" }
  http { endpoint = "0.0.0.0:4318" }
  output { traces = [otelcol.exporter.otlp.tempo.input] }
}

otelcol.exporter.otlp "tempo" {
  client {
    endpoint = "tempo-xxx.grafana.net/tempo:443"
    auth     = otelcol.auth.basic.grafana_cloud.handler
  }
}

otelcol.auth.basic "grafana_cloud" {
  username = sys.env("TEMPO_USER")
  password = sys.env("GRAFANA_API_KEY")
}
```

```bash
# Verify in Grafana → Explore → Tempo → service.name = your-service
# At the Alloy level, watch the receiver:
curl -s http://localhost:12345/metrics | grep otelcol_receiver_accepted_spans
```

Full pattern set (Kubernetes discovery + relabel, complete Cloud pipeline for all 4 signals): [`references/collection-patterns.md`](references/collection-patterns.md).

## Reference

- [`references/config-syntax.md`](references/config-syntax.md) — block/attribute/expression grammar, `import.*`, `remotecfg`, clustering
- [`references/components.md`](references/components.md) — full component catalog with purpose + typical args
- [`references/collection-patterns.md`](references/collection-patterns.md) — end-to-end pipelines (K8s pods, OTLP, profiles, logs)

## Troubleshooting

- `alloy validate` → "component not found" → version too old; `alloy --version` and upgrade
- UI shows component `unhealthy` → click into it on http://localhost:12345 for the live error
- `prometheus_remote_storage_samples_dropped_total` rising → check `enqueue_retries_total` and the remote_write endpoint URL + creds
- No spans landing in Tempo → check `otelcol_receiver_refused_spans` and the exporter's `otelcol_exporter_sent_spans` / `otelcol_exporter_send_failed_spans`

## Resources

- [Alloy docs](https://grafana.com/docs/alloy/latest/)
- [Component reference](https://grafana.com/docs/alloy/latest/reference/components/)
- [Migrate from Grafana Agent](https://grafana.com/docs/alloy/latest/set-up/migrate/from-agent/)
references/
collection-patterns.md 10.7 KB
# Alloy Collection Patterns

> Canonical recipes for the common things Alloy does. Configs are taken from the official Alloy
> "Collect" docs (https://grafana.com/docs/alloy/latest/collect/) and adjusted to be runnable as-is
> with placeholder values.

## Pipeline shape, at a glance

```
discovery / receive  →  process / relabel  →  write / export
```

Every pattern below fits this shape. The label of each component (in quotes after the block type) is
your choice; references use `block.type.label.export`.

---

## 1. Prometheus metrics — scrape and remote-write

Pull `/metrics` from a static list of targets and ship to a Prometheus-compatible endpoint.

```alloy
prometheus.scrape "custom_targets" {
  targets = [
    {__address__ = "prometheus:9090"},
    {__address__ = "custom-app:80", __metrics_path__ = "/custom-metrics-path", __scheme__ = "https"},
    {__address__ = "app:12345", environment = "production"},
  ]
  forward_to      = [prometheus.remote_write.default.receiver]
  scrape_interval = "30s"
}

prometheus.remote_write "default" {
  endpoint {
    url = sys.env("PROMETHEUS_URL")
    basic_auth {
      username = sys.env("PROMETHEUS_USER")
      password = sys.env("GRAFANA_API_KEY")
    }
  }
  external_labels = {
    cluster = "prod-us-east",
    env     = "production",
  }
}
```

Notes:

- Labels beginning with `__` are stripped after relabeling; they control the scrape, not the output.
- `__scheme__` defaults to `http`, `__metrics_path__` defaults to `/metrics`.
- Add multiple `endpoint` blocks to fan-out to several backends.

## 2. Kubernetes service discovery → scrape

Scrape every pod the API server lists, filtered by relabeling.

```alloy
discovery.kubernetes "pods" {
  role = "pod"
}

discovery.relabel "pods" {
  targets = discovery.kubernetes.pods.targets

  rule {
    source_labels = ["__meta_kubernetes_pod_label_app"]
    target_label  = "app"
  }
  rule {
    source_labels = ["__meta_kubernetes_namespace"]
    target_label  = "namespace"
  }
  // Drop pods that didn't set the "app" label
  rule {
    source_labels = ["__meta_kubernetes_pod_label_app"]
    regex         = ""
    action        = "drop"
  }
}

prometheus.scrape "k8s_pods" {
  targets    = discovery.relabel.pods.output
  forward_to = [prometheus.remote_write.default.receiver]
}
```

Other `role` values for `discovery.kubernetes`: `service`, `endpoints`, `endpointslice`, `node`,
`ingress`.

## 3. Kubernetes pod logs → Loki

Tail container logs from the node Alloy is running on. Uses the standard meta-label relabeling
recommended by the docs.

```alloy
loki.write "default" {
  endpoint {
    url = sys.env("LOKI_URL")
    basic_auth {
      username = sys.env("LOKI_USER")
      password = sys.env("GRAFANA_API_KEY")
    }
  }
}

discovery.kubernetes "pod" {
  role = "pod"
  selectors {
    role  = "pod"
    field = "spec.nodeName=" + coalesce(sys.env("HOSTNAME"), constants.hostname)
  }
}

discovery.relabel "pod_logs" {
  targets = discovery.kubernetes.pod.targets

  rule { source_labels = ["__meta_kubernetes_namespace"]                  target_label = "namespace"  action = "replace" }
  rule { source_labels = ["__meta_kubernetes_pod_name"]                   target_label = "pod"        action = "replace" }
  rule { source_labels = ["__meta_kubernetes_pod_container_name"]         target_label = "container"  action = "replace" }
  rule { source_labels = ["__meta_kubernetes_pod_label_app_kubernetes_io_name"] target_label = "app"  action = "replace" }

  rule {
    source_labels = ["__meta_kubernetes_namespace", "__meta_kubernetes_pod_container_name"]
    target_label  = "job"
    separator     = "/"
    replacement   = "$1"
    action        = "replace"
  }

  rule {
    source_labels = ["__meta_kubernetes_pod_uid", "__meta_kubernetes_pod_container_name"]
    target_label  = "__path__"
    separator     = "/"
    replacement   = "/var/log/pods/*$1/*.log"
    action        = "replace"
  }
}

loki.source.kubernetes "pod_logs" {
  targets    = discovery.relabel.pod_logs.output
  forward_to = [loki.process.pod_logs.receiver]
}

loki.process "pod_logs" {
  forward_to = [loki.write.default.receiver]
  stage.static_labels {
    values = { cluster = "prod-us-east" }
  }
}
```

## 4. Kubernetes cluster events → Loki

```alloy
loki.source.kubernetes_events "cluster_events" {
  job_name   = "integrations/kubernetes/eventhandler"
  log_format = "logfmt"
  forward_to = [loki.process.cluster_events.receiver]
}

loki.process "cluster_events" {
  forward_to = [loki.write.default.receiver]
  stage.static_labels {
    values = { cluster = "prod-us-east" }
  }
  stage.labels {
    values = { kubernetes_cluster_events = "job" }
  }
}
```

## 5. Node/system logs → Loki

```alloy
local.file_match "node_logs" {
  path_targets = [{
    __path__  = "/var/log/syslog",
    job       = "node/syslog",
    node_name = sys.env("HOSTNAME"),
    cluster   = "prod-us-east",
  }]
}

loki.source.file "node_logs" {
  targets    = local.file_match.node_logs.targets
  forward_to = [loki.write.default.receiver]
}
```

## 6. systemd journal → Loki

```alloy
loki.source.journal "system" {
  forward_to = [loki.write.default.receiver]
  labels     = { job = "systemd-journal" }
  // optional: relabel_rules, matches, format_as_json
}
```

## 7. OpenTelemetry → Grafana LGTM stack

OTLP in, split to metrics/logs/traces with a batch processor, ship to Grafana Cloud.

```alloy
otelcol.receiver.otlp "default" {
  grpc { endpoint = "0.0.0.0:4317" }
  http { endpoint = "0.0.0.0:4318" }

  output {
    metrics = [otelcol.processor.batch.default.input]
    logs    = [otelcol.processor.batch.default.input]
    traces  = [otelcol.processor.batch.default.input]
  }
}

otelcol.processor.batch "default" {
  output {
    metrics = [otelcol.exporter.prometheus.grafana_cloud_metrics.input]
    logs    = [otelcol.exporter.loki.grafana_cloud_logs.input]
    traces  = [otelcol.exporter.otlphttp.grafana_cloud_traces.input]
  }
}

otelcol.exporter.otlphttp "grafana_cloud_traces" {
  client {
    endpoint = "https://tempo-us-central1.grafana.net:443"
    auth     = otelcol.auth.basic.grafana_cloud.handler
  }
}

otelcol.exporter.prometheus "grafana_cloud_metrics" {
  forward_to = [prometheus.remote_write.grafana_cloud.receiver]
}

otelcol.exporter.loki "grafana_cloud_logs" {
  forward_to = [loki.write.grafana_cloud.receiver]
}

otelcol.auth.basic "grafana_cloud" {
  username = sys.env("GRAFANA_CLOUD_INSTANCE_ID")
  password = sys.env("GRAFANA_CLOUD_API_KEY")
}

prometheus.remote_write "grafana_cloud" {
  endpoint {
    url = "https://prometheus-us-central1.grafana.net/api/prom/push"
    basic_auth {
      username = sys.env("GRAFANA_CLOUD_METRICS_USER")
      password = sys.env("GRAFANA_CLOUD_API_KEY")
    }
  }
}

loki.write "grafana_cloud" {
  endpoint {
    url = "https://logs-prod-us-central1.grafana.net/loki/api/v1/push"
    basic_auth {
      username = sys.env("GRAFANA_CLOUD_LOGS_USER")
      password = sys.env("GRAFANA_CLOUD_API_KEY")
    }
  }
}
```

Add a `memory_limiter` in front of `batch` in production:

```alloy
otelcol.processor.memory_limiter "default" {
  check_interval   = "1s"
  limit_percentage = 80
  output {
    metrics = [otelcol.processor.batch.default.input]
    logs    = [otelcol.processor.batch.default.input]
    traces  = [otelcol.processor.batch.default.input]
  }
}
```

…and point the OTLP receiver's `output.*` at `otelcol.processor.memory_limiter.default.input`.

## 8. Profiles — pprof scraping → Pyroscope

```alloy
pyroscope.scrape "default" {
  targets = [
    {__address__ = "localhost:6060", service_name = "myapp"},
  ]
  forward_to = [pyroscope.write.default.receiver]
}

pyroscope.write "default" {
  endpoint {
    url = sys.env("PYROSCOPE_URL")
    basic_auth {
      username = sys.env("PYROSCOPE_USER")
      password = sys.env("GRAFANA_API_KEY")
    }
  }
}
```

## 9. Zero-code traces and metrics with Beyla

```alloy
beyla.ebpf "default" {
  open_port = "8080"   // or attach_pid, executable_name, k8s selectors

  output {
    metrics = [otelcol.processor.batch.default.input]
    traces  = [otelcol.processor.batch.default.input]
  }
}
```

## 10. Frontend telemetry — Faro

```alloy
faro.receiver "default" {
  server {
    listen_address = "0.0.0.0"
    listen_port    = 12347
    // Replace with your actual web origins before deploying — wildcard "*" lets any site send
    // telemetry to this endpoint and is not suitable for production.
    cors_allowed_origins = ["https://app.example.com"]
  }

  output {
    logs   = [loki.write.grafana_cloud.receiver]
    traces = [otelcol.processor.batch.default.input]
  }
}
```

## 11. Clustering — distribute scrape load

Run multiple Alloy replicas and let them shard targets among themselves.

```alloy
clustering {
  enabled = true
}

prometheus.scrape "cluster_aware" {
  targets    = discovery.kubernetes.pods.targets
  forward_to = [prometheus.remote_write.default.receiver]
  clustering { enabled = true }
}
```

Cluster discovery uses memberlist; configure peer addresses via the `--cluster.*` CLI flags on
`alloy run` (e.g. `--cluster.join-addresses=alloy-headless:12345`).

## 12. Fleet Management — remote config

```alloy
remotecfg {
  url = "https://fleet-management-prod-XXX.grafana.net"
  basic_auth {
    username = sys.env("FM_USERNAME")
    password = sys.env("FM_TOKEN")
  }
  poll_interval = "1m"
}
```

With `remotecfg`, the local file becomes the bootstrap. The fleet server delivers the rest as
modules Alloy imports automatically.

## 13. Modules and imports

Pull components from a Git module library:

```alloy
import.git "k8s_monitoring" {
  repository = "https://github.com/grafana/alloy-modules"
  revision   = "main"
  path       = "modules/kubernetes/"
}

k8s_monitoring.pods "default" {
  forward_to = [prometheus.remote_write.default.receiver]
}
```

## 14. Pipeline processing — relabel and parse

Drop noisy Go metrics, add an `environment` label:

```alloy
prometheus.relabel "filter" {
  forward_to = [prometheus.remote_write.default.receiver]

  rule {
    source_labels = ["__name__"]
    regex         = "go_.*"
    action        = "drop"
  }
  rule {
    target_label = "environment"
    replacement  = "production"
  }
}
```

Parse JSON logs and lift one field to a label:

```alloy
loki.process "json_parse" {
  forward_to = [loki.write.default.receiver]

  stage.json {
    expressions = { level = "level", msg = "message" }
  }
  stage.labels {
    values = { level = "" }
  }
  stage.drop {
    expression = ".*health check.*"
  }
}
```

---

## Running Alloy

```bash
alloy run /etc/alloy/config.alloy \
  --server.http.listen-addr=0.0.0.0:12345 \
  --storage.path=/var/lib/alloy/data \
  --cluster.enabled=true \
  --cluster.join-addresses=alloy-headless.alloy.svc:12345
```

Reload after editing: `kill -HUP <pid>` or `curl -XPOST http://localhost:12345/-/reload`.

UI and component graph: `http://localhost:12345/`.
components.md 16.1 KB
# Alloy Components Reference

> Index of the most commonly used Alloy components, grouped by namespace. The canonical and complete
> reference is at https://grafana.com/docs/alloy/latest/reference/components/.

Alloy components are identified by a dotted **namespace**.**name** and configured via a labeled
block. Each component has typed **arguments** (what you set) and **exports** (what other components
consume — typically `.receiver`, `.input`, `.targets`, `.output`, `.handler`, or `.content`).

## Discovery — find targets to scrape

Discovery components emit a `targets` export: an array of label maps consumed by `prometheus.scrape`,
`loki.source.*`, or `pyroscope.scrape`.

| Component                  | Purpose                                                          |
|----------------------------|------------------------------------------------------------------|
| `discovery.kubernetes`     | Pods, services, endpoints, nodes, ingresses via the K8s API      |
| `discovery.docker`         | Containers from the Docker daemon                                |
| `discovery.dockerswarm`    | Tasks/services from a Docker Swarm                               |
| `discovery.ec2`            | AWS EC2 instances                                                |
| `discovery.gce`            | GCP Compute Engine instances                                     |
| `discovery.azure`          | Azure VMs and scale sets                                         |
| `discovery.dns`            | DNS SRV/A/AAAA records                                           |
| `discovery.consul`         | Services registered in Consul                                    |
| `discovery.nomad`          | Allocations in HashiCorp Nomad                                   |
| `discovery.file`           | Targets from a JSON/YAML file (file_sd compatible)               |
| `discovery.http`           | Targets from an HTTP endpoint (http_sd compatible)               |
| `discovery.relabel`        | Apply relabeling rules to another component's `targets`          |
| `discovery.process`        | Local process listing (used with Beyla / Pyroscope eBPF)         |

```alloy
discovery.kubernetes "pods" {
  role = "pod"
}

discovery.relabel "pods" {
  targets = discovery.kubernetes.pods.targets
  rule {
    source_labels = ["__meta_kubernetes_namespace"]
    target_label  = "namespace"
  }
}
```

## Prometheus — metrics pipeline

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `prometheus.scrape`             | Pull `/metrics` from `targets`                                 |
| `prometheus.remote_write`       | Write metrics via Prometheus remote-write protocol             |
| `prometheus.relabel`            | Add/drop/rewrite labels on metric samples                      |
| `prometheus.operator.podmonitors`     | Scrape using Prometheus Operator `PodMonitor` CRDs       |
| `prometheus.operator.servicemonitors` | Scrape using `ServiceMonitor` CRDs                       |
| `prometheus.operator.probes`          | Use `Probe` CRDs                                         |
| `prometheus.receive_http`       | Accept remote-write traffic (proxy / fan-out)                  |
| `prometheus.exporter.unix`      | Linux node metrics (node_exporter equivalent)                  |
| `prometheus.exporter.windows`   | Windows host metrics                                           |
| `prometheus.exporter.mongodb`   | MongoDB metrics                                                |
| `prometheus.exporter.mysql`     | MySQL metrics                                                  |
| `prometheus.exporter.postgres`  | PostgreSQL metrics                                             |
| `prometheus.exporter.redis`     | Redis metrics                                                  |
| `prometheus.exporter.snmp`      | SNMP-based device metrics                                      |
| `prometheus.exporter.blackbox`  | Blackbox probe (HTTP/TCP/ICMP)                                 |
| `prometheus.exporter.cloudwatch`| AWS CloudWatch metrics                                         |
| `prometheus.exporter.kafka`     | Kafka metrics                                                  |
| `prometheus.exporter.process`   | Per-process metrics                                            |

Inputs to scrape/relabel/remote_write chain via:

```
discovery.* → discovery.relabel → prometheus.scrape → prometheus.relabel → prometheus.remote_write
                                                                        (.receiver)
```

## Loki — logs pipeline

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `loki.source.file`              | Tail log files (file_sd-style)                                 |
| `local.file_match`              | Path globs that produce targets for `loki.source.file`         |
| `loki.source.kubernetes`        | Tail Kubernetes container logs via API                         |
| `loki.source.kubernetes_events` | Stream cluster events                                          |
| `loki.source.journal`           | systemd journald                                               |
| `loki.source.docker`            | Docker container logs                                          |
| `loki.source.syslog`            | Listen for RFC5424/RFC3164 syslog                              |
| `loki.source.gcplog`            | GCP Pub/Sub logs                                               |
| `loki.source.awsfirehose`       | AWS Kinesis Data Firehose                                      |
| `loki.source.azure_event_hubs`  | Azure Event Hubs                                               |
| `loki.source.cloudflare`        | Cloudflare logpush                                             |
| `loki.source.api`               | Generic HTTP push endpoint                                     |
| `loki.echo`                     | Print received logs (debugging)                                |
| `loki.process`                  | Pipeline stages: parse, label, drop, transform                 |
| `loki.relabel`                  | Relabel without parsing                                        |
| `loki.write`                    | Push logs to Loki                                              |

Pipeline shape:

```
discovery.* → loki.source.* → loki.process → loki.write
                                          (.receiver)
```

`loki.process` stages include `stage.json`, `stage.logfmt`, `stage.regex`, `stage.labels`,
`stage.static_labels`, `stage.label_drop`, `stage.label_keep`, `stage.drop`, `stage.timestamp`,
`stage.output`, `stage.template`, `stage.multiline`, `stage.match`, and `stage.replace`.

## OpenTelemetry — `otelcol.*`

### Receivers

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `otelcol.receiver.otlp`         | OTLP over gRPC (4317) and HTTP (4318)                          |
| `otelcol.receiver.jaeger`       | Jaeger gRPC/Thrift                                             |
| `otelcol.receiver.zipkin`       | Zipkin HTTP                                                    |
| `otelcol.receiver.prometheus`   | Convert Prometheus scrape data into OTel metrics               |
| `otelcol.receiver.loki`         | Convert Loki log data into OTel logs                           |
| `otelcol.receiver.kafka`        | Consume OTLP/JSON from Kafka                                   |
| `otelcol.receiver.opencensus`   | OpenCensus protocol                                            |
| `otelcol.receiver.vcenter`      | VMware vCenter                                                 |
| `otelcol.receiver.datadog`      | Datadog Agent traces/metrics                                   |

### Processors

| Component                                | Purpose                                              |
|------------------------------------------|------------------------------------------------------|
| `otelcol.processor.batch`                | Batch signals before export                          |
| `otelcol.processor.memory_limiter`       | Drop data if memory exceeds threshold                |
| `otelcol.processor.transform`            | OTTL-based transformation                            |
| `otelcol.processor.attributes`           | Insert/update/delete attributes                      |
| `otelcol.processor.resourcedetection`    | Add resource attributes (k8s/aws/gcp/azure)          |
| `otelcol.processor.k8sattributes`        | Enrich with k8s metadata                             |
| `otelcol.processor.filter`               | Drop telemetry matching OTTL expressions             |
| `otelcol.processor.tail_sampling`        | Trace tail sampling                                  |
| `otelcol.processor.probabilistic_sampler`| Head-based sampling                                  |
| `otelcol.processor.span`                 | Rename / extract attributes from span names          |
| `otelcol.processor.deltatocumulative`    | Convert delta to cumulative temporality              |

### Exporters

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `otelcol.exporter.otlp`         | OTLP gRPC                                                      |
| `otelcol.exporter.otlphttp`     | OTLP HTTP                                                      |
| `otelcol.exporter.prometheus`   | Forward to `prometheus.remote_write`                           |
| `otelcol.exporter.loki`         | Forward to `loki.write`                                        |
| `otelcol.exporter.loadbalancing`| Distribute traces across endpoints (consistent hashing)        |
| `otelcol.exporter.kafka`        | Kafka producer                                                 |
| `otelcol.exporter.debug`        | Log telemetry to stderr (debugging)                            |
| `otelcol.exporter.faro`         | Frontend Observability                                         |

### Auth and extensions

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `otelcol.auth.basic`            | HTTP basic auth handler for otelcol clients                    |
| `otelcol.auth.bearer`           | Bearer-token auth                                              |
| `otelcol.auth.headers`          | Static header auth                                             |
| `otelcol.auth.oauth2`           | OAuth2 client credentials                                      |
| `otelcol.auth.sigv4`            | AWS SigV4                                                      |
| `otelcol.connector.spanmetrics` | Generate RED metrics from spans                                |
| `otelcol.connector.servicegraph`| Build service-graph metrics from traces                        |

OTel pipeline shape:

```
otelcol.receiver.* → otelcol.processor.* → otelcol.exporter.*
                  (output{traces=, metrics=, logs=})       (.input)
```

## Pyroscope — profiles

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `pyroscope.scrape`              | Pull pprof endpoints from targets                              |
| `pyroscope.ebpf`                | eBPF-based whole-system profiling                              |
| `pyroscope.java`                | async-profiler integration for JVMs                            |
| `pyroscope.relabel`             | Relabel profile streams                                        |
| `pyroscope.write`               | Send profiles to Pyroscope/Grafana Cloud Profiles              |
| `pyroscope.receive_http`        | Accept push from other Pyroscope clients                       |

## Beyla — eBPF auto-instrumentation

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `beyla.ebpf`                    | Auto-generate traces/metrics from any process without code     |

## Faro — frontend telemetry

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `faro.receiver`                 | Accept browser RUM payloads from the Faro Web SDK              |
| `otelcol.exporter.faro`         | Forward OTel data to Grafana Cloud Frontend Observability      |

## Database observability

| Component                              | Purpose                                                 |
|----------------------------------------|---------------------------------------------------------|
| `database_observability.mysql`         | Query Performance, EXPLAIN, slow-query parsing for MySQL|
| `database_observability.postgres`      | Same for PostgreSQL                                     |

## Mimir

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `mimir.rules.kubernetes`        | Sync `PrometheusRule` CRDs into Mimir ruler                    |

## Local / remote helpers

| Component                       | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `local.file`                    | Read a file, expose `.content` (watches for changes)           |
| `local.file_match`              | Glob filesystem paths into targets                             |
| `remote.http`                   | Fetch a URL, expose body as `.content`                         |
| `remote.s3`                     | Fetch an S3 object                                             |
| `remote.kubernetes.configmap`   | Read a ConfigMap value                                         |
| `remote.kubernetes.secret`      | Read a Secret value                                            |
| `remote.vault`                  | Read a HashiCorp Vault secret                                  |

## Imports / modules (top-level)

| Block                           | Purpose                                                        |
|---------------------------------|----------------------------------------------------------------|
| `import.file`                   | Pull declarations from a local file                            |
| `import.git`                    | Pull from a Git repo                                           |
| `import.http`                   | Pull from an HTTP endpoint                                     |
| `import.string`                 | Inline declarations                                            |
| `declare`                       | Define a reusable custom component                             |

## Quick reference — most common imports

```alloy
prometheus.scrape          // pull metrics
prometheus.remote_write    // ship metrics
prometheus.relabel         // filter/relabel metrics
loki.source.file           // tail files
loki.source.kubernetes     // tail pod logs
loki.process               // parse/label/drop logs
loki.write                 // ship logs
otelcol.receiver.otlp      // accept OTLP
otelcol.processor.batch    // batch
otelcol.processor.memory_limiter  // backpressure
otelcol.exporter.otlp      // ship via gRPC
otelcol.exporter.otlphttp  // ship via HTTPS
discovery.kubernetes       // k8s SD
discovery.relabel          // relabel targets
pyroscope.scrape           // scrape pprof
pyroscope.write            // ship profiles
beyla.ebpf                 // zero-code traces/metrics
```

For the full list and per-component arguments/exports, see
https://grafana.com/docs/alloy/latest/reference/components/.
config-syntax.md 9.1 KB
# Alloy Configuration Language Syntax

> Reference for Alloy's configuration syntax (`.alloy` files). For the canonical docs, see
> https://grafana.com/docs/alloy/latest/get-started/configuration-syntax/.

## File format

- Extension: `.alloy`
- Encoding: UTF-8
- Whitespace-insensitive; one or more components per file
- Comments: `//` line comment, `/* ... */` block comment

A config file is a sequence of top-level **blocks** (components and configuration blocks) and
**attributes**.

## Blocks

Blocks declare either a configuration block (`logging`, `http`, `tracing`, `remotecfg`,
`clustering`, ...) or a **component** instance.

```alloy
BLOCK_TYPE "LABEL" {
  attribute = value

  nested_block {
    attribute = value
  }
}
```

- `BLOCK_TYPE` is dotted (e.g. `prometheus.scrape`, `otelcol.receiver.otlp`).
- `"LABEL"` is the user-chosen instance name. The `BLOCK_TYPE.LABEL` pair must be unique.
- Some top-level blocks have no label (`logging`, `http`, `tracing`, `remotecfg`, `clustering`).

```alloy
// Two instances of the same component type, distinguished by label
prometheus.scrape "api" {
  targets    = [{__address__ = "api.example.com:8080"}]
  forward_to = [prometheus.remote_write.cloud.receiver]
}

prometheus.scrape "db" {
  targets    = [{__address__ = "db.example.com:9090"}]
  forward_to = [prometheus.remote_write.cloud.receiver]
}
```

## Attributes

Attributes are `NAME = VALUE` pairs inside a block.

```alloy
scrape_interval = "30s"
enabled         = true
targets         = [{__address__ = "localhost:9090"}]
```

Attribute names are unquoted identifiers. Values can be literals, references, function calls, or
arbitrary expressions.

## Component model

Every component has two halves:

1. **Arguments** — the attributes and nested blocks you write.
2. **Exports** — values the component publishes for other components to consume.

Reference an export with `BLOCK_TYPE.LABEL.export_name`:

```alloy
local.file "api_key" {
  filename = "/etc/secrets/api.key"
}

prometheus.remote_write "cloud" {
  endpoint {
    url = "https://prometheus.example.com/api/v1/write"
    basic_auth {
      username = "metrics"
      password = local.file.api_key.content   // <- export reference
    }
  }
}
```

When a referenced export changes, Alloy re-evaluates and restarts dependent components
automatically — you do not manually wire updates.

## Data types

| Type       | Example                                                   |
|------------|-----------------------------------------------------------|
| `number`   | `42`, `3.14`, `-7`                                        |
| `string`   | `"hello"`, multi-line `"""\nfoo\nbar\n"""` (raw)          |
| `bool`     | `true`, `false`                                           |
| `null`     | `null`                                                    |
| `array`    | `[1, 2, 3]`, `[{__address__ = "host:9090"}]`              |
| `object`   | `{ key = "value", other = 1 }`                            |
| `function` | values returned by stdlib (`sys.env`, etc.)               |
| `capsule`  | opaque internal type (e.g. component receivers/handlers)  |

Object keys can be unquoted identifiers (`key = "v"`) or quoted strings (`"key" = "v"`). Quoted
keys are required when the key isn't a valid identifier — e.g. it contains a hyphen
(`"node-name" = "..."`) or starts with a digit. Identifiers built only from letters, digits, and
underscores (including leading underscores like `__address__`) are valid unquoted; quoting them is
purely a convention borrowed from Prometheus-style metadata labels.

## Expressions

Expressions appear on the right-hand side of any attribute. Supported forms:

```alloy
// Literals
x = 1
y = "string"
z = true

// Arithmetic, comparison, logical operators
a = 1 + 2 * 3            // 7
b = (1 + 2) * 3          // 9
c = 10 > 5 && !false     // true
d = "https://" + host    // string concatenation

// Component reference
e = prometheus.remote_write.cloud.receiver

// Function call
f = sys.env("HOME")
g = encoding.from_json(local.file.config.content)

// Indexing and field access
h = my_array[0]
i = my_object.field
j = my_object["field-with-dash"]
```

Operator precedence (highest to lowest, standard):

1. Unary `!`, `-`
2. `*`, `/`, `%`
3. `+`, `-`
4. `<`, `<=`, `>`, `>=`
5. `==`, `!=`
6. `&&`
7. `||`

Use parentheses to override precedence.

## References to other components

Format: `<block_type>.<label>.<export>`.

```alloy
// Targets export from discovery, consumed by scrape
prometheus.scrape "k8s" {
  targets    = discovery.kubernetes.pods.targets
  forward_to = [prometheus.remote_write.cloud.receiver]
}
```

Forwarding arrays are common: `forward_to = [<recipient>.input]` or `[<recipient>.receiver]`. The
exact export name (`input`, `receiver`, `handler`, ...) depends on the recipient component.

## Standard library

The stdlib mixes two shapes: most functions live under a **namespace** and are called as
`namespace.function(...)` (e.g. `sys.env`, `string.replace`); a handful are **top-level** functions
called by their bare name (e.g. `coalesce`, `json_path`). The most-used:

| Name                                              | Shape       | Useful members                                                            |
|---------------------------------------------------|-------------|---------------------------------------------------------------------------|
| `sys`                                             | namespace   | `sys.env("VAR")` — read environment variable                              |
| `constants`                                       | namespace   | `constants.hostname`, `constants.os`, `constants.arch`                    |
| `array`                                           | namespace   | `array.concat(a, b)`, `array.combine_maps(...)`                           |
| `convert`                                         | namespace   | `convert.nonsensitive(...)`, type casts                                   |
| `encoding`                                        | namespace   | `encoding.from_json(...)`, `encoding.from_yaml(...)`                      |
| `file`                                            | namespace   | `file.path_join(...)`                                                     |
| `string`                                          | namespace   | `string.to_upper`, `string.to_lower`, `string.replace`, `string.split`    |
| `coalesce(a, b, c)`                               | top-level   | First non-null/non-empty argument                                         |
| `json_path(doc, "$.field")`                       | top-level   | Extract values from a JSON document                                       |

Full reference: https://grafana.com/docs/alloy/latest/reference/stdlib/.

```alloy
// Typical patterns
password = sys.env("GRAFANA_API_KEY")
field    = "spec.nodeName=" + coalesce(sys.env("HOSTNAME"), constants.hostname)
url      = "https://" + sys.env("HOST") + "/api"
config   = encoding.from_json(local.file.json_config.content)
```

## Top-level configuration blocks

Unlike component blocks, these are unlabeled and appear at most once.

```alloy
logging {
  level  = "info"     // debug | info | warn | error
  format = "logfmt"   // logfmt | json
}

http {
  listen_addr = "0.0.0.0:12345"   // Alloy UI + /metrics endpoint
}

tracing {
  sampling_fraction = 0.1
  write_to          = [otelcol.exporter.otlp.default.input]
}

remotecfg {
  url = "https://fleet-management.grafana.net"
  basic_auth {
    username = sys.env("FM_USERNAME")
    password = sys.env("FM_TOKEN")
  }
  poll_interval = "1m"
}

clustering {
  enabled = true
}
```

## Imports and modules

Imported namespaces let you call user-defined components like stdlib functions.

```alloy
// Local file
import.file "utils" {
  filename = "./modules/utils.alloy"
}

// Git
import.git "k8s" {
  repository = "https://github.com/grafana/alloy-modules"
  revision   = "main"
  path       = "modules/kubernetes/"
}

// HTTP
import.http "shared" {
  url            = "https://config-server/alloy/shared.alloy"
  poll_frequency = "5m"
}

// Invoke an imported declare block
utils.my_component "example" {
  arg = "value"
}
```

`declare` defines a reusable component locally:

```alloy
declare "wrapped_scrape" {
  argument "target" { optional = false }
  argument "receiver" { optional = false }

  prometheus.scrape "inner" {
    targets    = [{__address__ = argument.target.value}]
    forward_to = [argument.receiver.value]
  }
}
```

## Durations and sizes

- Durations are Go-style strings: `"30s"`, `"1m"`, `"500ms"`, `"2h30m"`.
- Byte sizes use IEC/SI suffixes where accepted: `"512MiB"`, `"1GB"`.

## Common pitfalls

- **Quoting object keys** is required only when the key isn't a valid identifier (hyphens, dots,
  leading digits): `{"node-name" = "..."}`. Quoting Prometheus-style keys like `__address__` is
  conventional but not required.
- **Trailing commas** are allowed and recommended in multi-line arrays/objects.
- **Component labels** must match references exactly — `prometheus.scrape "api"` is referenced as
  `prometheus.scrape.api.<export>`, not `api.<export>`.
- **Forwarding** uses the recipient's input export — usually `.receiver` (Prometheus/Loki/Pyroscope)
  or `.input` (otelcol).
- **Reloads**: edit and `SIGHUP` the process, or POST `/-/reload` on the HTTP endpoint.

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE