检查主机是否处于 Consul 维护模式

Check if host is in Consul in maintenance mode or not

如果给定主机在 Consul (0.8.5) 中处于维护模式,我正在为我们的监控编写一个检查。在命令行上非常简单,因为我可以 运行 consul maint 并获得适当的输出。通过 REST 我可以设置维护模式,但似乎无法检索它。

如何在不解析 Consul 的多行输出的情况下以安全的方式在 shell 脚本中进行检查?

您可以通过http://localhost:8500/v1/health/node/name_of_node检查节点是否处于维护中。如果节点处于维护模式,则输出将包含一个检查 ID 为 _node_maintenance.

的条目
$ curl http://localhost:8500/v1/health/node/name_of_node
[
  {
    "ModifyIndex": 270813,
    "CreateIndex": 270813,
    "ServiceTags": [],
    "Node": "name_of_node",
    "CheckID": "_node_maintenance",
    "Name": "Node Maintenance Mode",
    "Status": "critical",
    "Notes": "Maintenance mode is enabled for this node, but no reason was provided. This is a default message.",
    "Output": "",
    "ServiceID": "",
    "ServiceName": ""
  }
]

以下是获取维护中服务器列表的一些选项:

使用 curl 和 jq:

curl http://localhost:8500/v1/health/service/<serviceName>\?dc\=<dcKey> | jq '.[].Checks[] | select(.CheckID == "_node_maintenance")'

使用 groovy(returns 服务器名称列表):

List<String> getServersInMaintenance(String serviceName, String dc) {
    List<String> serversList = []
    def uri = "/v1/health/service/${serviceName}"

    //* this is a RestClient that takes uri, query and content type
    def response = this.get(uri,
            [dc: dc, passing: false],
            ContentType.JSON
    )

    List allChecks = response.data.Checks
    for (server in allChecks) {
        for(check in server) {
            if (check.Name.contains("Maint") && check.Status.equals("critical")) {
                serversList += "${check.Node}"
            }
        }
    }

    return serversList
}