

# Amazon CloudWatch examples using the AWS SDK for C\$1\$1
<a name="examples-cloudwatch"></a>

Amazon CloudWatch (CloudWatch) is a monitoring service for AWS cloud resources and the applications you run on AWS. You can use the following examples to program [CloudWatch](https://aws.amazon.com/cloudwatch) using the AWS SDK for C\$1\$1.

Amazon CloudWatch monitors your AWS resources and the applications you run on AWS in real time. You can use CloudWatch to collect and track metrics, which are variables you can measure for your resources and applications. CloudWatch alarms send notifications or automatically make changes to the resources you are monitoring based on rules that you define.

For more information about CloudWatch, see the [Amazon CloudWatch User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/).

**Note**  
Only the code that is necessary to demonstrate certain techniques is supplied in this Guide, but the [complete example code is available on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp). On GitHub you can download a single source file or you can clone the repository locally to get, build, and run all examples.

**Topics**
+ [Getting Metrics from CloudWatch](examples-cloudwatch-get-metrics.md)
+ [Publishing Custom Metric Data](examples-cloudwatch-publish-custom-metrics.md)
+ [Working with CloudWatch Alarms](examples-cloudwatch-create-alarms.md)
+ [Using Alarm Actions in CloudWatch](examples-cloudwatch-use-alarm-actions.md)
+ [Sending Events to CloudWatch](examples-cloudwatch-send-events.md)

# Getting Metrics from CloudWatch
<a name="examples-cloudwatch-get-metrics"></a>

## Prerequisites
<a name="codeExamplePrereq"></a>

Before you begin, we recommend you read [Getting started using the AWS SDK for C\$1\$1](getting-started.md). 

Download the example code and build the solution as described in [Getting started on code examples](getting-started-code-examples.md). 

To run the examples, the user profile your code uses to make the requests must have proper permissions in AWS (for the service and the action). For more information, see [Providing AWS credentials](credentials.md).

## Listing Metrics
<a name="listing-metrics"></a>

To list CloudWatch metrics, create a [ListMetricsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_list_metrics_request.html) and call the CloudWatchClient’s `ListMetrics` function. You can use the `ListMetricsRequest` to filter the returned metrics by namespace, metric name, or dimensions.

**Note**  
A list of metrics and dimensions that are posted by AWS services can be found within the [Amazon CloudWatch Metrics and Dimensions Reference](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) in the Amazon CloudWatch User Guide.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/ListMetricsRequest.h>
#include <aws/monitoring/model/ListMetricsResult.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::ListMetricsRequest request;

        if (argc > 1)
        {
            request.SetMetricName(argv[1]);
        }

        if (argc > 2)
        {
            request.SetNamespace(argv[2]);
        }

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.ListMetrics(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to list CloudWatch metrics:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left << std::setw(48) << "MetricName" <<
                    std::setw(32) << "Namespace" << "DimensionNameValuePairs" <<
                    std::endl;
                header = true;
            }

            const auto &metrics = outcome.GetResult().GetMetrics();
            for (const auto &metric : metrics)
            {
                std::cout << std::left << std::setw(48) <<
                    metric.GetMetricName() << std::setw(32) <<
                    metric.GetNamespace();
                const auto &dimensions = metric.GetDimensions();
                for (auto iter = dimensions.cbegin();
                    iter != dimensions.cend(); ++iter)
                {
                    const auto &dimkv = *iter;
                    std::cout << dimkv.GetName() << " = " << dimkv.GetValue();
                    if (iter + 1 != dimensions.cend())
                    {
                        std::cout << ", ";
                    }
                }
                std::cout << std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```

The metrics are returned in a [ListMetricsResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_list_metrics_result.html) by calling its `GetMetrics` function. The results may be *paged*. To retrieve the next batch of results, call `SetNextToken` on the original request object with the return value of the `ListMetricsResult` object’s `GetNextToken` function, and pass the modified request object back to another call to `ListMetrics`.

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/list_metrics.cpp).

## More Information
<a name="more-information"></a>
+  [ListMetrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/ListMetrics.html) in the Amazon CloudWatch API Reference.

# Publishing Custom Metric Data
<a name="examples-cloudwatch-publish-custom-metrics"></a>

A number of AWS services publish [their own metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html) in namespaces beginning with `AWS/` You can also publish custom metric data using your own namespace (as long as it doesn’t begin with `AWS/`).

## Prerequisites
<a name="codeExamplePrereq"></a>

Before you begin, we recommend you read [Getting started using the AWS SDK for C\$1\$1](getting-started.md). 

Download the example code and build the solution as described in [Getting started on code examples](getting-started-code-examples.md). 

To run the examples, the user profile your code uses to make the requests must have proper permissions in AWS (for the service and the action). For more information, see [Providing AWS credentials](credentials.md).

## Publish Custom Metric Data
<a name="publish-custom-metric-data"></a>

To publish your own metric data, call the CloudWatchClient’s `PutMetricData` function with a [PutMetricDataRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_data_request.html). The `PutMetricDataRequest` must include the custom namespace to use for the data, and information about the data point itself in a [MetricDatum](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_metric_datum.html) object.

**Note**  
You cannot specify a namespace that begins with `AWS/`. Namespaces that begin with `AWS/` are reserved for use by Amazon Web Services products.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricDataRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("UNIQUE_PAGES");
        dimension.SetValue("URLS");

        Aws::CloudWatch::Model::MetricDatum datum;
        datum.SetMetricName("PAGES_VISITED");
        datum.SetUnit(Aws::CloudWatch::Model::StandardUnit::None);
        datum.SetValue(data_point);
        datum.AddDimensions(dimension);

        Aws::CloudWatch::Model::PutMetricDataRequest request;
        request.SetNamespace("SITE/TRAFFIC");
        request.AddMetricData(datum);

        auto outcome = cw.PutMetricData(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to put sample metric data:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully put sample metric data" << std::endl;
        }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/put_metric_data.cpp).

## More Information
<a name="more-information"></a>
+  [Using Amazon CloudWatch Metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) in the Amazon CloudWatch User Guide.
+  [AWS Namespaces](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html) in the Amazon CloudWatch User Guide.
+  [PutMetricData](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricData.html) in the Amazon CloudWatch API Reference.

# Working with CloudWatch Alarms
<a name="examples-cloudwatch-create-alarms"></a>

## Prerequisites
<a name="codeExamplePrereq"></a>

Before you begin, we recommend you read [Getting started using the AWS SDK for C\$1\$1](getting-started.md). 

Download the example code and build the solution as described in [Getting started on code examples](getting-started-code-examples.md). 

To run the examples, the user profile your code uses to make the requests must have proper permissions in AWS (for the service and the action). For more information, see [Providing AWS credentials](credentials.md).

## Create an Alarm
<a name="create-an-alarm"></a>

To create an alarm based on a CloudWatch metric, call the CloudWatchClient’s `PutMetricAlarm` function with a [PutMetricAlarmRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_alarm_request.html) filled with the alarm conditions.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::PutMetricAlarmRequest request;
        request.SetAlarmName(alarm_name);
        request.SetComparisonOperator(
            Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
        request.SetEvaluationPeriods(1);
        request.SetMetricName("CPUUtilization");
        request.SetNamespace("AWS/EC2");
        request.SetPeriod(60);
        request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
        request.SetThreshold(70.0);
        request.SetActionsEnabled(false);
        request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
        request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("InstanceId");
        dimension.SetValue(instanceId);

        request.AddDimensions(dimension);

        auto outcome = cw.PutMetricAlarm(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch alarm " << alarm_name
                << std::endl;
        }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/put_metric_alarm.cpp).

## List Alarms
<a name="list-alarms"></a>

To list the CloudWatch alarms that you have created, call the CloudWatchClient’s `DescribeAlarms` function with a [DescribeAlarmsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_describe_alarms_request.html) that you can use to set options for the result.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DescribeAlarmsRequest.h>
#include <aws/monitoring/model/DescribeAlarmsResult.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DescribeAlarmsRequest request;
        request.SetMaxRecords(1);

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.DescribeAlarms(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to describe CloudWatch alarms:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left <<
                    std::setw(32) << "Name" <<
                    std::setw(64) << "Arn" <<
                    std::setw(64) << "Description" <<
                    std::setw(20) << "LastUpdated" <<
                    std::endl;
                header = true;
            }

            const auto &alarms = outcome.GetResult().GetMetricAlarms();
            for (const auto &alarm : alarms)
            {
                std::cout << std::left <<
                    std::setw(32) << alarm.GetAlarmName() <<
                    std::setw(64) << alarm.GetAlarmArn() <<
                    std::setw(64) << alarm.GetAlarmDescription() <<
                    std::setw(20) <<
                    alarm.GetAlarmConfigurationUpdatedTimestamp().ToGmtString(
                        SIMPLE_DATE_FORMAT_STR) <<
                    std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```

The list of alarms can be obtained by calling `getMetricAlarms` on the [DescribeAlarmsResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_describe_alarms_result.html) that is returned by `DescribeAlarms`.

The results may be *paged*. To retrieve the next batch of results, call `SetNextToken` on the original request object with the return value of the `DescribeAlarmsResult` object’s `GetNextToken` function, and pass the modified request object back to another call to `DescribeAlarms`.

**Note**  
You can also retrieve alarms for a specific metric by using the CloudWatchClient’s `DescribeAlarmsForMetric` function. Its use is similar to `DescribeAlarms`.

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/describe_alarms.cpp).

## Delete Alarms
<a name="delete-alarms"></a>

To delete CloudWatch alarms, call the CloudWatchClient’s `DeleteAlarms` function with a [DeleteAlarmsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_delete_alarms_request.html) containing one or more names of alarms that you want to delete.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DeleteAlarmsRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DeleteAlarmsRequest request;
        request.AddAlarmNames(alarm_name);

        auto outcome = cw.DeleteAlarms(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to delete CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully deleted CloudWatch alarm " << alarm_name
                << std::endl;
        }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/delete_alarm.cpp).

