zabbix_export:
  version: '7.0'
  template_groups:
    - uuid: c2c162144c2d4c5491c8801193af4945
      name: Templates/Cloud
  templates:
    - uuid: fd36e0a231d343d38a95d1ed789584ca
      template: 'AWS Lambda by HTTP'
      name: 'AWS Lambda by HTTP'
      description: |
        The template is designed to monitor AWS Lambda by HTTP via Zabbix, and it works without any external scripts.
        Don't forget to read the README.md for the correct setup of the template.
        
        You can discuss this template or leave feedback on our forum https://www.zabbix.com/forum/zabbix-suggestions-and-feedback
        
        Generated by official Zabbix template tool "Templator"
      vendor:
        name: Zabbix
        version: 7.0-0
      groups:
        - name: Templates/Cloud
      items:
        - uuid: 397bcf955a7449b79dab4770fe17922f
          name: 'AWS Lambda: Get alarms check'
          type: DEPENDENT
          key: aws.lambda.alarms.check
          value_type: CHAR
          description: 'Check that the alarm data has been received correctly.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - $.error
              error_handler: CUSTOM_VALUE
            - type: DISCARD_UNCHANGED_HEARTBEAT
              parameters:
                - 3h
          master_item:
            key: aws.lambda.get_alarms
          tags:
            - tag: component
              value: status
          triggers:
            - uuid: 77f2bf7f1086488289b1cf1931e8fd90
              expression: 'length(last(/AWS Lambda by HTTP/aws.lambda.alarms.check))>0'
              name: 'AWS Lambda: Failed to get alarms data'
              event_name: 'AWS Lambda: Failed to get CloudWatch alarms for the Lambda function'
              opdata: 'Current value: {ITEM.LASTVALUE1}'
              priority: WARNING
              description: 'Failed to get CloudWatch alarms for the Lambda function.'
              tags:
                - tag: scope
                  value: availability
        - uuid: 57c7e41184d74cc98c2eea33bfe28028
          name: 'AWS Lambda: Async events dropped sum'
          type: DEPENDENT
          key: aws.lambda.async_events_dropped.sum
          description: 'The number of events that are dropped without successfully executing the function. If you configure a dead-letter queue (DLQ) or an `OnFailure` destination, events are sent there before they''re dropped.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "AsyncEventsDropped")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: asynchronous
        - uuid: d8000a6335b14e0dae702787e4bf9db2
          name: 'AWS Lambda: Async events received sum'
          type: DEPENDENT
          key: aws.lambda.async_events_received.sum
          description: 'The number of events that Lambda successfully queues for processing. This metric provides insight into the number of events that a Lambda function receives.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "AsyncEventsReceived")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: asynchronous
        - uuid: 48b180f52bbf4c93b64433a97e00a029
          name: 'AWS Lambda: Async event age average'
          type: DEPENDENT
          key: aws.lambda.async_event_age.avg
          value_type: FLOAT
          units: s
          description: 'The time between when Lambda successfully queues the event and when the function is invoked. The value of this metric increases when events are being retried due to invocation failures or throttling.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "AsyncEventAge")].Values.first().first()'
              error_handler: DISCARD_VALUE
            - type: MULTIPLIER
              parameters:
                - '0.001'
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: asynchronous
        - uuid: 7eaf67dc1859405aa55f22ea8d85e7c5
          name: 'AWS Lambda: Total concurrent executions'
          type: DEPENDENT
          key: aws.lambda.concurrent_executions.max
          description: 'The number of function instances that are processing events. If this number reaches your concurrent executions quota for the Region or the reserved concurrency limit on the function, then Lambda will throttle additional invocation requests.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "ConcurrentExecutions")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: concurrency
        - uuid: 82536a92c0f84d67aabbe69e38e7f3a2
          name: 'AWS Lambda: Dead letter errors sum'
          type: DEPENDENT
          key: aws.lambda.dead_letter_errors.sum
          description: 'For asynchronous invocation, the number of times that Lambda attempts to send an event to a dead-letter queue (DLQ) but fails. Dead-letter errors can occur due to misconfigured resources or size limits.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "DeadLetterErrors")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: invocation
        - uuid: 370d8ac63e024a94a493c95e528f4604
          name: 'AWS Lambda: Duration average'
          type: DEPENDENT
          key: aws.lambda.duration.avg
          value_type: FLOAT
          units: s
          description: 'The amount of time that your function code spends processing an event. The billed duration for an invocation is the value of `Duration` rounded up to the nearest millisecond. Duration does not include cold start time.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "Duration")].Values.first().first()'
              error_handler: DISCARD_VALUE
            - type: MULTIPLIER
              parameters:
                - '0.001'
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: performance
        - uuid: 1b16f879dc5648d0b50e060d1f056fab
          name: 'AWS Lambda: Errors sum'
          type: DEPENDENT
          key: aws.lambda.errors.sum
          description: 'The number of invocations that result in a function error. Function errors include exceptions that your code throws and exceptions that the Lambda runtime throws. The runtime returns errors for issues such as timeouts and configuration errors.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "Errors")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: invocation
        - uuid: c80b25e889004287b6131c00000a3ad7
          name: 'AWS CloudWatch: Get Lambda alarms data'
          type: SCRIPT
          key: aws.lambda.get_alarms
          delay: 0s;m/1
          history: '0'
          value_type: TEXT
          params: |
            var AWS = {
            	params: {},
            	metadata: 'http://169.254.169.254/latest/meta-data/iam/security-credentials',
            
            	getField: function (data, path) {
            		var steps = path.split('.');
            		for (var i = 0; i < steps.length; i++) {
            			var step = steps[i];
            			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
            				throw 'Required field was not found: ' + path;
            			}
            
            			data = data[step];
            		}
            
            		return data;
            	},
            
            	setParams: function (params) {
            		AWS.params['proxy'] = params.proxy;
            		switch (AWS.getField(params, 'auth_type')) {
            			case 'role_base':
            				AWS.params['auth_type'] = 'role_base';
            				var request = new HttpRequest();
            				if (typeof AWS.params.proxy !== 'undefined' && AWS.params.proxy !== '') {
            					request.setProxy(AWS.params.proxy);
            				}
            				var IamRoleName = request.get(AWS.metadata);
            
            				if (request.getStatus() !== 200 || IamRoleName === null || IamRoleName === '') {
            					throw 'Error getting security credentials from instance metadata. Role not found.';
            				}
            
            				credentials = request.get(AWS.metadata + '/' + encodeURI(IamRoleName));
            
            				if (request.getStatus() !== 200 || credentials === null || credentials === '') {
            					throw 'Error getting security credentials from instance metadata.';
            				}
            
            				try {
            					credentials = JSON.parse(credentials);
            				}
            				catch (error) {
            					throw 'Failed to parse response received from instance metadata. Check debug log for more information.';
            				}
            
            				['AccessKeyId', 'SecretAccessKey', 'Token'].forEach(function (field) {
            					if (typeof credentials !== 'object' || typeof credentials[field] === 'undefined' || credentials[field] === '') {
            						throw 'Required credentials are not set: "' + field + '".';
            					};
            					AWS.params[field] = credentials[field];
            				});
            				break;
            			default:
            				AWS.params['auth_type'] = 'access_key';
            				['AccessKeyId', 'SecretAccessKey'].forEach(function (field) {
            					if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
            						throw 'Required param is not set: "' + field + '".';
            					}
            					AWS.params[field] = params[field];
            				});
            		}
            		['region', 'name'].forEach(function (field) {
            			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
            				throw 'Required param is not set: "' + field + '".';
            			}
            			AWS.params[field] = params[field];
            		});
            	},
            
            	sign: function (key, message) {
            		var hex = hmac('sha256', key, message);
            
            		if ((hex.length % 2) === 1) {
            			throw 'Invalid length of a hex string!';
            		}
            
            		var result = new Int8Array(hex.length / 2);
            		for (var i = 0, b = 0; i < hex.length; i += 2, b++) {
            			result[b] = parseInt(hex.substring(i, i + 2), 16);
            		}
            
            		return result;
            	},
            
            	prepareParams: function (params) {
            		var result = [];
            
            		Object.keys(params).sort().forEach(function (key) {
            			if (typeof params[key] !== 'object') {
            				result.push(key + '=' + encodeURIComponent(params[key]));
            			}
            			else {
            				result.push(prepareObject(key, params[key]));
            			}
            		});
            
            		return result.join('&');
            	},
            
            	request: function (method, region, service, params, data) {
            		if (typeof data === 'undefined' || data === null) {
            			data = '';
            		}
            
            		var amzdate = (new Date()).toISOString().replace(/\.\d+Z/, 'Z').replace(/[-:]/g, ''),
            			date = amzdate.replace(/T\d+Z/, ''),
            			host = service + '.' + region + '.amazonaws.com',
            			canonical_uri = '/',
            			canonical_headers = 'content-encoding:amz-1.0\n' + 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n',
            			signed_headers = 'content-encoding;host;x-amz-date',
            			canonical_request = method + '\n' + canonical_uri + '\n' + params + '\n' + canonical_headers + '\n' + signed_headers + '\n' + sha256(data),
            			credential_scope = date + '/' + region + '/' + service + '/' + 'aws4_request',
            			request_string = 'AWS4-HMAC-SHA256' + '\n' + amzdate + '\n' + credential_scope + '\n' + sha256(canonical_request),
            			key = AWS.sign('AWS4' + AWS.params.SecretAccessKey, date);
            
            		key = AWS.sign(key, region);
            		key = AWS.sign(key, service);
            		key = AWS.sign(key, 'aws4_request');
            
            		var request = new HttpRequest(),
            			url = 'https://' + host + canonical_uri + '?' + params;
            
            		if (typeof AWS.params.proxy !== 'undefined' && AWS.params.proxy !== '') {
            			request.setProxy(AWS.params.proxy);
            		}
            		request.addHeader('x-amz-date: ' + amzdate);
            		request.addHeader('Accept: application/json');
            		request.addHeader('Content-Type: application/json');
            		request.addHeader('Content-Encoding: amz-1.0');
            		request.addHeader('Authorization: ' + 'AWS4-HMAC-SHA256 Credential=' + AWS.params.AccessKeyId + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + hmac('sha256', key, request_string));
            		if (AWS.params.auth_type === 'role_base')
            			request.addHeader('X-Amz-Security-Token: ' + AWS.params.Token);
            
            		Zabbix.log(4, '[ AWS Lambda Alarms ] Sending request: ' + url);
            
            		response = request.get(url);
            
            		Zabbix.log(4, '[ AWS Lambda Alarms ] Received response with status code ' + request.getStatus() + ': ' + response);
            
            		if (request.getStatus() !== 200) {
            			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
            		}
            
            		if (response[0] === '<') {
            			try {
            				response = XML.toJson(response);
            			}
            			catch (error) {
            				throw 'Failed to parse response received from AWS CloudWatch API. Check debug log for more information.';
            			}
            		}
            
            		if (response !== null) {
            			try {
            				response = JSON.parse(response);
            			}
            			catch (error) {
            				throw 'Failed to parse response received from AWS CloudWatch API. Check debug log for more information.';
            			}
            		}
            
            		return response;
            	},
            
            	getAlarms: function () {
            		var payload = {
            			'Action': 'DescribeAlarms',
            			'Version': '2010-08-01',
            			'MaxRecords': 100
            		},
            			result = [];
            
            		while (payload.NextToken !== '') {
            			var alarms = AWS.getField(AWS.request('GET', AWS.params.region, 'monitoring', AWS.prepareParams(payload)), 'DescribeAlarmsResponse.DescribeAlarmsResult');
            			payload.NextToken = alarms.NextToken || '';
            			alarms_list = AWS.getField(alarms, 'MetricAlarms');
            
            			if (!Array.isArray(alarms_list))
            				alarms_list = [alarms_list]
            			alarms_list.forEach(function (alarm) {
            				var dimensions = alarm.Dimensions;
            
            				Zabbix.log(4, '[ AWS Lambda Alarms ] dimensions: ' + JSON.stringify(dimensions));
            
            				if (Array.isArray(alarm.Metrics)) {
            					alarm.Metrics.forEach(function (metric) {
            						if (typeof metric.MetricStat === 'object' && metric.MetricStat !== null
            							&& typeof metric.MetricStat.Metric === 'object' && metric.MetricStat.Metric !== null
            							&& Array.isArray(metric.MetricStat.Metric.Dimensions)) {
            							dimensions = dimensions.concat(metric.MetricStat.Metric.Dimensions);
            						}
            					});
            				}
            				for (var i in dimensions) {
            					if (dimensions[i].Name === 'FunctionName' && dimensions[i].Value === AWS.params.name) {
            						result.push(alarm);
            						break;
            					}
            				}
            			});
            		}
            
            		return result;
            	}
            }
            
            try {
            	AWS.setParams(JSON.parse(value));
            
            	return JSON.stringify(AWS.getAlarms());
            }
            catch (error) {
            	error += (String(error).endsWith('.')) ? '' : '.';
            	Zabbix.log(3, '[ AWS Lambda Alarms ] ERROR: ' + error);
            
            	return JSON.stringify({ 'error': error });
            }
          description: '`DescribeAlarms` API method: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html'
          preprocessing:
            - type: CHECK_NOT_SUPPORTED
              parameters:
                - '-1'
          timeout: '{$AWS.DATA.TIMEOUT}'
          parameters:
            - name: AccessKeyId
              value: '{$AWS.ACCESS.KEY.ID}'
            - name: auth_type
              value: '{$AWS.AUTH_TYPE}'
            - name: name
              value: '{$AWS.LAMBDA.NAME}'
            - name: proxy
              value: '{$AWS.PROXY}'
            - name: region
              value: '{$AWS.REGION}'
            - name: SecretAccessKey
              value: '{$AWS.SECRET.ACCESS.KEY}'
          tags:
            - tag: component
              value: raw
        - uuid: 24c4972d090f4e72abc473752aac27d8
          name: 'AWS Lambda: Get metrics data'
          type: SCRIPT
          key: aws.lambda.get_metrics
          delay: 0s;m/1
          history: '0'
          value_type: TEXT
          params: |
            var AWS = {
            	params: {},
            	metadata: 'http://169.254.169.254/latest/meta-data/iam/security-credentials',
            	request_period: 60,
            
            	getField: function (data, path) {
            		var steps = path.split('.');
            		for (var i = 0; i < steps.length; i++) {
            			var step = steps[i];
            			if (typeof data !== 'object' || typeof data[step] === 'undefined') {
            				throw 'Required field was not found: ' + path;
            			}
            
            			data = data[step];
            		}
            
            		return data;
            	},
            
            	setParams: function (params) {
            		AWS.params['proxy'] = params.proxy;
            		switch (AWS.getField(params, 'auth_type')) {
            			case 'role_base':
            				AWS.params['auth_type'] = 'role_base';
            				var request = new HttpRequest();
            				if (typeof AWS.params.proxy !== 'undefined' && AWS.params.proxy !== '') {
            					request.setProxy(AWS.params.proxy);
            				}
            				var IamRoleName = request.get(AWS.metadata);
            
            				if (request.getStatus() !== 200 || IamRoleName === null || IamRoleName === '') {
            					throw 'Error getting security credentials from instance metadata. Role not found.';
            				}
            
            				credentials = request.get(AWS.metadata + '/' + encodeURI(IamRoleName));
            
            				if (request.getStatus() !== 200 || credentials === null || credentials === '') {
            					throw 'Error getting security credentials from instance metadata.';
            				}
            
            				try {
            					credentials = JSON.parse(credentials);
            				}
            				catch (error) {
            					throw 'Failed to parse response received from instance metadata. Check debug log for more information.';
            				}
            
            				['AccessKeyId', 'SecretAccessKey', 'Token'].forEach(function (field) {
            					if (typeof credentials !== 'object' || typeof credentials[field] === 'undefined' || credentials[field] === '') {
            						throw 'Required credentials are not set: "' + field + '".';
            					};
            					AWS.params[field] = credentials[field];
            				});
            				break;
            			default:
            				AWS.params['auth_type'] = 'access_key';
            				['AccessKeyId', 'SecretAccessKey'].forEach(function (field) {
            					if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
            						throw 'Required param is not set: "' + field + '".';
            					}
            					AWS.params[field] = params[field];
            				});
            		}
            		['region', 'name'].forEach(function (field) {
            			if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
            				throw 'Required param is not set: "' + field + '".';
            			}
            			AWS.params[field] = params[field];
            		});
            
            	},
            
            	sign: function (key, message) {
            		var hex = hmac('sha256', key, message);
            
            		if ((hex.length % 2) === 1) {
            			throw 'Invalid length of a hex string!';
            		}
            
            		var result = new Int8Array(hex.length / 2);
            		for (var i = 0, b = 0; i < hex.length; i += 2, b++) {
            			result[b] = parseInt(hex.substring(i, i + 2), 16);
            		}
            
            		return result;
            	},
            
            	renderMetricQuery: function (period, name) {
            		var metrics_list = [
            			'AsyncEventsReceived:Average',
            			'AsyncEventAge:Average',
            			'AsyncEventsDropped:Average',
            			'ConcurrentExecutions:Average',
            			'UnreservedConcurrentExecutions:Sum',
            			'Invocations:Sum',
            			'Errors:Sum',
            			'Throttles:Sum',
            			'Duration:Average'
            		];
            
            		var metric_payload = [];
            		metrics_list.forEach(function (metric, index) {
            			var parts = metric.split(':', 2);
            			metric_payload.push({
            				'Id': 'm' + index,
            				'MetricStat': {
            					'Metric': {
            						'MetricName': parts[0],
            						'Namespace': 'AWS/Lambda',
            						'Dimensions': [
            							{
            								'Name': 'FunctionName',
            								'Value': name,
            							}
            						]
            					},
            					'Period': period,
            					'Stat': parts[1],
            				}
            			});
            		});
            
            		return metric_payload;
            	},
            
            	request: function (method, region, service, data) {
            		if (typeof data === 'undefined' || data === null) {
            			data = JSON.stringify([]);
            		}
            		else {
            			data = JSON.stringify(data)
            		}
            		var amzdate = (new Date()).toISOString().replace(/\.\d+Z/, 'Z').replace(/[-:]/g, ''),
            			date = amzdate.replace(/T\d+Z/, ''),
            			canonical_uri = '/',
            			host = service + '.' + region + '.amazonaws.com';
            
            		if (AWS.params.auth_type === 'role_base') {
            			var canonical_headers = 'content-encoding:amz-1.0\n' + 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n' + 'x-amz-security-token:' + AWS.params.Token + '\n',
            				signed_headers = 'content-encoding;host;x-amz-date;x-amz-security-token';
            		} else {
            			var canonical_headers = 'content-encoding:amz-1.0\n' + 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n',
            				signed_headers = 'content-encoding;host;x-amz-date';
            		}
            
            		canonical_request = method + '\n' + canonical_uri + '\n' + '\n' + canonical_headers + '\n' + signed_headers + '\n' + sha256(data);
            		url = 'https://' + host + canonical_uri;
            
            		var credential_scope = date + '/' + region + '/' + service + '/' + 'aws4_request',
            			request_string = 'AWS4-HMAC-SHA256' + '\n' + amzdate + '\n' + credential_scope + '\n' + sha256(canonical_request),
            			key = AWS.sign('AWS4' + AWS.params.SecretAccessKey, date);
            
            		key = AWS.sign(key, region);
            		key = AWS.sign(key, service);
            		key = AWS.sign(key, 'aws4_request');
            
            		var request = new HttpRequest();
            
            		if (typeof AWS.params.proxy !== 'undefined' && AWS.params.proxy !== '') {
            			request.setProxy(AWS.params.proxy);
            		}
            		request.addHeader('x-amz-date: ' + amzdate);
            		request.addHeader('x-amz-content-sha256:' + sha256(data));
            		request.addHeader('X-Amz-Target: GraniteServiceVersion20100801.GetMetricData')
            		request.addHeader('Accept: application/json');
            		request.addHeader('Content-Type: application/json');
            		request.addHeader('Content-Encoding: amz-1.0');
            		request.addHeader('Authorization: ' + 'AWS4-HMAC-SHA256 Credential=' + AWS.params.AccessKeyId + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + hmac('sha256', key, request_string));
            		if (AWS.params.auth_type === 'role_base')
            			request.addHeader('X-Amz-Security-Token: ' + AWS.params.Token);
            
            		Zabbix.log(4, '[ AWS Lambda Get metrics ] Sending request: ' + url);
            		response = request.post(url, data);
            		Zabbix.log(4, '[ AWS Lambda Get metrics ] Received response with status code ' + request.getStatus() + ': ' + response);
            		if (request.getStatus() !== 200) {
            			throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
            		}
            
            		return JSON.parse(response);
            	},
            
            	getMetricsData: function () {
            		var end_time = Math.floor((new Date().getTime()) / 1000),
            			start_time = end_time - AWS.request_period * 60;
            		payload = {
            			'StartTime': start_time,
            			'EndTime': end_time,
            			'ScanBy': 'TimestampDescending',
            			'MetricDataQueries': AWS.renderMetricQuery(AWS.request_period, AWS.params.name)
            		};
            
            		return AWS.getField(AWS.request('POST', AWS.params.region, 'monitoring', payload), 'MetricDataResults');
            	}
            };
            
            try {
            	AWS.setParams(JSON.parse(value));
            	return JSON.stringify(AWS.getMetricsData());
            }
            catch (error) {
            	error += (String(error).endsWith('.')) ? '' : '.';
            	Zabbix.log(3, '[ AWS Lambda Get metrics ] ERROR: ' + error);
            
            	return JSON.stringify({ 'error': error });
            }
          description: |
            Get Lambda function metrics.
            Full metrics list related to the Lambda function: https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html
          preprocessing:
            - type: CHECK_NOT_SUPPORTED
              parameters:
                - '-1'
          timeout: '{$AWS.DATA.TIMEOUT}'
          parameters:
            - name: AccessKeyId
              value: '{$AWS.ACCESS.KEY.ID}'
            - name: auth_type
              value: '{$AWS.AUTH_TYPE}'
            - name: name
              value: '{$AWS.LAMBDA.NAME}'
            - name: proxy
              value: '{$AWS.PROXY}'
            - name: region
              value: '{$AWS.REGION}'
            - name: SecretAccessKey
              value: '{$AWS.SECRET.ACCESS.KEY}'
          tags:
            - tag: component
              value: raw
        - uuid: 1bab5865e01b4233bc2bb5cb17516360
          name: 'AWS Lambda: Invocations sum'
          type: DEPENDENT
          key: aws.lambda.invocations.sum
          description: 'The number of times that your function code is invoked, including successful invocations and invocations that result in a function error. Invocations aren''t recorded if the invocation request is throttled or otherwise results in an invocation error. The value of `Invocations` equals the number of requests billed.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "Invocations")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: invocation
        - uuid: 2bfa15a2c1ef4f66a8b2065e34a1a690
          name: 'AWS Lambda: Get metrics check'
          type: DEPENDENT
          key: aws.lambda.metrics.check
          value_type: CHAR
          description: 'Check that the Lambda function metrics data has been received correctly.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - $.error
              error_handler: CUSTOM_VALUE
            - type: DISCARD_UNCHANGED_HEARTBEAT
              parameters:
                - 3h
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: status
          triggers:
            - uuid: 95ed5e8c560f4c6e89ed9d1a754ed032
              expression: 'length(last(/AWS Lambda by HTTP/aws.lambda.metrics.check))>0'
              name: 'AWS Lambda: Failed to get metrics data'
              event_name: 'AWS Lambda: Failed to get CloudWatch metrics for the Lambda function'
              opdata: 'Current value: {ITEM.LASTVALUE1}'
              priority: WARNING
              description: 'Failed to get CloudWatch metrics for the Lambda function.'
              tags:
                - tag: scope
                  value: availability
        - uuid: 9f141ce56187497794d109c030c43a06
          name: 'AWS Lambda: Throttles sum'
          type: DEPENDENT
          key: aws.lambda.throttles.sum
          description: 'The number of invocation requests that are throttled. When all function instances are processing requests and no concurrency is available to scale up, Lambda rejects additional requests with a `TooManyRequestsException` error.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "Throttles")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: invocation
        - uuid: b0ecd33e96734ac69447c095032dea55
          name: 'AWS Lambda: Unreserved concurrent executions maximum'
          type: DEPENDENT
          key: aws.lambda.unreserved_concurrent_executions.max
          description: 'For a Region, the number of events that function without reserved concurrency are processing.'
          preprocessing:
            - type: JSONPATH
              parameters:
                - '$.[?(@.Label == "UnreservedConcurrentExecutions")].Values.first().first()'
              error_handler: DISCARD_VALUE
          master_item:
            key: aws.lambda.get_metrics
          tags:
            - tag: component
              value: concurrency
      discovery_rules:
        - uuid: 7b00199cc6c041f5998c798884305f9e
          name: 'Lambda alarm discovery'
          type: DEPENDENT
          key: aws.lambda.discovery
          filter:
            evaltype: AND
            conditions:
              - macro: '{#ALARM_NAME}'
                value: '{$AWS.LAMBDA.LLD.FILTER.ALARM_NAME.MATCHES}'
              - macro: '{#ALARM_NAME}'
                value: '{$AWS.LAMBDA.LLD.FILTER.ALARM_NAME.NOT_MATCHES}'
                operator: NOT_MATCHES_REGEX
              - macro: '{#ALARM_SERVICE_NAMESPACE}'
                value: '{$AWS.LAMBDA.LLD.FILTER.ALARM_SERVICE_NAMESPACE.MATCHES}'
              - macro: '{#ALARM_SERVICE_NAMESPACE}'
                value: '{$AWS.LAMBDA.LLD.FILTER.ALARM_SERVICE_NAMESPACE.NOT_MATCHES}'
                operator: NOT_MATCHES_REGEX
          description: 'Used for the discovery of alarm Lambda functions.'
          item_prototypes:
            - uuid: 893819314ae34f31bde78612679da46b
              name: 'AWS Lambda Alarms: [{#ALARM_NAME}]: Get metrics'
              type: DEPENDENT
              key: 'aws.lambda.alarm.get_metrics["{#ALARM_NAME}"]'
              history: '0'
              value_type: TEXT
              description: 'Get metrics about the alarm state and its reason.'
              preprocessing:
                - type: JSONPATH
                  parameters:
                    - '$.[?(@.AlarmName == "{#ALARM_NAME}")].first()'
                  error_handler: DISCARD_VALUE
              master_item:
                key: aws.lambda.get_alarms
              tags:
                - tag: component
                  value: raw
            - uuid: 2e34c9ed36c64a6aade389e739340529
              name: 'AWS Lambda Alarms: [{#ALARM_NAME}]: State'
              type: DEPENDENT
              key: 'aws.lambda.alarm.state["{#ALARM_NAME}"]'
              description: |
                The value of the alarm state. Possible values:
                0 - OK;
                1 - INSUFFICIENT_DATA;
                2 - ALARM.
                Alarm description:
                `{#ALARM_DESCRIPTION}`
              valuemap:
                name: 'Alarm state'
              preprocessing:
                - type: JSONPATH
                  parameters:
                    - $.StateValue
                  error_handler: CUSTOM_VALUE
                  error_handler_params: '3'
                - type: JAVASCRIPT
                  parameters:
                    - |
                      var state = ['OK', 'INSUFFICIENT_DATA', 'ALARM'];
                      
                      return state.indexOf(value.trim()) === -1 ? 255 : state.indexOf(value.trim());
              master_item:
                key: 'aws.lambda.alarm.get_metrics["{#ALARM_NAME}"]'
              tags:
                - tag: component
                  value: alarms
              trigger_prototypes:
                - uuid: fc0d5744b0284362897a2d3191727d66
                  expression: 'last(/AWS Lambda by HTTP/aws.lambda.alarm.state["{#ALARM_NAME}"])=1'
                  name: 'AWS Lambda Alarms: [{#ALARM_NAME}] has ''Insufficient data'' state'
                  event_name: 'AWS Lambda Alarms: [{#ALARM_NAME}] has ''Insufficient data'' state'
                  opdata: 'Current value: {ITEM.LASTVALUE1}'
                  priority: INFO
                  description: 'Either the alarm has just started, the metric is not available, or not enough data is available for the metric to determine the alarm state.'
                  tags:
                    - tag: scope
                      value: notice
            - uuid: 7a314dfe3f4e4142bf4827f6cb6285bd
              name: 'AWS Lambda Alarms: [{#ALARM_NAME}]: State reason'
              type: DEPENDENT
              key: 'aws.lambda.alarm.state_reason["{#ALARM_NAME}"]'
              value_type: TEXT
              description: |
                An explanation for the alarm state reason in text format.
                Alarm description:
                `{#ALARM_DESCRIPTION}`
              preprocessing:
                - type: JSONPATH
                  parameters:
                    - $.StateReason
                  error_handler: DISCARD_VALUE
                - type: DISCARD_UNCHANGED_HEARTBEAT
                  parameters:
                    - 3h
              master_item:
                key: 'aws.lambda.alarm.get_metrics["{#ALARM_NAME}"]'
              tags:
                - tag: component
                  value: alarms
          trigger_prototypes:
            - uuid: c3ce7372e8cf4ff48eee7f91870dc58d
              expression: 'last(/AWS Lambda by HTTP/aws.lambda.alarm.state["{#ALARM_NAME}"])=2 and length(last(/AWS Lambda by HTTP/aws.lambda.alarm.state_reason["{#ALARM_NAME}"]))>0'
              name: 'AWS Lambda Alarms: [{#ALARM_NAME}] has ''Alarm'' state'
              event_name: 'AWS Lambda Alarms: [{#ALARM_NAME}] has ''Alarm'' state (reason: {ITEM.LASTVALUE2})'
              opdata: 'Reason: {ITEM.LASTVALUE2}'
              priority: AVERAGE
              description: |
                The alarm `{#ALARM_NAME}` is in the ALARM state.
                Reason: `{ITEM.LASTVALUE2}`
              tags:
                - tag: scope
                  value: availability
          master_item:
            key: aws.lambda.get_alarms
          preprocessing:
            - type: JAVASCRIPT
              parameters:
                - |
                  var result = [];
                  var alarms = JSON.parse(value);
                  
                  alarms.forEach(function(alarm) {
                  
                   result.push({
                  '{#ALARM_DESCRIPTION}': alarm.AlarmDescription !== null ? alarm.AlarmDescription : 'None' ,
                  '{#ALARM_NAME}': alarm.AlarmName,
                  '{#ALARM_PERIOD}': alarm.Period,
                  '{#METRIC_NAME}': alarm.MetricName,
                  '{#ALARM_SERVICE_NAMESPACE}': alarm.Namespace !== null ? alarm.Namespace : 'None'
                    });
                  });
                  
                  return JSON.stringify(result);
            - type: DISCARD_UNCHANGED_HEARTBEAT
              parameters:
                - 3h
      tags:
        - tag: class
          value: software
        - tag: target
          value: aws
        - tag: target
          value: lambda
      macros:
        - macro: '{$AWS.ACCESS.KEY.ID}'
          description: 'Access key ID.'
        - macro: '{$AWS.AUTH_TYPE}'
          value: access_key
          description: 'Authorization method. Possible values: `role_base`, `access_key`.'
        - macro: '{$AWS.DATA.TIMEOUT}'
          value: 60s
          description: 'API response timeout.'
        - macro: '{$AWS.LAMBDA.ARN}'
          description: 'Amazon Resource Names (ARN) of the load balancer.'
        - macro: '{$AWS.LAMBDA.LLD.FILTER.ALARM_NAME.MATCHES}'
          value: '.*'
          description: 'Filter of discoverable alarms by name.'
        - macro: '{$AWS.LAMBDA.LLD.FILTER.ALARM_NAME.NOT_MATCHES}'
          value: CHANGE_IF_NEEDED
          description: 'Filter to exclude discovered alarms by name.'
        - macro: '{$AWS.LAMBDA.LLD.FILTER.ALARM_SERVICE_NAMESPACE.MATCHES}'
          value: '.*'
          description: 'Filter of discoverable alarms by namespace.'
        - macro: '{$AWS.LAMBDA.LLD.FILTER.ALARM_SERVICE_NAMESPACE.NOT_MATCHES}'
          value: CHANGE_IF_NEEDED
          description: 'Filter to exclude discovered alarms by namespace.'
        - macro: '{$AWS.PROXY}'
          description: 'Sets the HTTP proxy value. If this macro is empty, no proxy is used.'
        - macro: '{$AWS.REGION}'
          value: us-west-1
          description: 'AWS Application Load Balancer region code.'
        - macro: '{$AWS.SECRET.ACCESS.KEY}'
          type: SECRET_TEXT
          description: 'Secret access key.'
      dashboards:
        - uuid: aab5dac54efa4d0cbc0f7980220e172e
          name: 'Overview AWS Lambda function'
          pages:
            - name: 'AWS Lambda: Invocation metrics'
              widgets:
                - type: graph
                  width: '24'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Invocations'
                    - type: STRING
                      name: reference
                      value: ECCBA
                - type: graph
                  'y': '5'
                  width: '24'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Errors'
                    - type: STRING
                      name: reference
                      value: DBBFF
                - type: graph
                  'y': '10'
                  width: '24'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Duration'
                    - type: STRING
                      name: reference
                      value: FBDDF
                - type: graph
                  'y': '15'
                  width: '24'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Throttles'
                    - type: STRING
                      name: reference
                      value: BDAAA
            - name: 'AWS Lambda: Asynchronous invocation metrics'
              widgets:
                - type: graph
                  width: '8'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Asynchronous events'
                    - type: STRING
                      name: reference
                      value: CAADA
                - type: graph
                  x: '8'
                  width: '8'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Async event age'
                    - type: STRING
                      name: reference
                      value: EAFEB
                - type: graph
                  x: '16'
                  width: '8'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Async dropped events'
                    - type: STRING
                      name: reference
                      value: ECADD
            - name: 'AWS Lambda: Concurrency metrics'
              widgets:
                - type: graph
                  width: '12'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Concurrent executions'
                    - type: STRING
                      name: reference
                      value: CAECA
                - type: graph
                  x: '12'
                  width: '12'
                  height: '5'
                  fields:
                    - type: GRAPH
                      name: graphid.0
                      value:
                        host: 'AWS Lambda by HTTP'
                        name: 'AWS Lambda: Unreserved concurrent executions'
                    - type: STRING
                      name: reference
                      value: CFEBE
      valuemaps:
        - uuid: a61fdde5c78748339a903f1224524deb
          name: 'Alarm state'
          mappings:
            - value: '0'
              newvalue: OK
            - value: '1'
              newvalue: 'Insufficient data'
            - value: '2'
              newvalue: Alarm
            - value: '255'
              newvalue: Unknown
  graphs:
    - uuid: af2dcb92a19a47c2a6f8d1ea78794553
      name: 'AWS Lambda: Async dropped events'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.async_events_dropped.sum
    - uuid: c6d59fa52671477db6865874acedec1b
      name: 'AWS Lambda: Async event age'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.async_event_age.avg
    - uuid: 2b98a8ff2c584419b962ed0cb3fe8809
      name: 'AWS Lambda: Asynchronous events'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.async_events_received.sum
    - uuid: 8eb1c4bbb3974048a76e4c84bdfa25a5
      name: 'AWS Lambda: Concurrent executions'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.concurrent_executions.max
    - uuid: 7e1dad2ad49d4c0487e4e724594331fa
      name: 'AWS Lambda: Duration'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.duration.avg
    - uuid: 07288fd5c2ff4806a6749e114d0cf93d
      name: 'AWS Lambda: Errors'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.errors.sum
    - uuid: cc854ebac57143629b49f1fae3598d8b
      name: 'AWS Lambda: Invocations'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.invocations.sum
    - uuid: c16f61d853474a0f9a251327873ef62e
      name: 'AWS Lambda: Throttles'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.dead_letter_errors.sum
        - sortorder: '1'
          drawtype: BOLD_LINE
          color: F63100
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.throttles.sum
    - uuid: d01c132670fb4347b591ddb96900fa99
      name: 'AWS Lambda: Unreserved concurrent executions'
      graph_items:
        - drawtype: BOLD_LINE
          color: 199C0D
          item:
            host: 'AWS Lambda by HTTP'
            key: aws.lambda.unreserved_concurrent_executions.max
