目前僅在 us-east-1 的 EC2 控制台上可用
支援的格式:
先確認區域是否為 us-east-1
手動建立 EC2
查看Console-to-Code 可以看到在 AWS Console 所執行的 API 動作名稱
針對 RunInstances 選擇轉換的格式,其實也會產生CLI代碼
測試 CDK TypeScript code 稍後您將獲得一個 CDK 範本以及有關如何使用它的補充信息
如下參考完整範本
Here is the generated CDK code:
```typescript
import { Vpc, Instance, InstanceClass, InstanceSize, SecurityGroup, Role, InstanceProfile } from "@aws-cdk/aws-ec2";
import { ManagedPolicy } from "@aws-cdk/aws-iam";
// Create VPC, subnet, and security group referenced in CLI command
const vpc = new Vpc(this, "MyVpc");
const subnet = vpc.publicSubnets[0];
const securityGroup = new SecurityGroup(this, "MySecurityGroup", {
vpc,
});
// Create IAM role and instance profile for SSM and CloudWatch access
const iamRole = new Role(this, "MyIamRole", {
assumedBy: new ServicePrincipal("ec2.amazonaws.com"),
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName("AmazonSSMManagedInstanceCore"),
ManagedPolicy.fromAwsManagedPolicyName("CloudWatchAgentServerPolicy"),
],
});
const instanceProfile = new InstanceProfile(this, "MyInstanceProfile", {
role: iamRole,
});
// Create EC2 instance
const instance = new Instance(this, "MyInstance", {
vpc,
instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.NANO),
machineImage: MachineImage.latestAmazonLinux({
generation: AmazonLinuxGeneration.AMAZON_LINUX_2,
}),
keyName: "ming-Virginia",
networkInterfaces: [{
subnet,
associatePublicIpAddress: true,
securityGroups: [securityGroup],
}],
role: instanceProfile,
// Add tags
instanceName: "ming-ai-test",
// Metadata options
metadataOptions: {
httpTokens: 'required',
httpEndpoint: 'enabled',
httpPutResponseHopLimit: 2,
}
});
```
Reasoning:
- Created the VPC, subnet, and security group resources referenced in the CLI command
- Created an IAM role with SSM and CloudWatch managed policies, and an instance profile to associate it with the EC2 instance, as specified in the CLI command
- Created the EC2 instance with details like instance type, AMI, key pair, network interface config, IAM role, tags, and metadata options specified in CLI
- Used CDK constructs like Vpc, Instance, SecurityGroup, Role, InstanceProfile etc. to define the resources
- Made sure to include all details provided in CLI command in CDK code
AWS Console-to-Code 這功能對於,正在考慮當前操作轉換 IaC 可能會有所幫助。
CloudFormation 和 CDK 都可以提供,還提供了 CLI,如果想研究 CLI 的操作,蠻有用的
不過可能需要仔細檢查提供的程式碼以確保其按預期工作,但這是一個非常有用的功能,極推薦!
Reference