## More Information
<a name="more-information"></a>
+  [Creating Amazon CloudWatch Alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html) in the Amazon CloudWatch User Guide
+  [PutMetricAlarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricAlarm.html) in the Amazon CloudWatch API Reference
+  [DescribeAlarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DescribeAlarms.html) in the Amazon CloudWatch API Reference
+  [DeleteAlarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DeleteAlarms.html) in the Amazon CloudWatch API Reference

# Using Alarm Actions in CloudWatch
<a name="examples-cloudwatch-use-alarm-actions"></a>

Using CloudWatch alarm actions, you can create alarms that perform actions such as automatically stopping, terminating, rebooting, or recovering Amazon EC2 instances.

Alarm actions can be added to an alarm by using the [PutMetricAlarmRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_alarm_request.html)’s `SetAlarmActions` function when [creating an alarm](examples-cloudwatch-create-alarms.md).

## Prerequisites
<a name="codeExamplePrereq"></a>

Before you begin, we recommend you read [Getting started using the AWS SDK for C\$1\$1](getting-started.md). 

Download the example code and build the solution as described in [Getting started on code examples](getting-started-code-examples.md). 

To run the examples, the user profile your code uses to make the requests must have proper permissions in AWS (for the service and the action). For more information, see [Providing AWS credentials](credentials.md).

