模块
模块 是 Alloy 配置的一个单元,它结合了所有其他概念。它包含配置块、实例化组件和自定义组件定义的组合。您作为参数传递给 run
命令的模块称为 主配置。
导入模块
您可以 导入 模块,以便在其他模块(称为 导入模块)中使用其自定义组件。使用以下导入配置块之一从多个位置导入模块:
import.file
: 从磁盘文件导入模块。import.git
: 从 Git 仓库中的文件导入模块。import.http
: 从 HTTP 请求响应导入模块。import.string
: 从字符串导入模块。
警告
您不能导入包含除
declare
或import
之外的顶级块的模块。
模块被导入到一个 命名空间 中,从而将导入模块的顶级自定义组件暴露给导入模块。导入块的标签指定了导入的命名空间。例如,如果一个配置包含一个名为 import.file "my_module"
的块,那么该模块定义的自定义组件将以 my_module.CUSTOM_COMPONENT_NAME
的形式暴露。导入的命名空间在给定的导入模块中必须是唯一的。
如果导入的命名空间与内置组件命名空间(例如 prometheus
)的名称匹配,则内置命名空间将对导入模块隐藏。仅导入模块中定义的组件可用。
警告
如果您为
import
或declare
块使用的标签与现有组件匹配,则该组件将被遮蔽,并在您的配置中变为不可用。例如,如果您使用标签import.file "mimir"
,您就无法使用以mimir
开头的现有组件,例如mimir.rules.kubernetes
,因为该标签指向导入的模块。
示例
此示例模块定义了一个组件,用于过滤掉调试级别和信息级别的日志行
declare "log_filter" {
// argument.write_to is a required argument that specifies where filtered
// log lines are sent.
//
// The value of the argument is retrieved in this file with
// argument.write_to.value.
argument "write_to" {
optional = false
}
// loki.process.filter is our component which executes the filtering,
// passing filtered logs to argument.write_to.value.
loki.process "filter" {
// Drop all debug- and info-level logs.
stage.match {
selector = `{job!=""} |~ "level=(debug|info)"`
action = "drop"
}
// Send processed logs to our argument.
forward_to = argument.write_to.value
}
// export.filter_input exports a value to the module consumer.
export "filter_input" {
// Expose the receiver of loki.process so the module importer can send
// logs to our loki.process component.
value = loki.process.filter.receiver
}
}
您可以将此模块保存到名为 helpers.alloy
的文件并导入它
// Import our helpers.alloy module, exposing its custom components as
// helpers.COMPONENT_NAME.
import.file "helpers" {
filename = "helpers.alloy"
}
loki.source.file "self" {
targets = LOG_TARGETS
// Forward collected logs to the input of our filter.
forward_to = [helpers.log_filter.default.filter_input]
}
helpers.log_filter "default" {
// Configure the filter to forward filtered logs to loki.write below.
write_to = [loki.write.default.receiver]
}
loki.write "default" {
endpoint {
url = LOKI_URL
}
}
安全性
由于模块可以从潜在的远程源加载任意配置,请仔细考虑解决方案的安全性。最佳实践是确保攻击者无法修改 Alloy 配置。这包括主 Alloy 配置文件和从远程位置(如 Git 仓库或 HTTP 服务器)获取的模块。