[アップデート] AWS Console-to-Code (Preview)が使用可能になりました #AWSreInvent

2023.11.27

こんにちは、つくぼし(tsukuboshi0755)です!

AWS Console-to-Code (Preview) というサービスが発表されたので、今回試してみます!

Console-to-Codeとは?

AWSコンソールで行った操作を記録し、サンプルコードを生成するという、IaC導入に役立つサービスです。

現状バージニア北部(us-east-1)のEC2コンソールのみで提供されています。

以下の形式であれば、Console-to-Codeを用いてコード変換が可能なようです。

  • CDK(Java)
  • CDK(Python)
  • CDK(TypeScript)
  • CloudFormation(JSON)
  • CloudFormation(YAML)

またこちらのサービス自体は、無料で使用可能です。

公式ドキュメントは以下の通りです。

Generate code for your console actions using Console-to-Code - Amazon Elastic Compute Cloud

なお2023年11月時点ではパブリックプレビュー版である事にご注意ください。

試してみる

早速本サービスを試してみましょう。

今回は以下の通り事前にコンソール上でEC2インスタンスを作成し、Code-to-Consoleがその操作を記録してコードを生成できるか確認します。

バージニア北部(us-east-1)のEC2コンソールの左ペインを確認すると、以下の通りConsole-to-Codeという機能が追加されているのでクリックします。

すると以下のような画面に飛びます。

下の表には、EC2コンソール上で行った操作が記録されています。

タイプ読み取り専用に切り替える事で取得操作のみ、変異に切り替える事で作成/変更/削除操作のみに絞り込む事ができるようです。

今回は以下のRunInstancesで記録されているEC2インスタンスの作成操作をコードに変換してみます。

まずはCloudFormationに変換してみます。

今回はYAMLを試してみます。

コードに変換したい操作にチェックを入れ、一番右のオレンジ色のラジオボタンをクリックした後、YAMLコードの生成をクリックします。

すると以下のような形で、CloudFormationテンプレート、及び使用する際の補足事項が提供されます!

 Here is the generated CloudFormation YAML:

```yaml
Resources:

  EC2Instance: 
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0230bd60aa48260c6 
      InstanceType: t2.micro
      NetworkInterfaces: 
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          GroupSet:
            - sg-08f0d5fb2d69e3c74
          SubnetId: subnet-066c221b719e5e8bd
      TagSpecifications:
        - ResourceType: instance 
          Tags:
            - Key: Name
              Value: console-to-code-sample
      MetadataOptions:
        HttpTokens: required
        HttpEndpoint: enabled
        HttpPutResponseHopLimit: 2
      PrivateDnsNameOptions:
        HostnameType: ip-name
        EnableResourceNameDnsARecord: false
        EnableResourceNameDnsAAAARecord: false
      ClientToken: c7dea626-edaf-4bdc-8888-7634036a863e
      MinCount: 1
      MaxCount: 1
      
```

Reasoning:
- Created an EC2 instance resource with the provided AMI, instance type, network interface configuration, tags, metadata options, private DNS options, client token and count.
- Used the AWS::EC2::Instance resource type.
- Specified the provided ImageId, InstanceType, NetworkInterfaces, TagSpecifications, MetadataOptions, PrivateDnsNameOptions, ClientToken, MinCount and MaxCount properties.
- The network interface was configured with the provided subnet, security group, public IP setting and device index.
- The tags were specified according to the provided tag specifications.
- The metadata options were configured with the provided HTTP settings. 
- The private DNS options were disabled as specified.
- The client token and count were set as provided.

なおEC2の設定とコード内容を比較した所、コンソールで実施した内容と全く同じ設定を反映しているという訳ではなく、いくつかAWS側が補完している設定もあるようです。

もし提供されたIaCコードを使用する際は、想定通りの内容になっているか確認する事を推奨します。


次にCDKにも変換してみます。

今回はTypeScriptを試してみます。

同じくコードに変換したい操作にチェックを入れ、一番右のオレンジ色のラジオボタンをクリックした後、TypeScriptコードの生成をクリックします。

すると以下のような形で、CDKコード、及び使用する際の補足事項が提供されます!

 Here is the generated CDK code:

```typescript
import * as ec2 from '@aws-cdk/aws-ec2';

const vpc = new ec2.Vpc(this, 'Vpc'); 

const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
  vpc,
});

securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 'allow ssh access');

const subnet = new ec2.Subnet(this, 'Subnet', {
  vpcId: vpc.vpcId,
  availabilityZone: 'us-east-1a',
});

const instance = new ec2.Instance(this, 'Instance', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
  machineImage: ec2.MachineImage.latestAmazonLinux(),
  securityGroup: securityGroup,
  subnet: subnet,
});

instance.addUserData(`
  #!/bin/bash
  yum update -y
  yum install -y httpd
  SYSTEMCTL_SKIP_REDIRECT=true systemctl enable httpd
  SYSTEMCTL_SKIP_REDIRECT=true systemctl start httpd  
`);

instance.instance.addTag('Name', 'console-to-code-sample');

instance.instance.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);

```

Reasoning:
- Created a VPC, security group, and subnet to match what was referenced in the CLI commands
- Used latest Amazon Linux image and t2.micro instance type
- Opened port 22 in security group for SSH access
- Added user data to install httpd and start web server
- Tagged instance with 'Name' tag
- Set removal policy to destroy to match CLI behavior
- Other options like metadata and DNS were not implemented in CDK since they are not commonly used

CDKコードに変換可能な言語は、TypeScript, Python, Javaの3種類です。

よく使う主要言語に対応しているのは嬉しいですね。


さらに地味に嬉しいのが、IaCコードと合わせてCLIも同時に提供される点です。

例えば今回のRunInstancesの場合、IaCコードが生成されると共に、以下のCLIが提供されます。

aws ec2 run-instances --image-id "ami-0230bd60aa48260c6" --instance-type "t2.micro" --network-interfaces '{"SubnetId":"subnet-066c221b719e5e8bd","AssociatePublicIpAddress":true,"DeviceIndex":0,"Groups":["sg-08f0d5fb2d69e3c74"]}' --tag-specifications '{"ResourceType":"instance","Tags":[{"Key":"Name","Value":"console-to-code-sample"}]}' --metadata-options '{"HttpTokens":"required","HttpEndpoint":"enabled","HttpPutResponseHopLimit":2}' --private-dns-name-options '{"HostnameType":"ip-name","EnableResourceNameDnsARecord":false,"EnableResourceNameDnsAAAARecord":false}' --client-token "c7dea626-edaf-4bdc-8888-7634036a863e" --count "1"

IaCコードに変換したい場合だけでなく、CLIで操作したい場合も、本機能は役立ちそうですね。

最後に

今回はAWS Console-to-Code (Preview)を試してみました!

CloudFormationとCDKのどちらも提供可能なので、IaC化を考えている場合は参考になりそうです。

さらにCLIも提供されるため、CLIでの操作を調査したい場合にも役立ちそうですね。

提供されたコードについては想定通りの動作をするか事前に精査する必要がありそうですが、とても便利な機能なのでぜひ一度試してみてはいかがでしょうか。

以上、つくぼし(tsukuboshi0755)でした!