## Enable Alarm Actions
<a name="enable-alarm-actions"></a>

To enable alarm actions for a CloudWatch alarm, call the CloudWatchClient’s `EnableAlarmActions` with a [EnableAlarmActionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_enable_alarm_actions_request.html) containing one or more names of alarms whose actions you want to enable.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/EnableAlarmActionsRequest.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::CloudWatch::CloudWatchClient cw;
    Aws::CloudWatch::Model::PutMetricAlarmRequest request;
    request.SetAlarmName(alarm_name);
    request.SetComparisonOperator(
        Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
    request.SetEvaluationPeriods(1);
    request.SetMetricName("CPUUtilization");
    request.SetNamespace("AWS/EC2");
    request.SetPeriod(60);
    request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
    request.SetThreshold(70.0);
    request.SetActionsEnabled(false);
    request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
    request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);
    request.AddAlarmActions(actionArn);

    Aws::CloudWatch::Model::Dimension dimension;
    dimension.SetName("InstanceId");
    dimension.SetValue(instanceId);
    request.AddDimensions(dimension);

    auto outcome = cw.PutMetricAlarm(request);
    if (!outcome.IsSuccess())
    {
        std::cout << "Failed to create CloudWatch alarm:" <<
            outcome.GetError().GetMessage() << std::endl;
        return;
    }

    Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request;
    enable_request.AddAlarmNames(alarm_name);

    auto enable_outcome = cw.EnableAlarmActions(enable_request);
    if (!enable_outcome.IsSuccess())
    {
        std::cout << "Failed to enable alarm actions:" <<
            enable_outcome.GetError().GetMessage() << std::endl;
        return;
    }

    std::cout << "Successfully created alarm " << alarm_name <<
        " and enabled actions on it." << std::endl;
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/enable_alarm_actions.cpp).

## Disable Alarm Actions
<a name="disable-alarm-actions"></a>

To disable alarm actions for a CloudWatch alarm, call the CloudWatchClient’s `DisableAlarmActions` with a [DisableAlarmActionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_disable_alarm_actions_request.html) containing one or more names of alarms whose actions you want to disable.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DisableAlarmActionsRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::DisableAlarmActionsRequest disableAlarmActionsRequest;
        disableAlarmActionsRequest.AddAlarmNames(alarm_name);

        auto disableAlarmActionsOutcome = cw.DisableAlarmActions(disableAlarmActionsRequest);
        if (!disableAlarmActionsOutcome.IsSuccess())
        {
            std::cout << "Failed to disable actions for alarm " << alarm_name <<
                ": " << disableAlarmActionsOutcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully disabled actions for alarm " <<
                alarm_name << std::endl;
        }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/disable_alarm_actions.cpp).

