0

下面是我使用 API 在 AWS 中创建 VPC 的代码,但出现错误。

代码:

CreateAccessKeyRequest key = new CreateAccessKeyRequest();
BasicAWSCredentials cred = new BasicAWSCredentials("", "");
key.setRequestCredentials(cred);
AmazonEC2 ec2 = new AmazonEC2Client();
System.out.println("Creating VPC.....\n");
CreateVpcRequest newVPC = new CreateVpcRequest("In");
newVPC.setRequestCredentials(key.getRequestCredentials());
String cidrBlock = "192.168.1.70/28";
newVPC.setCidrBlock(cidrBlock);
newVPC.setInstanceTenancy(Tenancy.Default);
AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(cred);
CreateVpcResult res = ec2.createVpc(newVPC);
Vpc vp = res.getVpc();
vp.setIsDefault(true);
String vpcId = vp.getVpcId();
System.out.println("Created VPC" + vpcId);

错误:

Exception in thread "main" com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
    at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
    at com.amazonaws.services.ec2.AmazonEC2Client.invoke(AmazonEC2Client.java:10540)
    at com.amazonaws.services.ec2.AmazonEC2Client.createVpc(AmazonEC2Client.java:5709)
    at CreateUserRequest.main(CreateUserRequest.java:29)
4

2 回答 2

0

感谢 Sébastien Stormacq 为我的回答提供支持。我们已经找到了这个问题的解决方案。实际上,我的 Windows 桌面时间比实际时间晚了 6 分钟。因此,在验证 AWS 凭证方面存在冲突。我们手动将时间与准确时间同步,现在它的工作就像一个魅力。当遇到相同问题时,请检查 Windows 时间。

于 2015-04-27T07:54:50.717 回答
0

上面的代码片段有几个问题。

首先,硬编码访问密钥/秘密密钥是个坏主意。这些应该存储在外部配置文件或环境变量中。如果此代码旨在从 EC2 实例运行,则应改用“角色”和实例配置文件。这在http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/credentials.html有清楚的解释

话虽如此,如果这只是为了快速测试,让我们假设硬编码访问密钥和密钥确实是可能的,代码级别还有其他问题:

  • 您不需要使用CreateAccessKeyRequest,因为这是生成新访问密钥/秘密密钥的 API 调用

  • AmazonEC2Client没有提及您的凭据提供程序

  • 无需为 VPC 请求本身设置凭证提供程序

  • setInstanceTenancy不是必需的,这是默认设置

  • vp.setIsDefault(true);没用。如果您想创建默认 VPC,请向我们的支持团队提出请求,他们会将您的 VPC 标记为默认 VPC(请参阅https://aws.amazon.com/premiumsupport/knowledge-center/deleted-default-vpc/ )

这是创建 VPC 的修改后的代码示例

package com.stormacq;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.*;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateVpcRequest;
import com.amazonaws.services.ec2.model.CreateVpcResult;
import com.amazonaws.services.ec2.model.Vpc;

public class Main {

    public static void main(String[] args) {
        BasicAWSCredentials cred = new BasicAWSCredentials("AK...OQ", "gH...tp");
        AmazonEC2 ec2 = new AmazonEC2Client(cred);
        ec2.setRegion(Region.getRegion(Regions.US_EAST_1));

        System.out.println("Creating VPC...");
        CreateVpcRequest newVPC = new CreateVpcRequest("In");

        newVPC.setCidrBlock("192.168.1.70/28");
        CreateVpcResult res = ec2.createVpc(newVPC);
        Vpc vp = res.getVpc();

        String vpcId = vp.getVpcId();
        System.out.println("Created VPC " + vpcId);
    }
}
于 2015-04-22T08:00:13.063 回答