

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 湊集其他 Prometheus 來源並匯入這些指標
<a name="ContainerInsights-Prometheus-Setup-configure"></a>

具有 Prometheus 監控的 CloudWatch 代理程式需要兩種組態來湊集 Prometheus 指標。其中一個是 Prometheus 文件的 [<scrape\_config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 中記錄的標準 Prometheus 湊集組態。另一個適用於 CloudWatch 代理程式組態。

對於 Amazon EKS 叢集，組態在 `prometheus-eks.yaml` (EC2 啟動類型) 或 `prometheus-eks-fargate.yaml` (Fargate 啟動類型) 中定義為兩種組態映射：
+ `name: prometheus-config` 區段包含 Prometheus 湊集的設定。
+ `name: prometheus-cwagentconfig` 區段包含 CloudWatch 代理程式的組態。您可以使用此區段來設定 CloudWatch 收集 Prometheus 指標的方式。例如，您可以將要匯入 CloudWatch 的指標列入白名單，並定義其維度。

對於在 Amazon EC2 執行個體上執行的 Kubernetes 叢集，組態在 `prometheus-k8s.yaml` YAML 檔案中定義為兩種組態映射：
+ `name: prometheus-config` 區段包含 Prometheus 湊集的設定。
+ `name: prometheus-cwagentconfig` 區段包含 CloudWatch 代理程式的組態。

若要湊集其他 Prometheus 指標來源並將這些指標匯入 CloudWatch，您可以修改 Prometheus 湊集組態和 CloudWatch 代理程式組態，然後使用更新的組態重新部署代理程式。

**VPC 安全群組要求**

Prometheus 工作負載安全群組的輸入規則必須開啟到 CloudWatch 代理程式的 Prometheus 連接埠，以便透過私有 IP 擷取 Prometheus 指標。

CloudWatch 代理程式安全群組的輸出規則必須允許 CloudWatch 代理程式透過私有 IP 連接至 Prometheus 工作負載的連接埠。

## Prometheus 湊集組態
<a name="ContainerInsights-Prometheus-Setup-config-global"></a>

CloudWatch 代理程式支援標準 Prometheus 湊集組態，如 Prometheus 文件的 [<scrape\_config>](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) 中所述。您可以編輯此區段來更新已存在於此檔案中的組態，並新增其他 Prometheus 湊集目標。根據預設，範例組態檔案包含下列全域組態行：

```
global:
  scrape_interval: 1m
  scrape_timeout: 10s
```
+ **scrape\_interval**— 定義湊集目標的頻率。
+ **scrape\_timeout**— 定義湊集請求逾時之前要等待的時間。

您也可以在任務層級為這些設定定義不同的數值，以覆寫全域設定。

### Prometheus 湊集任務
<a name="ContainerInsights-Prometheus-Setup-config-scrape"></a>

CloudWatch 代理程式 YAML 檔案已設定一些預設的湊集任務。例如，在 `prometheus-eks.yaml` 中，已在 `scrape_configs` 區段中的 `job_name` 行設定預設湊集任務。在此檔案中，下列預設 `kubernetes-pod-jmx` 區段會湊集 JMX Exporter 指標。

```
   - job_name: 'kubernetes-pod-jmx'
      sample_limit: 10000
      metrics_path: /metrics
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - source_labels: [__address__]
        action: keep
        regex: '.*:9404$'
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - action: replace
        source_labels:
        - __meta_kubernetes_namespace
        target_label: Namespace
      - source_labels: [__meta_kubernetes_pod_name]
        action: replace
        target_label: pod_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_container_name
        target_label: container_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_name
        target_label: pod_controller_name
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_controller_kind
        target_label: pod_controller_kind
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_phase
        target_label: pod_phase
```

會湊集這些預設目標當中的各個目標，並使用內嵌的指標格式將指標傳送到日誌事件中的 CloudWatch。如需詳細資訊，請參閱[在日誌中內嵌指標](CloudWatch_Embedded_Metric_Format.md)。

來自 Amazon EKS 和 Kubernetes 叢集的日誌事件會存放在 CloudWatch Logs 中的 **/aws/containerinsights/{{cluster\_name}}/prometheus** 日誌群組。來自 Amazon ECS 叢集的日誌事件會存放在 **/aws/ecs/containerinsights/{{cluster\_name}}/prometheus** 日誌群組。

每個湊集任務都包含在此日誌群組的不同日誌串流中。例如，Prometheus 湊集任務 `kubernetes-pod-appmesh-envoy` 是針對 App Mesh 所定義。來自 Amazon EKS 和 Kubernetes 叢集的所有 App Mesh Prometheus 指標都會傳送至名為 **/aws/containerinsights/{{cluster\_name}}>prometheus/kubernetes-pod-appmesh-envoy/** 的日誌串流。

若要新增湊集目標，請新增 `job_name` 區段到 YAML 檔案的 `scrape_configs` 區段，然後重新啟動代理程式。如需此程序的範例，請參閱[新增 Prometheus 湊集目標的教學課程：Prometheus API 伺服器指標](#ContainerInsights-Prometheus-Setup-new-exporters)。

## Prometheus 的 CloudWatch 代理程式組態
<a name="ContainerInsights-Prometheus-Setup-cw-agent-config2"></a>

CloudWatch 代理程式組態檔案在 `metrics_collected` 下有一個 `prometheus` 區段可用於 Prometheus 湊集組態。其包含下列組態選項：
+ **cluster\_name**— 指定要在日誌事件中新增為標籤的叢集名稱。此欄位為選用欄位。如果您省略此值，代理程式可以偵測 Amazon EKS 或 Kubernetes 叢集名稱。
+ **log\_group\_name**— 為湊集的 Prometheus 指標指定日誌檔案群組名稱。此欄位為選用欄位。如果您省略此值，CloudWatch 會將 **/aws/containerinsights/{{cluster\_name}}/prometheus** 用於來自 Amazon EKS 和 Kubernetes 叢集的日誌。
+ **prometheus\_config\_path**— 指定 Prometheus 湊集組態檔案路徑。如果此欄位的值以 `env:` 為開頭，則將從容器的環境變數中擷取 Prometheus 湊集組態檔案內容。請不要變更此欄位。
+ **ecs\_service\_discovery**— 是指定 Amazon ECS Prometheus 服務探索組態的區段。如需詳細資訊，請參閱[在 Amazon ECS 叢集上自動探索的詳細指南](ContainerInsights-Prometheus-Setup-autodiscovery-ecs.md)。

  `ecs_service_discovery` 區段可以包含下列欄位：
  + `sd_frequency` 是發現 Prometheus Exporters 的頻率。指定數字和單位尾碼。例如：每分鐘一次 `1m` 或每 30 秒`30s`一次。有效的單位尾碼為`ns`、`us`、`ms`、`s`、`m` 以及 `h`。

    此欄位為選用欄位。預設值為 60 秒 (1 分鐘)。
  + `sd_target_cluster` 是用於自動探索的目標 Amazon ECS 叢集名稱。此欄位為選用欄位。預設是安裝 CloudWatch 代理程式的 Amazon ECS 叢集名稱。
  + `sd_cluster_region` 是目標 Amazon ECS 叢集的區域。此欄位為選用欄位。預設是安裝 CloudWatch 代理程式的 Amazon ECS 叢集區域。
  + `sd_result_file` 是 Prometheus 目標結果的 YAML 檔案路徑。Prometheus 湊集組態將參與此檔案。
  + `docker_label` 是選用區段，您可以用它來指定 Docker 標籤型服務探索的組態。如果您省略此區段，則不會使用 Docker 標籤型探索。此區段可以包含下列欄位：
    + `sd_port_label` 是容器的 Docker 標籤名稱，用於指定 Prometheus 指標的容器連接埠。預設值為 `ECS_PROMETHEUS_EXPORTER_PORT`。如果容器沒有此 Docker 標籤，CloudWatch 代理程式將略過它。
    + `sd_metrics_path_label` 是容器的 Docker 標籤名稱，用於指定 Prometheus 指標路徑。預設值為 `ECS_PROMETHEUS_METRICS_PATH`。如果容器沒有此 Docker 標籤，則代理程式會假設預設路徑 `/metrics`。
    + `sd_job_name_label` 是容器的 Docker 標籤名稱，用於指定 Prometheus 湊集任務名稱。預設值為 `job`。如果容器沒有此 Docker 標籤，CloudWatch 代理程式會在 Prometheus 湊集組態中使用任務名稱。
  + `task_definition_list` 是選用區段，您可以用它來指定任務定義型服務探索的組態。如果您省略此區段，則不會使用任務定義型探索。此區段可以包含下列欄位：
    + `sd_task_definition_arn_pattern` 是用來指定要探索的 Amazon ECS 任務定義的模式。這是規則表達式。
    + `sd_metrics_ports` 列出了 Prometheus 指標的 containerPort。使用分號分隔 containerPorts。
    + `sd_container_name_pattern` 指定了 Amazon ECS 任務容器名稱。這是規則表達式。
    + `sd_metrics_path` 指定了 Prometheus 指標路徑。如果您省略此項，代理程式會假設預設路徑 `/metrics`
    + `sd_job_name` 指定了 Prometheus 湊集任務名稱。如果您省略此欄位，CloudWatch 代理程式會使用 Prometheus 湊集組態中的任務名稱。
+ **metric\_declaration**— 是以要產生之內嵌指標格式來指定日誌陣列的區段。根據預設，CloudWatch 代理程式匯入的每個 Prometheus 來源都有 `metric_declaration` 區段。這些區段各包括下列欄位：
  + `label_matcher` 是一個規則表達式，會檢查 `source_labels` 中列出的標籤值。符合的指標已啟用，可包含在傳送至 CloudWatch 的內嵌指標格式。

    如果您在 `source_labels` 中指定了多個標籤，我們建議您不要在 `label_matcher` 的規則表達式中使用 `^` 或 `$` 字元。
  + `source_labels` 指定由 `label_matcher` 行檢查的標籤值。
  + `label_separator` 指定要在 ` label_matcher` 行中使用的分隔符號 (如果指定多個 `source_labels`)。預設值為 `;`。您可以在下面的範例中看到 `label_matcher` 行中使用此預設值。
  + `metric_selectors` 是一個規則表達式，可指定要收集和傳送至 CloudWatch 的指標。
  + `dimensions` 是要用作為每個所選指標之 CloudWatch 維度的標籤清單。

請參閱以下 `metric_declaration` 範例。

```
"metric_declaration": [
  {
     "source_labels":[ "Service", "Namespace"],
     "label_matcher":"(.*node-exporter.*|.*kube-dns.*);kube-system",
     "dimensions":[
        ["Service", "Namespace"]
     ],
     "metric_selectors":[
        "^coredns_dns_request_type_count_total$"
     ]
  }
]
```

此範例會在符合下列條件時，設定內嵌指標格式區段，以作為日誌事件傳送：
+ `Service` 的數值包含 `node-exporter` 或 `kube-dns`。
+ `Namespace` 的值為 `kube-system`。
+ Prometheus 指標 `coredns_dns_request_type_count_total` 包含 `Service` 和 `Namespace` 標籤。

傳送的日誌事件包含下列反白顯示的區段：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"coredns_dns_request_type_count_total"
            }
         ],
         "Dimensions":[
            [
               "Namespace",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "Namespace":"kube-system",
   "Service":"kube-dns",
   "coredns_dns_request_type_count_total":2562,
   "eks_amazonaws_com_component":"kube-dns",
   "instance":"192.168.61.254:9153",
   "job":"kubernetes-service-endpoints",
   ...
}
```

## 新增 Prometheus 湊集目標的教學課程：Prometheus API 伺服器指標
<a name="ContainerInsights-Prometheus-Setup-new-exporters"></a>

Kubernetes API 伺服器預設會在端點上公開 Prometheus 指標。Kubernetes API 伺服器湊集組態的官方範例可以在 [Github](https://github.com/prometheus/prometheus/blob/main/documentation/examples/prometheus-kubernetes.yml) 上取得。

下列教學說明如何執行下列步驟，開始將 Kubernetes API 伺服器指標匯入 CloudWatch：
+ 將 Kubernetes API 伺服器的 Prometheus 湊集組態新增至 CloudWatch 代理程式 YAML 檔案。
+ 在 CloudWatch 代理程式 YAML 檔案中設定內嵌指標格式指標定義。
+ (選用) 為 Kubernetes API 伺服器指標建立 CloudWatch 儀表板。

**注意**  
Kubernetes API 伺服器會公開量測、計數器、長條圖和摘要指標。在此版本的 Prometheus 指標支援中，CloudWatch 僅會匯入具有量測計、計數器和摘要類型的指標。

**若要開始在 CloudWatch 中收集 Kubernetes API 伺服器 Prometheus 指標**

1. 輸入下列其中一個命令，以下載最新版本的 `prometheus-eks.yaml`、`prometheus-eks-fargate.yaml` 或 `prometheus-k8s.yaml` 檔案。

   對於具有 EC2 啟動類型的 Amazon EKS 叢集，請輸入下列命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml
   ```

   對於具有 Fargate 啟動類型的 Amazon EKS 叢集，請輸入下列命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks-fargate.yaml
   ```

   對於在 Amazon EC2 執行個體上執行的 Kubernetes 叢集，請輸入下列命令：

   ```
   curl -O https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-k8s.yaml
   ```

1. 使用文字編輯器開啟檔案，找出 `prometheus-config` 區段，並在該區段內新增以下區段。儲存變更：

   ```
       # Scrape config for API servers
       - job_name: 'kubernetes-apiservers'
         kubernetes_sd_configs:
           - role: endpoints
             namespaces:
               names:
                 - default
         scheme: https
         tls_config:
           ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
           insecure_skip_verify: true
         bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
         relabel_configs:
         - source_labels: [__meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
           action: keep
           regex: kubernetes;https
         - action: replace
           source_labels:
           - __meta_kubernetes_namespace
           target_label: Namespace
         - action: replace
           source_labels:
           - __meta_kubernetes_service_name
           target_label: Service
   ```

1. 趁文字編輯器中開啟 YAML 檔案時，找出 `cwagentconfig.json` 區段。新增下列子區段並儲存變更。此區段會將 API 伺服器指標放到 CloudWatch 代理程式允許清單上。允許清單中會新增三種類型的 API 伺服器指標：
   + etcd 物件計數
   + API 伺服器註冊控制器指標
   + API 伺服器請求指標

   ```
   {"source_labels": ["job", "resource"],
     "label_matcher": "^kubernetes-apiservers;(services|daemonsets.apps|deployments.apps|configmaps|endpoints|secrets|serviceaccounts|replicasets.apps)",
     "dimensions": [["ClusterName","Service","resource"]],
     "metric_selectors": [
     "^etcd_object_counts$"
     ]
   },
   {"source_labels": ["job", "name"],
      "label_matcher": "^kubernetes-apiservers;APIServiceRegistrationController$",
      "dimensions": [["ClusterName","Service","name"]],
      "metric_selectors": [
      "^workqueue_depth$",
      "^workqueue_adds_total$",
      "^workqueue_retries_total$"
     ]
   },
   {"source_labels": ["job","code"],
     "label_matcher": "^kubernetes-apiservers;2[0-9]{2}$",
     "dimensions": [["ClusterName","Service","code"]],
     "metric_selectors": [
      "^apiserver_request_total$"
     ]
   },
   {"source_labels": ["job"],
     "label_matcher": "^kubernetes-apiservers",
     "dimensions": [["ClusterName","Service"]],
     "metric_selectors": [
     "^apiserver_request_total$"
     ]
   },
   ```

1. 如果您已在叢集中部署具有 Prometheus 支援的 CloudWatch 代理程式，則必須輸入下列命令來刪除它：

   ```
   kubectl delete deployment cwagent-prometheus -n amazon-cloudwatch
   ```

1. 輸入下列其中一個命令，以更新的組態來部署 CloudWatch 代理程式：對於具有 EC2 啟動類型的 Amazon EKS 叢集，請輸入：

   ```
   kubectl apply -f prometheus-eks.yaml
   ```

   對於具有 Fargate 啟動類型的 Amazon EKS 叢集，請輸入下列命令。將 {{MyCluster}} 和 {{region}} 取代為可比對部署的數值。

   ```
   cat prometheus-eks-fargate.yaml \
   | sed "s/{{cluster_name}}/{{MyCluster}}/;s/{{region_name}}/{{region}}/" \
   | kubectl apply -f -
   ```

   對於 Kubernetes 叢集，請輸入下列命令。將 {{MyCluster}} 和 {{region}} 取代為可比對部署的數值。

   ```
   cat prometheus-k8s.yaml \
   | sed "s/{{cluster_name}}/{{MyCluster}}/;s/{{region_name}}/{{region}}/" \
   | kubectl apply -f -
   ```

完成此操作後，您應該在 **/aws/containerinsights/{{cluster\_name}}/prometheus** 日誌群組中查看名為** kubernetes-apiservers **的新日誌串流。此日誌串流應該包含具有內嵌指標格式定義的日誌事件，如下所示：

```
{
   "CloudWatchMetrics":[
      {
         "Metrics":[
            {
               "Name":"apiserver_request_total"
            }
         ],
         "Dimensions":[
            [
               "ClusterName",
               "Service"
            ]
         ],
         "Namespace":"ContainerInsights/Prometheus"
      }
   ],
   "ClusterName":"my-cluster-name",
   "Namespace":"default",
   "Service":"kubernetes",
   "Timestamp":"1592267020339",
   "Version":"0",
   "apiserver_request_count":0,
   "apiserver_request_total":0,
   "code":"0",
   "component":"apiserver",
   "contentType":"application/json",
   "instance":"192.0.2.0:443",
   "job":"kubernetes-apiservers",
   "prom_metric_type":"counter",
   "resource":"pods",
   "scope":"namespace",
   "verb":"WATCH",
   "version":"v1"
}
```

您可以在 **ContainerInsights/Prometheus** 命名空間中的 CloudWatch 主控台中，檢視您的指標。您也可以選擇為您的 Prometheus Kubernetes API 伺服器指標建立 CloudWatch 儀表板。

### (選用) 為 Kubernetes API 伺服器指標建立儀表板。
<a name="ContainerInsights-Prometheus-Setup-KPI-dashboard"></a>

若要在儀表板中查看 Kubernetes API 伺服器指標，您必須先完成先前章節中的步驟，才能開始在 CloudWatch 中收集這些指標。

**若要建立 Kubernetes API 伺服器指標的儀表板**

1. 透過 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 開啟 CloudWatch 主控台。

1. 請確定您已選取正確的 AWS 區域。

1. 在導覽窗格中，選擇 **Dashboards** (儀表板)。

1. 選擇 **Create Dashboard (建立儀表板)**。輸入新儀表板的名稱，然後選擇 **Create dashboard (建立儀表板)**。

1. 在 **Add to this dashboard (新增至此儀表板)** 中，選擇 **Cancel (取消)**。

1. 選擇 **Actions (動作)**、**View/edit sources (檢視/編輯來源)**。

1. 下載下列 JSON 檔案：[Kubernetes API 儀表板來源](https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/sample_cloudwatch_dashboards/kubernetes_api_server/cw_dashboard_kubernetes_api_server.json)。

1. 使用文字編輯器開啟您下載的 JSON 檔案，然後進行下列變更：
   + 將所有 `{{YOUR_CLUSTER_NAME}}` 字串取代為您叢集的確切名稱。確定不要在文字前後加空格。
   + 將所有 `{{YOUR_AWS_REGION}}` 字串取代為收集指標的區域的名稱。例如 `us-west-2`。確定不要在文字前後加空格。

1. 複製整個 JSON blob 並將其貼入 CloudWatch 主控台的文字方塊中，取代方塊中已經存在的內容。

1. 選擇 **Update (更新)**、**Save dashboard (儲存儀表板)**。