You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS PHP SDK调用API创建安全组报MalformedQueryString错误排查

问题详情

依赖版本

使用的AWS PHP SDK版本如下:

AWS PHP SDK Version 3.188.1 - 2021-08-09

相关代码

require '../aws_sdk/aws-autoloader.php';
use Aws\Ec2\Ec2Client;
use Aws\Exception\AwsException;

$Ec2Client = Ec2Client('mykey', 'mysecretkey', '2016-11-15', 'us-east-1');

$params = [
    'DryRun' => true,
    'GroupName' => 'mygroupSG',
    'Description' => 'My Security Group'
];

$results = SecurityGroup($Ec2Client, $params);

function Ec2Client($access_Key, $SecretAccessKey, $version, $region)
{
    try {
        $ec2Client = new Aws\Ec2\Ec2Client([
            'key' => $access_Key, 
            'secret' => $SecretAccessKey,
            'version' => $version,
            'region' => $region
        ]); 
    } catch (Ec2Exception $ex) {
        die($ex->getMessage());
    }
    return $ec2Client;
}

function SecurityGroup($Ec2Client, $params)
{
    try {
        return $Ec2Client->createSecurityGroup($params);
    } catch (Ec2Exception $ex) {
        var_dump($ex);
        die ($ex->getAwsErrorCode());
    }    
}

错误输出

Fatal error: Uncaught exception 'Aws\Ec2\Exception\Ec2Exception' with message 'Error executing "CreateSecurityGroup" on "https://ec2.us-east-1.amazonaws.com"; AWS HTTP error: Client error: `POST https://ec2.us-east-1.amazonaws.com` resulted in a `400 Bad Request` response: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MalformedQueryString</title> </head> </htm (truncated...) Unable to parse error information from response - Error parsing XML: String could not be parsed as XML' GuzzleHttp\Exception\ClientException: Client error: `POST https://ec2.us-east-1.amazonaws.com` resulted in a `400 Bad Request` response: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MalformedQueryString</title> </head> </htm (truncated...) in /aws_sdk/GuzzleHttp/Exception/RequestException.php:113 Stack trace: #0 /aws_sdk/GuzzleHttp/Middleware.php(65): GuzzleHttp\Exception\RequestException in /aws_sdk/Aws/WrappedHttpHandler.php on line 195

前置排查情况

已单独验证Ec2Client实例可正常创建,代码参照AWS官方文档示例编写,因官方存在多版参数列表不同的示例容易混淆,需要该问题的解决方法。

解决方案

问题出在.aws目录下的凭证文件,其中存储的凭证无效导致身份认证失败。Ec2Client初始化阶段仅做参数格式校验,不会实际发起请求校验凭证有效性,因此创建实例时不会抛出对应错误,只有调用业务接口发起实际请求时才会触发认证相关报错。
你可以先校验本地凭证文件(Linux/macOS路径为~/.aws/credentials,Windows路径为C:\Users\你的用户名\.aws\credentials)中的访问密钥、私有密钥是否有效,是否具备EC2安全组创建权限,确认无误后重新运行代码即可。


内容的提问来源于stack exchange,提问作者EastsideDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:36:01