forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGettingStartedWithLambda.php
More file actions
177 lines (157 loc) · 7.04 KB
/
Copy pathGettingStartedWithLambda.php
File metadata and controls
177 lines (157 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
<?php
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# snippet-start:[php.example_code.lambda.basics.scenario]
namespace Lambda;
use Aws\S3\S3Client;
use GuzzleHttp\Psr7\Stream;
use Iam\IAMService;
class GettingStartedWithLambda
{
public function run()
{
echo("\n");
echo("--------------------------------------\n");
print("Welcome to the AWS Lambda getting started demo using PHP!\n");
echo("--------------------------------------\n");
$clientArgs = [
'region' => 'us-west-2',
'version' => 'latest',
'profile' => 'default',
];
$uniqid = uniqid();
$iamService = new IAMService();
$s3client = new S3Client($clientArgs);
$lambdaService = new LambdaService();
echo "First, let's create a role to run our Lambda code.\n";
$roleName = "test-lambda-role-$uniqid";
$rolePolicyDocument = "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{
\"Effect\": \"Allow\",
\"Principal\": {
\"Service\": \"lambda.amazonaws.com\"
},
\"Action\": \"sts:AssumeRole\"
}
]
}";
$role = $iamService->createRole($roleName, $rolePolicyDocument);
echo "Created role {$role['RoleName']}.\n";
$iamService->attachRolePolicy(
$role['RoleName'],
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
);
echo "Attached the AWSLambdaBasicExecutionRole to {$role['RoleName']}.\n";
echo "\nNow let's create an S3 bucket and upload our Lambda code there.\n";
$bucketName = "amzn-s3-demo-bucket-$uniqid";
$s3client->createBucket([
'Bucket' => $bucketName,
]);
echo "Created bucket $bucketName.\n";
$functionName = "doc_example_lambda_$uniqid";
$codeBasic = __DIR__ . "/lambda_handler_basic.zip";
$handler = "lambda_handler_basic";
$file = file_get_contents($codeBasic);
$s3client->putObject([
'Bucket' => $bucketName,
'Key' => $functionName,
'Body' => $file,
]);
echo "Uploaded the Lambda code.\n";
$createLambdaFunction = $lambdaService->createFunction($functionName, $role, $bucketName, $handler);
// Wait until the function has finished being created.
do {
$getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
} while ($getLambdaFunction['Configuration']['State'] == "Pending");
echo "Created Lambda function {$getLambdaFunction['Configuration']['FunctionName']}.\n";
sleep(1);
echo "\nOk, let's invoke that Lambda code.\n";
$basicParams = [
'action' => 'increment',
'number' => 3,
];
/** @var Stream $invokeFunction */
$invokeFunction = $lambdaService->invoke($functionName, $basicParams)['Payload'];
$result = json_decode($invokeFunction->getContents())->result;
echo "After invoking the Lambda code with the input of {$basicParams['number']} we received $result.\n";
echo "\nSince that's working, let's update the Lambda code.\n";
$codeCalculator = "lambda_handler_calculator.zip";
$handlerCalculator = "lambda_handler_calculator";
echo "First, put the new code into the S3 bucket.\n";
$file = file_get_contents($codeCalculator);
$s3client->putObject([
'Bucket' => $bucketName,
'Key' => $functionName,
'Body' => $file,
]);
echo "New code uploaded.\n";
$lambdaService->updateFunctionCode($functionName, $bucketName, $functionName);
// Wait for the Lambda code to finish updating.
do {
$getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
} while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful");
echo "New Lambda code uploaded.\n";
$environment = [
'Variable' => ['Variables' => ['LOG_LEVEL' => 'DEBUG']],
];
$lambdaService->updateFunctionConfiguration($functionName, $handlerCalculator, $environment);
do {
$getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
} while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful");
echo "Lambda code updated with new handler and a LOG_LEVEL of DEBUG for more information.\n";
echo "Invoke the new code with some new data.\n";
$calculatorParams = [
'action' => 'plus',
'x' => 5,
'y' => 4,
];
$invokeFunction = $lambdaService->invoke($functionName, $calculatorParams, "Tail");
$result = json_decode($invokeFunction['Payload']->getContents())->result;
echo "Indeed, {$calculatorParams['x']} + {$calculatorParams['y']} does equal $result.\n";
echo "Here's the extra debug info: ";
echo base64_decode($invokeFunction['LogResult']) . "\n";
echo "\nBut what happens if you try to divide by zero?\n";
$divZeroParams = [
'action' => 'divide',
'x' => 5,
'y' => 0,
];
$invokeFunction = $lambdaService->invoke($functionName, $divZeroParams, "Tail");
$result = json_decode($invokeFunction['Payload']->getContents())->result;
echo "You get a |$result| result.\n";
echo "And an error message: ";
echo base64_decode($invokeFunction['LogResult']) . "\n";
echo "\nHere's all the Lambda functions you have in this Region:\n";
$listLambdaFunctions = $lambdaService->listFunctions(5);
$allLambdaFunctions = $listLambdaFunctions['Functions'];
$next = $listLambdaFunctions->get('NextMarker');
while ($next != false) {
$listLambdaFunctions = $lambdaService->listFunctions(5, $next);
$next = $listLambdaFunctions->get('NextMarker');
$allLambdaFunctions = array_merge($allLambdaFunctions, $listLambdaFunctions['Functions']);
}
foreach ($allLambdaFunctions as $function) {
echo "{$function['FunctionName']}\n";
}
echo "\n\nAnd don't forget to clean up your data!\n";
$lambdaService->deleteFunction($functionName);
echo "Deleted Lambda function.\n";
$iamService->deleteRole($role['RoleName']);
echo "Deleted Role.\n";
$deleteObjects = $s3client->listObjectsV2([
'Bucket' => $bucketName,
]);
$deleteObjects = $s3client->deleteObjects([
'Bucket' => $bucketName,
'Delete' => [
'Objects' => $deleteObjects['Contents'],
]
]);
echo "Deleted all objects from the S3 bucket.\n";
$s3client->deleteBucket(['Bucket' => $bucketName]);
echo "Deleted the bucket.\n";
}
}
# snippet-end:[php.example_code.lambda.basics.scenario]