

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 [AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# 使用 的 CloudWatch 範例 AWS CLI
<a name="cli_2_cloudwatch_code_examples"></a>

下列程式碼範例示範如何使用 AWS Command Line Interface 搭配 CloudWatch 執行動作和實作常見案例。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

每個範例均包含完整原始碼的連結，您可在連結中找到如何設定和執行內容中程式碼的相關指示。

**Topics**
+ [動作](#actions)

## 動作
<a name="actions"></a>

### `delete-alarms`
<a name="cloudwatch_DeleteAlarms_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `delete-alarms`。

**AWS CLI**  
**刪除警示**  
下列範例會使用 `delete-alarms` 命令刪除名為「myalarm」的 Amazon CloudWatch 警示：  

```
aws cloudwatch delete-alarms --alarm-names myalarm
```
輸出：  

```
This command returns to the prompt if successful.
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteAlarms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-alarms.html)。

### `delete-anomaly-detector`
<a name="cloudwatch_DeleteAnomalyDetector_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `delete-anomaly-detector`。

**AWS CLI**  
**刪除指定的異常偵測模型**  
下列 `delete-anomaly-detector` 範例會刪除指定帳戶中的異常偵測器模型。  

```
aws cloudwatch delete-anomaly-detector \
    --namespace AWS/Logs \
    --metric-name IncomingBytes \
    --stat SampleCount
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[刪除異常偵測模型](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Anomaly_Detection_Alarm.html#Delete_Anomaly_Detection_Model)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteAnomalyDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-anomaly-detector.html)。

### `delete-dashboards`
<a name="cloudwatch_DeleteDashboards_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `delete-dashboards`。

**AWS CLI**  
**刪除指定的儀表板**  
下列 `delete-dashboards` 範例會刪除指定帳戶中兩個名為 `Dashboard-A` 和 `Dashboard-B` 的儀表板。  

```
aws cloudwatch delete-dashboards \
    --dashboard-names Dashboard-A Dashboard-B
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Amazon CloudWatch 儀表板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteDashboards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-dashboards.html)。

### `delete-insight-rules`
<a name="cloudwatch_DeleteInsightRules_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `delete-insight-rules`。

**AWS CLI**  
**刪除指定的 Contributor Insights 規則**  
下列 `delete-insight-rules` 範例刪除指定帳戶中名為 `Rule-A` 和 `Rule-B` 的兩個 Contributor Insights 規則。  

```
aws cloudwatch delete-insight-rules \
    --rule-names Rule-A Rule-B
```
輸出：  

```
{
    "Failures": []
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Contributor Insights 分析高基數資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-insight-rules.html)。

### `delete-metric-stream`
<a name="cloudwatch_DeleteMetricStream_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `delete-metric-stream`。

**AWS CLI**  
**刪除指定的指標串流**  
下列 `delete-metric-stream` 範例刪除指定帳戶中名為 `QuickPartial-gSCKvO` 的指標串流。  

```
aws cloudwatch delete-metric-stream \
    --name QuickPartial-gSCKvO
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-metric-stream.html)。

### `describe-alarm-history`
<a name="cloudwatch_DescribeAlarmHistory_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `describe-alarm-history`。

**AWS CLI**  
**若要擷取警示的歷史記錄**  
下列範例會使用 `describe-alarm-history` 命令擷取名為「myalarm」的 Amazon CloudWatch 警示的歷史記錄：  

```
aws cloudwatch describe-alarm-history --alarm-name "myalarm" --history-item-type StateUpdate
```
輸出：  

```
{
    "AlarmHistoryItems": [
        {
            "Timestamp": "2014-04-09T18:59:06.442Z",
            "HistoryItemType": "StateUpdate",
            "AlarmName": "myalarm",
            "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"testing purposes\"},\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].\",\"stateReasonData\":{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}}}",
            "HistorySummary": "Alarm updated from ALARM to OK"
        },
        {
            "Timestamp": "2014-04-09T18:59:05.805Z",
            "HistoryItemType": "StateUpdate",
            "AlarmName": "myalarm",
            "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.839999999999996, 39.714].\",\"stateReasonData\":{\"version\":\"1.0\",\"queryDate\":\"2014-03-11T22:45:41.569+0000\",\"startDate\":\"2014-03-11T22:30:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.839999999999996,39.714],\"threshold\":70.0}},\"newState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"testing purposes\"}}",
            "HistorySummary": "Alarm updated from OK to ALARM"
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱*《AWS CLI 命令參考》*中的 [DescribeAlarmHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarm-history.html)。

### `describe-alarms-for-metric`
<a name="cloudwatch_DescribeAlarmsForMetric_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `describe-alarms-for-metric`。

**AWS CLI**  
**顯示與指標相關聯的警示資訊**  
下列範例使用 `describe-alarms-for-metric` 命令，顯示與 Amazon EC2 CPUUtilization 指標和 ID 為 i-0c986c72 的執行個體相關聯之任何警示的資訊：  

```
aws cloudwatch describe-alarms-for-metric --metric-name CPUUtilization --namespace AWS/EC2 --dimensions Name=InstanceId,Value=i-0c986c72
```
輸出：  

```
{
    "MetricAlarms": [
        {
            "EvaluationPeriods": 10,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:myHighCpuAlarm2",
            "StateUpdatedTimestamp": "2013-10-30T03:03:51.479Z",
            "AlarmConfigurationUpdatedTimestamp": "2013-10-30T03:03:50.865Z",
            "ComparisonOperator": "GreaterThanOrEqualToThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:111122223333:NotifyMe"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2013-10-30T03:03:51.479+0000\",\"startDate\":\"2013-10-30T02:08:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[40.698,39.612,42.432,39.796,38.816,42.28,42.854,40.088,40.760000000000005,41.316],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myHighCpuAlarm2",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 10 datapoints were not greater than or equal to the threshold (70.0). The most recent datapoints: [40.760000000000005, 41.316].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": true,
            "MetricName": "CPUUtilization"
        },
        {
            "EvaluationPeriods": 2,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:myHighCpuAlarm",
            "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z",
            "AlarmConfigurationUpdatedTimestamp": "2014-04-09T22:26:05.958Z",
            "ComparisonOperator": "GreaterThanThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:111122223333:HighCPUAlarm"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myHighCpuAlarm",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": false,
            "MetricName": "CPUUtilization"
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱*《AWS CLI 命令參考》*中的 [DescribeAlarmsForMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarms-for-metric.html)。

### `describe-alarms`
<a name="cloudwatch_DescribeAlarms_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `describe-alarms`。

**AWS CLI**  
**列出有關警示的資訊**  
下列範例使用 `describe-alarms` 命令提供名為「myalarm」的警示相關資訊：  

```
aws cloudwatch describe-alarms --alarm-names "myalarm"
```
輸出：  

```
{
    "MetricAlarms": [
        {
            "EvaluationPeriods": 2,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:123456789012:alarm:myalarm",
            "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z",
            "AlarmConfigurationUpdatedTimestamp": "2012-12-27T00:49:54.032Z",
            "ComparisonOperator": "GreaterThanThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:123456789012:myHighCpuAlarm"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myalarm",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": true,
            "MetricName": "CPUUtilization"
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱*《AWS CLI 命令參考》*中的 [DescribeAlarms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarms.html)。

### `describe-anomaly-detectors`
<a name="cloudwatch_DescribeAnomalyDetectors_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `describe-anomaly-detectors`。

**AWS CLI**  
**擷取異常偵測模型的清單**  
下列 `describe-anomaly-detectors` 範例顯示與指定帳戶中 `AWS/Logs` 命名空間相關聯的異常偵測器模型相關資訊。  

```
aws cloudwatch describe-anomaly-detectors \
    --namespace AWS/Logs
```
輸出：  

```
{
    "AnomalyDetectors": [
        {
            "Namespace": "AWS/Logs",
            "MetricName": "IncomingBytes",
            "Dimensions": [],
            "Stat": "SampleCount",
            "Configuration": {
                "ExcludedTimeRanges": []
            },
            "StateValue": "TRAINED",
            "SingleMetricAnomalyDetector": {
                "AccountId": "123456789012",
                "Namespace": "AWS/Logs",
                "MetricName": "IncomingBytes",
                "Dimensions": [],
                "Stat": "SampleCount"
            }
        },
        {
            "Namespace": "AWS/Logs",
            "MetricName": "IncomingBytes",
            "Dimensions": [
                {
                    "Name": "LogGroupName",
                    "Value": "demo"
                }
            ],
            "Stat": "Average",
            "Configuration": {
                "ExcludedTimeRanges": []
            },
            "StateValue": "PENDING_TRAINING",
            "SingleMetricAnomalyDetector": {
                "AccountId": "123456789012",
                "Namespace": "AWS/Logs",
                "MetricName": "IncomingBytes",
                "Dimensions": [
                    {
                        "Name": "LogGroupName",
                        "Value": "demo"
                    }
                ],
                "Stat": "Average"
            }
        }
    ]
}
```
如需詳細資訊，請參閱*《Amazon CloudWatch 使用者指南》*中的[使用 CloudWatch 異常偵測](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeAnomalyDetectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-anomaly-detectors.html)。

### `describe-insight-rules`
<a name="cloudwatch_DescribeInsightRules_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `describe-insight-rules`。

**AWS CLI**  
**擷取 Contributor Insights 規則的清單**  
下列 `describe-insight-rules` 範例顯示指定帳戶中的所有 Contributor Insights 規則。  

```
aws cloudwatch describe-insight-rules
```
輸出：  

```
{
    "InsightRules": [
        {
            "Name": "Rule-A",
            "State": "ENABLED",
            "Schema": "CloudWatchLogRule/1",
            "Definition": "{\n\t\"AggregateOn\": \"Count\",\n\t\"Contribution\": {\n\t\t\"Filters\": [],\n\t\t\"Keys\": [\n\t\t\t\"$.requestId\"\n\t\t]\n\t},\n\t\"LogFormat\": \"JSON\",\n\t\"Schema\": {\n\t\t\"Name\": \"CloudWatchLogRule\",\n\t\t\"Version\": 1\n\t},\n\t\"LogGroupARNs\": [\n\t\t\"arn:aws:logs:us-east-1:123456789012:log-group:demo\"\n\t]\n}",
            "ManagedRule": false
        },
        {
            "Name": "Rule-B",
            "State": "ENABLED",
            "Schema": "CloudWatchLogRule/1",
            "Definition": "{\n\t\"AggregateOn\": \"Count\",\n\t\"Contribution\": {\n\t\t\"Filters\": [],\n\t\t\"Keys\": [\n\t\t\t\"$.requestId\"\n\t\t]\n\t},\n\t\"LogFormat\": \"JSON\",\n\t\"Schema\": {\n\t\t\"Name\": \"CloudWatchLogRule\",\n\t\t\"Version\": 1\n\t},\n\t\"LogGroupARNs\": [\n\t\t\"arn:aws:logs:us-east-1:123456789012:log-group:demo-1\"\n\t]\n}",
            "ManagedRule": false
        }
    ]
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Contributor Insights 分析高基數資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-insight-rules.html)。

### `disable-alarm-actions`
<a name="cloudwatch_DisableAlarmActions_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `disable-alarm-actions`。

**AWS CLI**  
**停用警示的動作**  
下列範例使用 `disable-alarm-actions` 命令來停用名為 myalarm 之警示的所有動作：  

```
aws cloudwatch disable-alarm-actions --alarm-names myalarm
```
如果成功，此命令會回到提示字元。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DisableAlarmActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/disable-alarm-actions.html)。

### `disable-insight-rules`
<a name="cloudwatch_DisableInsightRules_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `disable-insight-rules`。

**AWS CLI**  
**停用指定的 Contributor Insights 規則**  
下列 `disable-insight-rules` 範例在指定帳戶中停用兩個名為 `Rule-A` 和 `Rule-B` 的 Contributor Insights 規則。  

```
aws cloudwatch disable-insight-rules \
    --rule-names Rule-A Rule-B
```
輸出：  

```
{
    "Failures": []
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Contributor Insights 分析高基數資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DisableInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/disable-insight-rules.html)。

### `enable-alarm-actions`
<a name="cloudwatch_EnableAlarmActions_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `enable-alarm-actions`。

**AWS CLI**  
**啟用警示的所有動作**  
下列範例使用 `enable-alarm-actions` 命令來啟用名為 myalarm 之警示的所有動作：  

```
aws cloudwatch enable-alarm-actions --alarm-names myalarm
```
如果成功，此命令會回到提示字元。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [EnableAlarmActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/enable-alarm-actions.html)。

### `enable-insight-rules`
<a name="cloudwatch_EnableInsightRules_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `enable-insight-rules`。

**AWS CLI**  
**啟用指定的 Contributor Insights 規則**  
下列 `enable-insight-rules` 範例啟用指定帳戶中名為 `Rule-A` 和 `Rule-B` 的兩個 Contributor Insights 規則。  

```
aws cloudwatch enable-insight-rules \
    --rule-names Rule-A Rule-B
```
輸出：  

```
{
    "Failures": []
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Contributor Insights 分析高基數資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [EnableInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/enable-insight-rules.html)。

### `get-dashboard`
<a name="cloudwatch_GetDashboard_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-dashboard`。

**AWS CLI**  
**擷取儀表板相關資訊**  
下列 `get-dashboard` 範例顯示指定帳戶中名為 `Dashboard-A` 的儀表板相關資訊。  

```
aws cloudwatch get-dashboard \
    --dashboard-name Dashboard-A
```
輸出：  

```
{
    "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A",
    "DashboardBody": "{\"widgets\":[{\"type\":\"metric\",\"x\":0,\"y\":0,\"width\":6,\"height\":6,\"properties\":{\"view\":\"timeSeries\",\"stacked\":false,\"metrics\":[[\"AWS/EC2\",\"NetworkIn\",\"InstanceId\",\"i-0131f062232ade043\"],[\".\",\"NetworkOut\",\".\",\".\"]],\"region\":\"us-east-1\"}}]}",
    "DashboardName": "Dashboard-A"
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Amazon CloudWatch 儀表板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-dashboard.html)。

### `get-insight-rule-report`
<a name="cloudwatch_GetInsightRuleReport_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-insight-rule-report`。

**AWS CLI**  
**擷取 Contributor Insights 規則收集的時間序列資料**  
下列 `get-insight-rule-report` 範例傳回 Contributor Insights 規則收集的時間序列資料。  

```
aws cloudwatch get-insight-rule-report \
    --rule-name Rule-A \
    --start-time 2024-10-13T20:15:00Z \
    --end-time 2024-10-13T20:30:00Z \
    --period 300
```
輸出：  

```
{
    "KeyLabels": [
        "PartitionKey"
    ],
    "AggregationStatistic": "Sum",
    "AggregateValue": 0.5,
    "ApproximateUniqueCount": 1,
    "Contributors": [
        {
            "Keys": [
                "RequestID"
            ],
            "ApproximateAggregateValue": 0.5,
            "Datapoints": [
                {
                    "Timestamp": "2024-10-13T21:00:00+00:00",
                    "ApproximateValue": 0.5
                }
            ]
        }
    ],
    "RuleAttributes": []
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Contributor Insights 分析高基數資料](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetInsightRuleReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-insight-rule-report.html)。

### `get-metric-data`
<a name="cloudwatch_GetMetricData_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-metric-data`。

**AWS CLI**  
**範例 1：使用數學運算式取得指定 EC2 的平均總 IOPS**  
下列 `get-metric-data` 範例使用結合 `EBSReadOps` 和 `EBSWriteOps` 指標的指標數學運算式，擷取具有 InstanceID `i-abcdef` 之 EC2 執行個體的 CloudWatch 指標值。  

```
aws cloudwatch get-metric-data \
    --metric-data-queries file://file.json \
    --start-time 2024-09-29T22:10:00Z \
    --end-time 2024-09-29T22:15:00Z
```
`file.json` 的內容：  

```
[
    {
        "Id": "m3",
        "Expression": "(m1+m2)/300",
        "Label": "Avg Total IOPS"
    },
    {
        "Id": "m1",
        "MetricStat": {
            "Metric": {
                "Namespace": "AWS/EC2",
                "MetricName": "EBSReadOps",
                "Dimensions": [
                    {
                        "Name": "InstanceId",
                        "Value": "i-abcdef"
                    }
                ]
            },
            "Period": 300,
            "Stat": "Sum",
            "Unit": "Count"
        },
        "ReturnData": false
    },
    {
        "Id": "m2",
        "MetricStat": {
            "Metric": {
                "Namespace": "AWS/EC2",
                "MetricName": "EBSWriteOps",
                "Dimensions": [
                    {
                        "Name": "InstanceId",
                        "Value": "i-abcdef"
                    }
                ]
            },
            "Period": 300,
            "Stat": "Sum",
            "Unit": "Count"
        },
        "ReturnData": false
    }
]
```
輸出：  

```
{
    "MetricDataResults": [
        {
            "Id": "m3",
            "Label": "Avg Total IOPS",
            "Timestamps": [
                "2024-09-29T22:10:00+00:00"
            ],
            "Values": [
                96.85
            ],
            "StatusCode": "Complete"
        }
    ],
    "Messages": []
}
```
**範例 2：使用 CloudWatch 帳單指標監控預估 AWS 費用**  
下列`get-metric-data`範例會從 AWS/計費命名空間擷取 `EstimatedCharges` CloudWatch 指標。  

```
aws cloudwatch get-metric-data \
    --metric-data-queries '[{"Id":"m1","MetricStat":{"Metric":{"Namespace":"AWS/Billing","MetricName":"EstimatedCharges","Dimensions":[{"Name":"Currency","Value":"USD"}]},"Period":21600,"Stat":"Maximum"}}]' \
    --start-time 2024-09-26T12:00:00Z \
    --end-time 2024-09-26T18:00:00Z \
    --region us-east-1
```
輸出：  

```
{
    "MetricDataResults": [
        {
            "Id": "m1",
            "Label": "EstimatedCharges",
            "Timestamps": [
                "2024-09-26T12:00:00+00:00"
            ],
            "Values": [
                542.38
            ],
            "StatusCode": "Complete"
        }
    ],
    "Messages": []
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用數學運算式和 CloudWatch 指標](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-data.html)。

### `get-metric-statistics`
<a name="cloudwatch_GetMetricStatistics_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-metric-statistics`。

**AWS CLI**  
**取得每個 EC2 執行個體的 CPU 使用率**  
下列範例使用 `get-metric-statistics` 命令來取得 ID 為 i-abcdef 之 EC2 執行個體的 CPU 使用率。  

```
aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start-time 2014-04-08T23:18:00Z --end-time 2014-04-09T23:18:00Z --period 3600 --namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=i-abcdef
```
輸出：  

```
{
    "Datapoints": [
        {
            "Timestamp": "2014-04-09T11:18:00Z",
            "Maximum": 44.79,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T20:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T19:18:00Z",
            "Maximum": 50.85,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T09:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T03:18:00Z",
            "Maximum": 76.84,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T21:18:00Z",
            "Maximum": 48.96,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T14:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T08:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T16:18:00Z",
            "Maximum": 45.55,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T06:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T13:18:00Z",
            "Maximum": 45.08,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T05:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T18:18:00Z",
            "Maximum": 46.88,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T17:18:00Z",
            "Maximum": 52.08,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T07:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T02:18:00Z",
            "Maximum": 51.23,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T12:18:00Z",
            "Maximum": 47.67,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-08T23:18:00Z",
            "Maximum": 46.88,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T10:18:00Z",
            "Maximum": 51.91,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T04:18:00Z",
            "Maximum": 47.13,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T15:18:00Z",
            "Maximum": 48.96,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T00:18:00Z",
            "Maximum": 48.16,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T01:18:00Z",
            "Maximum": 49.18,
            "Unit": "Percent"
        }
    ],
    "Label": "CPUUtilization"
}
```
**指定多個維度**  
下列範例說明如何指定多個維度。每個維度都指定為「名稱/值」對，名稱和值之間用逗號分隔。使用空格分隔多個維度。如果單一指標包含多個維度，則必須為每個定義的維度指定值。  
如需有關使用 `get-metric-statistics` 命令的更多範例，請參閱《Amazon CloudWatch 開發人員指南》**中的「取得指標的統計資料」。  

```
aws cloudwatch get-metric-statistics --metric-name Buffers --namespace MyNameSpace --dimensions Name=InstanceID,Value=i-abcdef Name=InstanceType,Value=m1.small --start-time 2016-10-15T04:00:00Z --end-time 2016-10-19T07:00:00Z --statistics Average --period 60
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetMetricStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-statistics.html)。

### `get-metric-stream`
<a name="cloudwatch_GetMetricStream_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-metric-stream`。

**AWS CLI**  
**擷取指標串流的相關資訊**  
下列 `get-metric-stream` 範例顯示指定帳戶中名為 `QuickFull-GuaFbs` 的指標串流的相關資訊。  

```
aws cloudwatch get-metric-stream \
    --name QuickFull-GuaFbs
```
輸出：  

```
{
    "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs",
    "Name": "QuickFull-GuaFbs",
    "FirehoseArn": "arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG",
    "RoleArn": "arn:aws:iam::123456789012:role/service-role/MetricStreams-FirehosePutRecords-JN10W9B3",
    "State": "running",
    "CreationDate": "2024-10-11T18:48:59.187000+00:00",
    "LastUpdateDate": "2024-10-11T18:48:59.187000+00:00",
    "OutputFormat": "json",
    "IncludeLinkedAccountsMetrics": false
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-stream.html)。

### `get-metric-widget-image`
<a name="cloudwatch_GetMetricWidgetImage_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `get-metric-widget-image`。

**AWS CLI**  
**擷取 CPUUtilization 的快照圖形**  
下列 `get-metric-widget-image` 範例使用 ID `i-abcde` 擷取 EC2 執行個體指標 `CPUUtilization` 的快照圖形，並將擷取的影像儲存為本機電腦上名為 "image.png" 的檔案。  

```
aws cloudwatch get-metric-widget-image \
    --metric-widget '{"metrics":[["AWS/EC2","CPUUtilization","InstanceId","i-abcde"]]}' \
    --output-format png \
    --output text | base64 --decode > image.png
```
此命令不會產生輸出。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetMetricWidgetImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-widget-image.html)。

### `list-dashboards`
<a name="cloudwatch_ListDashboards_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `list-dashboards`。

**AWS CLI**  
**擷取儀表板清單**  
下列 `list-dashboards` 範例列出指定帳戶中的所有儀表板。  

```
aws cloudwatch list-dashboards
```
輸出：  

```
{
    "DashboardEntries": [
        {
            "DashboardName": "Dashboard-A",
            "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A",
            "LastModified": "2024-10-11T18:40:11+00:00",
            "Size": 271
        },
        {
            "DashboardName": "Dashboard-B",
            "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-B",
            "LastModified": "2024-10-11T18:44:41+00:00",
            "Size": 522
        }
    ]
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 Amazon CloudWatch 儀表板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListDashboards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-dashboards.html)。

### `list-metric-streams`
<a name="cloudwatch_ListMetricStreams_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `list-metric-streams`。

**AWS CLI**  
**擷取指標串流清單**  
下列 `list-metric-streams` 範例列出指定帳戶中的所有指標串流。  

```
aws cloudwatch list-metric-streams
```
輸出：  

```
{
    "Entries": [
        {
            "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs",
            "CreationDate": "2024-10-11T18:48:59.187000+00:00",
            "LastUpdateDate": "2024-10-11T18:48:59.187000+00:00",
            "Name": "QuickFull-GuaFbs",
            "FirehoseArn": "arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG",
            "State": "running",
            "OutputFormat": "json"
        }
    ]
}
```
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-metric-streams.html)。

### `list-metrics`
<a name="cloudwatch_ListMetrics_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `list-metrics`。

**AWS CLI**  
**列出 Amazon SNS 的指標**  
下列 `list-metrics` 範例顯示 Amazon SNS 的指標。  

```
aws cloudwatch list-metrics \
    --namespace "AWS/SNS"
```
輸出：  

```
{
    "Metrics": [
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "PublishSize"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "PublishSize"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfNotificationsFailed"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfNotificationsDelivered"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfMessagesPublished"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfMessagesPublished"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfNotificationsDelivered"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfNotificationsFailed"
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListMetrics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-metrics.html)。

### `list-tags-for-resource`
<a name="cloudwatch_ListTagsForResource_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `list-tags-for-resource`。

**AWS CLI**  
**列出與現有警示相關聯的標籤\$1**  
下列 `list-tags-for-resource` 範例列出與指定帳戶中名為 `demo` 的警示相關聯的所有標籤。  

```
aws cloudwatch list-tags-for-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo
```
輸出：  

```
{
    "Tags": [
        {
            "Key": "stack",
            "Value": "Production"
        },
        {
            "Key": "team",
            "Value": "Devops"
        }
    ]
}
```
如需詳細資訊，請參閱《Amazon CloudWatch 使用者指南》**中的[警示和標記](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_alarms_and_tagging.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-tags-for-resource.html)。

### `put-anomaly-detector`
<a name="cloudwatch_PutAnomalyDetector_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-anomaly-detector`。

**AWS CLI**  
**建立異常偵測模型**  
下列 `put-anomaly-detector` 範例會為 CloudWatch 指標建立異常偵測模型。  

```
aws cloudwatch put-anomaly-detector \
    --namespace AWS/Logs \
    --metric-name IncomingBytes \
    --stat SampleCount
```
此命令不會產生輸出。  
如需詳細資訊，請參閱*《Amazon CloudWatch 使用者指南》*中的[使用 CloudWatch 異常偵測](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutAnomalyDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-anomaly-detector.html)。

### `put-composite-alarm`
<a name="cloudwatch_PutCompositeAlarm_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-composite-alarm`。

**AWS CLI**  
**建立複合 CloudWatch 警示。**  
下列 `put-composite-alarm` 範例在指定的帳戶中建立名為 `ProdAlarm` 的複合警示。  

```
aws cloudwatch put-composite-alarm \
    --alarm-name ProdAlarm \
    --alarm-rule "ALARM(CPUUtilizationTooHigh) AND ALARM(MemUsageTooHigh)" \
    --alarm-actions arn:aws:sns:us-east-1:123456789012:demo \
    --actions-enabled
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[建立複合警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Composite_Alarm_How_To.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutCompositeAlarm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-composite-alarm.html)。

### `put-dashboard`
<a name="cloudwatch_PutDashboard_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-dashboard`。

**AWS CLI**  
**建立儀表板**  
下列 `put-dashboard` 範例在指定的帳戶中建立名為 `Dashboard-A` 的儀表板。  

```
aws cloudwatch put-dashboard \
    --dashboard-name Dashboard-A \
    --dashboard-body '{"widgets":[{"height":6,"width":6,"y":0,"x":0,"type":"metric","properties":{"view":"timeSeries","stacked":false,"metrics":[["Namespace","CPUUtilization","Environment","Prod","Type","App"]],"region":"us-east-1"}}]}'
```
輸出：  

```
{
    "DashboardValidationMessages": []
}
```
如需更多詳細資訊，請參閱*《Amazon CloudWatch 使用者指南》*中的[建立 CloudWatch 儀表板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create_dashboard.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-dashboard.html)。

### `put-insight-rule`
<a name="cloudwatch_PutInsightRule_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-insight-rule`。

**AWS CLI**  
**建立 Contributor Insights 規則**  
下列 `put-insight-rule` 範例在指定帳戶中建立名為 `VPCFlowLogsContributorInsights` 的 Contributor Insights 規則。  

```
aws cloudwatch put-insight-rule \
    --rule-name VPCFlowLogsContributorInsights \
    --rule-definition file://insight-rule.json \
    --rule-state ENABLED
```
`insight-rule.json` 的內容：  

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "AggregateOn": "Count",
    "Contribution": {
        "Filters": [],
        "Keys": [
            "tcp-flag"
        ]
    },
    "LogFormat": "CLF",
    "LogGroupNames": [
        "/vpc/flowlogs/*"
    ],
    "Fields": {
        "23": "tcp-flag"
    }
}
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《Amazon CloudWatch 使用者指南》**中的[在 CloudWatch 中建立 Contributor Insights 規則](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights-CreateRule.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutInsightRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-insight-rule.html)。

### `put-metric-alarm`
<a name="cloudwatch_PutMetricAlarm_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-metric-alarm`。

**AWS CLI**  
**在 CPU 使用率超過 70% 時傳送 Amazon Simple Notification Service 電子郵件訊息**  
以下範例使用 `put-metric-alarm` 命令，在 CPU 使用率超過 70% 時傳送 Amazon Simple Notification Service 電子郵件訊息：  

```
aws cloudwatch put-metric-alarm --alarm-name cpu-mon --alarm-description "Alarm when CPU exceeds 70 percent" --metric-name CPUUtilization --namespace AWS/EC2 --statistic Average --period 300 --threshold 70 --comparison-operator GreaterThanThreshold  --dimensions "Name=InstanceId,Value=i-12345678" --evaluation-periods 2 --alarm-actions arn:aws:sns:us-east-1:111122223333:MyTopic --unit Percent
```
如果成功，此命令會回到提示字元。如果已存在具有相同名稱的警示，將會被新警示所覆寫。  
**指定多個維度**  
下列範例說明如何指定多個維度。每個維度都指定為「名稱/值」對，名稱和值之間用逗號分隔。多個維度由空格分隔：  

```
aws cloudwatch put-metric-alarm --alarm-name "Default_Test_Alarm3" --alarm-description "The default example alarm" --namespace "CW EXAMPLE METRICS" --metric-name Default_Test --statistic Average --period 60 --evaluation-periods 3 --threshold 50 --comparison-operator GreaterThanOrEqualToThreshold --dimensions Name=key1,Value=value1 Name=key2,Value=value2
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutMetricAlarm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-alarm.html)。

### `put-metric-data`
<a name="cloudwatch_PutMetricData_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-metric-data`。

**AWS CLI**  
**將自訂指標發布至 Amazon CloudWatch**  
下列範例使用 `put-metric-data` 命令將自訂指標發布至 Amazon CloudWatch：  

```
aws cloudwatch put-metric-data --namespace "Usage Metrics" --metric-data file://metric.json
```
指標本身的值會儲存在 JSON 檔案 `metric.json` 中。  
以下是該檔案的內容：  

```
[
  {
    "MetricName": "New Posts",
    "Timestamp": "Wednesday, June 12, 2013 8:28:20 PM",
    "Value": 0.50,
    "Unit": "Count"
  }
]
```
如需詳細資訊，請參閱《Amazon CloudWatch 使用者指南》**中的「發布自訂指標」。  
**指定多個維度**  
下列範例說明如何指定多個維度。每個維度均指定為 Name=Value 對。使用逗號分隔多個維度：  

```
aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-data.html)。

### `put-metric-stream`
<a name="cloudwatch_PutMetricStream_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `put-metric-stream`。

**AWS CLI**  
**建立指標串流**  
下列 `put-metric-stream` 範例在指定帳戶中建立名為 `QuickFull-GuaFb` 的指標串流。  

```
aws cloudwatch put-metric-stream \
    --name QuickFull-GuaFbs \
    --firehose-arn arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG \
    --role-arn arn:aws:iam::123456789012:role/service-role/MetricStreams-FirehosePutRecords-JN10W9B3 \
    --output-format json \
    --no-include-linked-accounts-metrics
```
輸出：  

```
{
    "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs"
}
```
如需詳細資訊，請參閱《Amazon CloudWatch 使用者指南》**中的[設定指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-setup.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-stream.html)。

### `set-alarm-state`
<a name="cloudwatch_SetAlarmState_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `set-alarm-state`。

**AWS CLI**  
**暫時變更警示的狀態**  
以下範例使用 `set-alarm-state` 命令暫時變更名為 "myalarm" 的 Amazon CloudWatch 警示狀態，並將其設定為 ALARM 狀態以供測試之用：  

```
aws cloudwatch set-alarm-state --alarm-name "myalarm" --state-value ALARM --state-reason "testing purposes"
```
如果成功，此命令會回到提示字元。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [SetAlarmState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/set-alarm-state.html)。

### `start-metric-streams`
<a name="cloudwatch_StartMetricStreams_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `start-metric-streams`。

**AWS CLI**  
**啟動指定的指標串流**  
下列 `start-metric-streams` 範例啟動指定帳戶中名為 `QuickFull-GuaFbs` 的指標串流。  

```
aws cloudwatch start-metric-streams \
    --names QuickFull-GuaFbs
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [StartMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/start-metric-streams.html)。

### `stop-metric-streams`
<a name="cloudwatch_StopMetricStreams_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `stop-metric-streams`。

**AWS CLI**  
**停止指定的指標串流**  
下列 `stop-metric-streams` 範例停止指定帳戶中名為 `QuickFull-GuaFbs` 的指標串流。  

```
aws cloudwatch stop-metric-streams \
    --names QuickFull-GuaFbs
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用指標串流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [StopMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/stop-metric-streams.html)。

### `tag-resource`
<a name="cloudwatch_TagResource_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `tag-resource`。

**AWS CLI**  
**將一或多個標籤新增至指定的資源**  
下列 `tag-resource` 範例將 2 個標籤新增至指定帳戶中名為 `demo` 的 CloudWatch 警示。  

```
aws cloudwatch tag-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo \
    --tags Key=stack,Value=Production Key=team,Value=Devops
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[標記 Amazon CloudWatch 資源](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/tag-resource.html)。

### `untag-resource`
<a name="cloudwatch_UntagResource_cli_2_topic"></a>

以下程式碼範例顯示如何使用 `untag-resource`。

**AWS CLI**  
**從指定的資源移除一或多個標籤**  
下列 `untag-resource` 範例從指定帳戶中名為 `demo` 的 CloudWatch 警示中移除 2 個標籤。  

```
aws cloudwatch untag-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo \
    --tag-keys stack team
```
此命令不會產生輸出。  
如需詳細資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[標記 Amazon CloudWatch 資源](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/untag-resource.html)。