以下是使用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)
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
感谢SébastienStormacq支持我的回答。我们找到了解决此问题的方法。实际上我的Windows桌面时间比实际时间晚了6分钟。因此,它会收到冲突以验证AWS凭据。我们用准确的时间手动同步时间,现在它的工作就像一个魅力。一旦遇到同样的问题,请检查Windows时间。