PHP SDK call examples for ECS
This topic describes how to install Elastic Compute Service (ECS) SDK V2.0 for PHP and provides an example on how to use the SDK to call ECS API operations. In the example, ECS SDK V2.0 for PHP is used to call the DescribeInstances operation to query information about ECS instances.
Prerequisites
-
The AccessKey of an Alibaba Cloud account provides full access to your resources, which poses a high security risk if the AccessKey is leaked. We recommend that you create a Resource Access Management (RAM) user and grant the RAM user only the required permissions. Then, use the AccessKey of the RAM user to call API operations. For more information, see Create an AccessKey.
-
You have granted the RAM user permissions to manage ECS resources. The example code in this topic shows a query operation. In this example, the AliyunECSReadonlyAccess system policy is used. You can grant custom permissions as needed.
-
Use custom policies.
For more information about how to create custom policies, see Create a custom policy and Authorization information.
ECS provides custom policy examples based on best practices. You can use these examples to quickly create custom policies that meet your business needs. For more information, see Custom policies.
-
Use system policies.
For information about all system policies that ECS supports and their permission descriptions, see System policies for ECS.
-
-
Configure the AccessKey using environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.
Install the SDK
For information about how to install the PHP V2.0 SDK, see SDK Center. You can copy the following command and run it in the terminal to install the ECS SDK:
composer require alibabacloud/ecs-20140526 4.3.0
Using the SDK
1. Initialize a client.
Alibaba Cloud SDKs support multiple access credentials, such as AccessKey pairs and Security Token Service (STS) tokens, to initialize clients. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a client.
<?php
require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use Darabonba\OpenApi\Models\Config;
class Sample
{
public static function createClient()
{
$config = new Config([
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
"endpoint" => "ecs.cn-hangzhou.aliyuncs.com",
]);
return new Ecs($config);
}
}
2. Create a request object for the API operation.
Before building the request object, refer to the interface's API reference for parameter information.
The name of a request object is in the {Operation name}Request format. For example, the request object for the DescribeInstances operation is named DescribeInstancesRequest.
// Create a request object.
$describeInstancesRequest = new DescribeInstancesRequest([
"regionId" => "cn-beijing"
]);
3. Call the API operation.
When you call an API operation from a client, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see Advanced settings.
The name of a response object is in the {Operation name}Response format. For example, the response object for the DescribeInstances operation is named DescribeInstancesResponse.
// Create a runtime configuration object.
$runtime = new RuntimeOptions();
// Send the request.
$describeInstancesResponse = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);
4. Handle exceptions.
SDK for PHP classifies exceptions into the following types:
-
TeaUnableRetryError: This type of exception is caused by network issues. In most cases, a TeaUnableRetryError exception is thrown when the maximum number of retries is reached. You can call the
getLastExceptionmethod to obtain information about the API request when the exception occurs. -
TeaError: In most cases, this type of exception is caused by business errors.
We recommend that you properly handle exceptions by performing operations, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.
5. Complete sample code.
<?php
require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstancesRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
class Sample
{
public static function main()
{
try {
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
"endpoint" => "ecs.cn-beijing.aliyuncs.com", // <endpoint>
]);
$client = new Ecs($config);
// Create a request object.
$describeInstancesRequest = new DescribeInstancesRequest([
"regionId" => "cn-beijing"
]);
// Create a runtime configuration object.
$runtime = new RuntimeOptions();
// Send the request.
$describeInstancesResponse = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);
var_dump($describeInstancesResponse);
} catch (\Exception $error) {
if ($error instanceof TeaError) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference.
print_r("message:" . $error->getMessage() . "\n");
print_r("code:" . $error->getCode() . "\n");
print_r($error->data);
} elseif ($error instanceof TeaUnableRetryError) {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference.
print_r($error->getLastException());
} else {
// Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference.
print_r("message:" . $error->getMessage());
}
}
}
}
Sample::main();
Scenario-based examples
More information
In addition to the methods described above, you can also make generalized calls to the ECS OpenAPI. For more information, see Generalized calls.
If you use ECS SDK V1.0 for PHP, see V1.0 PHP SDK for information about the SDK.