使用第 3 AWS SDK for PHP 版向 Amazon CloudWatch 活動發送事件 - AWS SDK for PHP

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

使用第 3 AWS SDK for PHP 版向 Amazon CloudWatch 活動發送事件

CloudWatch 事件提供近乎即時的系統事件串流,描述 Amazon Web Services (AWS) 資源對任何不同目標的變更。使用簡單的規則,您可以比對事件,並將這些事件轉傳到一或多個目標函數或串流。

下列範例示範如何:

  • 使用建立規則PutRule

  • 使用將目標新增至規則PutTargets

  • 使用將自訂事件傳送至 CloudWatch 事件PutEvents

所有的範例程式碼都可以AWS SDK for PHP在這裡取得 GitHub。

登入資料

在執行範例程式碼之前,請依照中的說明設定您的AWS認證憑證。然後匯入AWS SDK for PHP,如中所述基本使用

建立規則

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

範例程式碼

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putRule([ 'Name' => 'DEMO_EVENT', // REQUIRED 'RoleArn' => 'IAM_ROLE_ARN', 'ScheduleExpression' => 'rate(5 minutes)', 'State' => 'ENABLED', ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

將目標新增至規則

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

範例程式碼

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putTargets([ 'Rule' => 'DEMO_EVENT', // REQUIRED 'Targets' => [ // REQUIRED [ 'Arn' => 'LAMBDA_FUNCTION_ARN', // REQUIRED 'Id' => 'myCloudWatchEventsTarget' // REQUIRED ], ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

傳送自訂事件

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

範例程式碼

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putEvents([ 'Entries' => [ // REQUIRED [ 'Detail' => '<string>', 'DetailType' => '<string>', 'Resources' => ['<string>'], 'Source' => '<string>', 'Time' => time() ], ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }