1// Code generated by smithy-go-codegen DO NOT EDIT.
2
3package cloudwatch
4
5import (
6	"context"
7	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
8	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
9	"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
10	"github.com/aws/smithy-go/middleware"
11	smithyhttp "github.com/aws/smithy-go/transport/http"
12)
13
14// Creates or updates an alarm and associates it with the specified metric, metric
15// math expression, or anomaly detection model. Alarms based on anomaly detection
16// models cannot have Auto Scaling actions. When this operation creates an alarm,
17// the alarm state is immediately set to INSUFFICIENT_DATA. The alarm is then
18// evaluated and its state is set appropriately. Any actions associated with the
19// new state are then executed. When you update an existing alarm, its state is
20// left unchanged, but the update completely overwrites the previous configuration
21// of the alarm. If you are an IAM user, you must have Amazon EC2 permissions for
22// some alarm operations:
23//
24// * The iam:CreateServiceLinkedRole for all alarms with
25// EC2 actions
26//
27// * The iam:CreateServiceLinkedRole to create an alarm with Systems
28// Manager OpsItem actions.
29//
30// The first time you create an alarm in the AWS
31// Management Console, the CLI, or by using the PutMetricAlarm API, CloudWatch
32// creates the necessary service-linked role for you. The service-linked roles are
33// called AWSServiceRoleForCloudWatchEvents and
34// AWSServiceRoleForCloudWatchAlarms_ActionSSM. For more information, see AWS
35// service-linked role
36// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role).
37func (c *Client) PutMetricAlarm(ctx context.Context, params *PutMetricAlarmInput, optFns ...func(*Options)) (*PutMetricAlarmOutput, error) {
38	if params == nil {
39		params = &PutMetricAlarmInput{}
40	}
41
42	result, metadata, err := c.invokeOperation(ctx, "PutMetricAlarm", params, optFns, addOperationPutMetricAlarmMiddlewares)
43	if err != nil {
44		return nil, err
45	}
46
47	out := result.(*PutMetricAlarmOutput)
48	out.ResultMetadata = metadata
49	return out, nil
50}
51
52type PutMetricAlarmInput struct {
53
54	// The name for the alarm. This name must be unique within the Region.
55	//
56	// This member is required.
57	AlarmName *string
58
59	// The arithmetic operation to use when comparing the specified statistic and
60	// threshold. The specified statistic value is used as the first operand. The
61	// values LessThanLowerOrGreaterThanUpperThreshold, LessThanLowerThreshold, and
62	// GreaterThanUpperThreshold are used only for alarms based on anomaly detection
63	// models.
64	//
65	// This member is required.
66	ComparisonOperator types.ComparisonOperator
67
68	// The number of periods over which data is compared to the specified threshold. If
69	// you are setting an alarm that requires that a number of consecutive data points
70	// be breaching to trigger the alarm, this value specifies that number. If you are
71	// setting an "M out of N" alarm, this value is the N. An alarm's total current
72	// evaluation period can be no longer than one day, so this number multiplied by
73	// Period cannot be more than 86,400 seconds.
74	//
75	// This member is required.
76	EvaluationPeriods *int32
77
78	// Indicates whether actions should be executed during any changes to the alarm
79	// state. The default is TRUE.
80	ActionsEnabled *bool
81
82	// The actions to execute when this alarm transitions to the ALARM state from any
83	// other state. Each action is specified as an Amazon Resource Name (ARN). Valid
84	// Values: arn:aws:automate:region:ec2:stop | arn:aws:automate:region:ec2:terminate
85	// | arn:aws:automate:region:ec2:recover | arn:aws:automate:region:ec2:reboot |
86	// arn:aws:sns:region:account-id:sns-topic-name  |
87	// arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name
88	// | arn:aws:ssm:region:account-id:opsitem:severity  Valid Values (for use with IAM
89	// roles): arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0
90	// | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0
91	// | arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0
92	AlarmActions []string
93
94	// The description for the alarm.
95	AlarmDescription *string
96
97	// The number of data points that must be breaching to trigger the alarm. This is
98	// used only if you are setting an "M out of N" alarm. In that case, this value is
99	// the M. For more information, see Evaluating an Alarm
100	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarm-evaluation)
101	// in the Amazon CloudWatch User Guide.
102	DatapointsToAlarm *int32
103
104	// The dimensions for the metric specified in MetricName.
105	Dimensions []types.Dimension
106
107	// Used only for alarms based on percentiles. If you specify ignore, the alarm
108	// state does not change during periods with too few data points to be
109	// statistically significant. If you specify evaluate or omit this parameter, the
110	// alarm is always evaluated and possibly changes state no matter how many data
111	// points are available. For more information, see Percentile-Based CloudWatch
112	// Alarms and Low Data Samples
113	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#percentiles-with-low-samples).
114	// Valid Values: evaluate | ignore
115	EvaluateLowSampleCountPercentile *string
116
117	// The percentile statistic for the metric specified in MetricName. Specify a value
118	// between p0.0 and p100. When you call PutMetricAlarm and specify a MetricName,
119	// you must specify either Statistic or ExtendedStatistic, but not both.
120	ExtendedStatistic *string
121
122	// The actions to execute when this alarm transitions to the INSUFFICIENT_DATA
123	// state from any other state. Each action is specified as an Amazon Resource Name
124	// (ARN). Valid Values: arn:aws:automate:region:ec2:stop |
125	// arn:aws:automate:region:ec2:terminate | arn:aws:automate:region:ec2:recover |
126	// arn:aws:automate:region:ec2:reboot |
127	// arn:aws:sns:region:account-id:sns-topic-name  |
128	// arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name
129	// Valid Values (for use with IAM roles):
130	// >arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0 |
131	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0 |
132	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0
133	InsufficientDataActions []string
134
135	// The name for the metric associated with the alarm. For each PutMetricAlarm
136	// operation, you must specify either MetricName or a Metrics array. If you are
137	// creating an alarm based on a math expression, you cannot specify this parameter,
138	// or any of the Dimensions, Period, Namespace, Statistic, or ExtendedStatistic
139	// parameters. Instead, you specify all this information in the Metrics array.
140	MetricName *string
141
142	// An array of MetricDataQuery structures that enable you to create an alarm based
143	// on the result of a metric math expression. For each PutMetricAlarm operation,
144	// you must specify either MetricName or a Metrics array. Each item in the Metrics
145	// array either retrieves a metric or performs a math expression. One item in the
146	// Metrics array is the expression that the alarm watches. You designate this
147	// expression by setting ReturnData to true for this object in the array. For more
148	// information, see MetricDataQuery
149	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDataQuery.html).
150	// If you use the Metrics parameter, you cannot include the MetricName, Dimensions,
151	// Period, Namespace, Statistic, or ExtendedStatistic parameters of PutMetricAlarm
152	// in the same operation. Instead, you retrieve the metrics you are using in your
153	// math expression as part of the Metrics array.
154	Metrics []types.MetricDataQuery
155
156	// The namespace for the metric associated specified in MetricName.
157	Namespace *string
158
159	// The actions to execute when this alarm transitions to an OK state from any other
160	// state. Each action is specified as an Amazon Resource Name (ARN). Valid Values:
161	// arn:aws:automate:region:ec2:stop | arn:aws:automate:region:ec2:terminate |
162	// arn:aws:automate:region:ec2:recover | arn:aws:automate:region:ec2:reboot |
163	// arn:aws:sns:region:account-id:sns-topic-name  |
164	// arn:aws:autoscaling:region:account-id:scalingPolicy:policy-id:autoScalingGroupName/group-friendly-name:policyName/policy-friendly-name
165	// Valid Values (for use with IAM roles):
166	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Stop/1.0 |
167	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Terminate/1.0 |
168	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Reboot/1.0 |
169	// arn:aws:swf:region:account-id:action/actions/AWS_EC2.InstanceId.Recover/1.0
170	OKActions []string
171
172	// The length, in seconds, used each time the metric specified in MetricName is
173	// evaluated. Valid values are 10, 30, and any multiple of 60. Period is required
174	// for alarms based on static thresholds. If you are creating an alarm based on a
175	// metric math expression, you specify the period for each metric within the
176	// objects in the Metrics array. Be sure to specify 10 or 30 only for metrics that
177	// are stored by a PutMetricData call with a StorageResolution of 1. If you specify
178	// a period of 10 or 30 for a metric that does not have sub-minute resolution, the
179	// alarm still attempts to gather data at the period rate that you specify. In this
180	// case, it does not receive data for the attempts that do not correspond to a
181	// one-minute data resolution, and the alarm might often lapse into
182	// INSUFFICENT_DATA status. Specifying 10 or 30 also sets this alarm as a
183	// high-resolution alarm, which has a higher charge than other alarms. For more
184	// information about pricing, see Amazon CloudWatch Pricing
185	// (https://aws.amazon.com/cloudwatch/pricing/). An alarm's total current
186	// evaluation period can be no longer than one day, so Period multiplied by
187	// EvaluationPeriods cannot be more than 86,400 seconds.
188	Period *int32
189
190	// The statistic for the metric specified in MetricName, other than percentile. For
191	// percentile statistics, use ExtendedStatistic. When you call PutMetricAlarm and
192	// specify a MetricName, you must specify either Statistic or ExtendedStatistic,
193	// but not both.
194	Statistic types.Statistic
195
196	// A list of key-value pairs to associate with the alarm. You can associate as many
197	// as 50 tags with an alarm. Tags can help you organize and categorize your
198	// resources. You can also use them to scope user permissions by granting a user
199	// permission to access or change only resources with certain tag values. If you
200	// are using this operation to update an existing alarm, any tags you specify in
201	// this parameter are ignored. To change the tags of an existing alarm, use
202	// TagResource
203	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_TagResource.html)
204	// or UntagResource
205	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_UntagResource.html).
206	Tags []types.Tag
207
208	// The value against which the specified statistic is compared. This parameter is
209	// required for alarms based on static thresholds, but should not be used for
210	// alarms based on anomaly detection models.
211	Threshold *float64
212
213	// If this is an alarm based on an anomaly detection model, make this value match
214	// the ID of the ANOMALY_DETECTION_BAND function. For an example of how to use this
215	// parameter, see the Anomaly Detection Model Alarm example on this page. If your
216	// alarm uses this parameter, it cannot have Auto Scaling actions.
217	ThresholdMetricId *string
218
219	// Sets how this alarm is to handle missing data points. If TreatMissingData is
220	// omitted, the default behavior of missing is used. For more information, see
221	// Configuring How CloudWatch Alarms Treats Missing Data
222	// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarms-and-missing-data).
223	// Valid Values: breaching | notBreaching | ignore | missing
224	TreatMissingData *string
225
226	// The unit of measure for the statistic. For example, the units for the Amazon EC2
227	// NetworkIn metric are Bytes because NetworkIn tracks the number of bytes that an
228	// instance receives on all network interfaces. You can also specify a unit when
229	// you create a custom metric. Units help provide conceptual meaning to your data.
230	// Metric data points that specify a unit of measure, such as Percent, are
231	// aggregated separately. If you don't specify Unit, CloudWatch retrieves all unit
232	// types that have been published for the metric and attempts to evaluate the
233	// alarm. Usually, metrics are published with only one unit, so the alarm works as
234	// intended. However, if the metric is published with multiple types of units and
235	// you don't specify a unit, the alarm's behavior is not defined and it behaves
236	// predictably. We recommend omitting Unit so that you don't inadvertently specify
237	// an incorrect unit that is not published for this metric. Doing so causes the
238	// alarm to be stuck in the INSUFFICIENT DATA state.
239	Unit types.StandardUnit
240}
241
242type PutMetricAlarmOutput struct {
243	// Metadata pertaining to the operation's result.
244	ResultMetadata middleware.Metadata
245}
246
247func addOperationPutMetricAlarmMiddlewares(stack *middleware.Stack, options Options) (err error) {
248	err = stack.Serialize.Add(&awsAwsquery_serializeOpPutMetricAlarm{}, middleware.After)
249	if err != nil {
250		return err
251	}
252	err = stack.Deserialize.Add(&awsAwsquery_deserializeOpPutMetricAlarm{}, middleware.After)
253	if err != nil {
254		return err
255	}
256	if err = addSetLoggerMiddleware(stack, options); err != nil {
257		return err
258	}
259	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
260		return err
261	}
262	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
263		return err
264	}
265	if err = addResolveEndpointMiddleware(stack, options); err != nil {
266		return err
267	}
268	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
269		return err
270	}
271	if err = addRetryMiddlewares(stack, options); err != nil {
272		return err
273	}
274	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
275		return err
276	}
277	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
278		return err
279	}
280	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
281		return err
282	}
283	if err = addClientUserAgent(stack); err != nil {
284		return err
285	}
286	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
287		return err
288	}
289	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
290		return err
291	}
292	if err = addOpPutMetricAlarmValidationMiddleware(stack); err != nil {
293		return err
294	}
295	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutMetricAlarm(options.Region), middleware.Before); err != nil {
296		return err
297	}
298	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
299		return err
300	}
301	if err = addResponseErrorMiddleware(stack); err != nil {
302		return err
303	}
304	if err = addRequestResponseLogging(stack, options); err != nil {
305		return err
306	}
307	return nil
308}
309
310func newServiceMetadataMiddleware_opPutMetricAlarm(region string) *awsmiddleware.RegisterServiceMetadata {
311	return &awsmiddleware.RegisterServiceMetadata{
312		Region:        region,
313		ServiceID:     ServiceID,
314		SigningName:   "monitoring",
315		OperationName: "PutMetricAlarm",
316	}
317}
318