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

# 导入与导出规则

> 把告警规则导出成按名称引用的规则包，或导入规则包与 Prometheus 告警规则文件。

```http theme={null}
GET  /api/v1/alerts/rules/export
POST /api/v1/alerts/rules/import
```

## 导出

需要 `alerts.rules.read`。查询参数 `ids` 是逗号分开的规则 id，空着是全部规则。返回规则包：

```json theme={null}
{
  "format": "molesignal.alert-rules/v1",
  "exported_at": "2026-10-28T08:00:00Z",
  "rules": [
    {
      "name": "High error rate",
      "description": "",
      "enabled": true,
      "kind": "scheduled",
      "query": {"language": "promql", "statement": "sum(rate(http_requests_total{code=~\"5..\"}[5m]))", "period_secs": 60, "stream": {"name": "http_requests_total", "stream_type": "metrics"}},
      "trigger": {"operator": "gt", "threshold": 5, "for_periods": 2, "silence_secs": 300},
      "thresholds": [],
      "severity": "error",
      "escalation_policy": "Payments on-call",
      "labels": {"service": "checkout"},
      "annotations": {}
    }
  ]
}
```

规则带着全部定义，不带 id、组织、评估状态和时间。`escalation_policy` 是升级策略的名称，没有这一项是默认策略；组合规则的 `query.composite.rules` 里是子规则的名称。心跳规则的打卡地址不在规则包里。

## 导入

需要 `alerts.rules.manage`。

| 字段 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `content` | string | 是 | 规则包（JSON 或 YAML，带 `format`），或 Prometheus 的告警规则文件（顶层 `groups`，或 `PrometheusRule` 的 `spec.groups`），最大 4 MiB，最多 500 条规则。 |
| `dry_run` | boolean | 否 | 默认 `true`，只预演；`false` 才写。 |
| `create_only` | boolean | 否 | `true` 时已有的同名规则不动。 |

每一条按名称对上已有规则：没有就新建，正好一条就比较字段，同名的有几条就报错，文件里同一个名称出现两次也报错。每一条照保存规则时那样检查。有一条出错时什么都不写；没有出错时在一个事务里写进去，逐条发联邦的变更事件，并记一条审计 `alert_rules.imported`。Prometheus 规则怎样换成 MoleSignal 的规则见[导入与导出](https://docs.molesignal.com/zh-Hans/alerting/rules.md#导入与导出)。

```bash cURL theme={null}
curl -X POST http://localhost:5080/api/v1/alerts/rules/import \
  -H "authorization: Bearer $MS_TOKEN" \
  -H "content-type: application/json" \
  -d "$(jq -n --rawfile content rules.yaml '{content: $content, dry_run: true}')"
```

```json 200 theme={null}
{
  "format": "prometheus",
  "items": [
    {"name": "HighErrorRate", "action": "create", "rule_id": "3KF1..."},
    {"name": "DiskFull", "action": "update", "changes": ["query", "trigger"], "rule_id": "3KC9..."},
    {"name": "TargetDown", "action": "error", "error": "no escalation policy is named `ops`"}
  ],
  "notes": ["recording rule `job:errors:rate5m` in group `api` is not imported"],
  "applied": false
}
```

`action` 是 `create`、`update`、`unchanged`、`skip`（`create_only` 时已有的）或 `error`。`applied` 说明写进去了没有。

**错误**

| 状态码 | 原因 |
| - | - |
| `400` | 内容既不是规则包也不是 Prometheus 规则文件，格式名不对，太大或规则太多。 |
| `403` | Token 缺少权限。 |


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