## More Information
<a name="more-information"></a>
+  [Create Alarms to Stop, Terminate, Reboot, or Recover an Instance](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html) in the Amazon CloudWatch User Guide
+  [PutMetricAlarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricAlarm.html) in the Amazon CloudWatch API Reference
+  [EnableAlarmActions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/EnableAlarmActions.html) in the Amazon CloudWatch API Reference
+  [DisableAlarmActions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DisableAlarmActions.html) in the Amazon CloudWatch API Reference

# Sending Events to CloudWatch
<a name="examples-cloudwatch-send-events"></a>

CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS resources to Amazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, Amazon SNS topics, Amazon SQS queues, or built-in targets. You can match events and route them to one or more target functions or streams by using simple rules.

**Note**  
These code snippets assume that you understand the material in [Getting Started Using the AWS SDK for C\$1\$1](getting-started.md) and have configured default AWS credentials using the information in [Providing AWS Credentials](credentials.md).

## Add Events
<a name="add-events"></a>

To add custom CloudWatch events, call the CloudWatchEventsClient’s `PutEvents` function with a [PutEventsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_events_request.html) object that contains one or more [PutEventsRequestEntry](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_events_request_entry.html) objects that provide details about each event. You can specify several parameters for the entry such as the source and type of the event, resources associated with the event, and so on.

**Note**  
You can specify a maximum of 10 events per call to `putEvents`.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutEventsRequest.h>
#include <aws/events/model/PutEventsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry;
        event_entry.SetDetail(MakeDetails(event_key, event_value));
        event_entry.SetDetailType("sampleSubmitted");
        event_entry.AddResources(resource_arn);
        event_entry.SetSource("aws-sdk-cpp-cloudwatch-example");

        Aws::CloudWatchEvents::Model::PutEventsRequest request;
        request.AddEntries(event_entry);

        auto outcome = cwe.PutEvents(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to post CloudWatch event: " <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully posted CloudWatch event" << std::endl;
        }
```

## Add Rules
<a name="add-rules"></a>

To create or update a rule, call the CloudWatchEventsClient’s `PutRule` function with a [PutRuleRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_rule_request.html) with the name of the rule and optional parameters such as the [event pattern](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html), IAM role to associate with the rule, and a [scheduling expression](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) that describes how often the rule is run.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutRuleRequest.h>
#include <aws/events/model/PutRuleResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;
        Aws::CloudWatchEvents::Model::PutRuleRequest request;
        request.SetName(rule_name);
        request.SetRoleArn(role_arn);
        request.SetScheduleExpression("rate(5 minutes)");
        request.SetState(Aws::CloudWatchEvents::Model::RuleState::ENABLED);

        auto outcome = cwe.PutRule(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events rule " <<
                rule_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch events rule " <<
                rule_name << " with resulting Arn " <<
                outcome.GetResult().GetRuleArn() << std::endl;
        }
```

## Add Targets
<a name="add-targets"></a>

Targets are the resources that are invoked when a rule is triggered. Example targets include Amazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, and built-in targets.

To add a target to a rule, call the CloudWatchEventsClient’s `PutTargets` function with a [PutTargetsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_targets_request.html) containing the rule to update and a list of targets to add to the rule.

 **Includes** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutTargetsRequest.h>
#include <aws/events/model/PutTargetsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::Target target;
        target.SetArn(lambda_arn);
        target.SetId(target_id);

        Aws::CloudWatchEvents::Model::PutTargetsRequest request;
        request.SetRule(rule_name);
        request.AddTargets(target);

        auto putTargetsOutcome = cwe.PutTargets(request);
        if (!putTargetsOutcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events target for rule "
                << rule_name << ": " <<
                putTargetsOutcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout <<
                "Successfully created CloudWatch events target for rule "
                << rule_name << std::endl;
        }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/eventbridge/put_targets.cpp).

## More Information
<a name="more-information"></a>
+  [Adding Events with PutEvents](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html) in the Amazon CloudWatch Events User Guide
+  [Schedule Expressions for Rules](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) in the Amazon CloudWatch Events User Guide
+  [Event Types for CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html) in the Amazon CloudWatch Events User Guide
+  [Events and Event Patterns](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html) in the Amazon CloudWatch Events User Guide
+  [PutEvents](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutEvents.html) in the Amazon CloudWatch Events API Reference
+  [PutTargets](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutTargets.html) in the Amazon CloudWatch Events API Reference
+  [PutRule](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutRule.html) in the Amazon CloudWatch Events API Reference