Closed8

CDKで作成したWindows EC2が意図せず再作成されてしまった

hirenhiren

使っていたのはこれ

new ec2.Instance(this, 'EC2', {
  machineImage: new ec2.WindowsImage(ec2.WindowsVersion.WINDOWS_SERVER_2022_JAPANESE_FULL_BASE),
});
hirenhiren

実はドキュメントにはちゃんと注意喚起が記載されていた......

このマシン イメージは、デプロイメントごとに最新バージョンに自動的に更新されます。新しいバージョンのイメージが利用可能になると、インスタンスが置き換えられることに注意してください。このイメージを使用している場合は、インスタンスにステートフル情報を保存しないでください。

https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.WindowsImage.html

hirenhiren

試しにやってみたけどこれもcdk.context.jsonは作られず、WindowsImageと一緒だった

new ec2.Instance(this, 'EC2', {
  machineImage: ec2.MachineImage.latestWindows(ec2.WindowsVersion.WINDOWS_SERVER_2019_JAPANESE_FULL_BASE),
});
hirenhiren

どっちでもいいみたい(出力される結果は同じ)

LookupMachineImage※Example
new ec2.Instance(this, 'EC2', {
      machineImage: new ec2.LookupMachineImage({
        name: 'name',
      
        // the properties below are optional
        filters: {
          filtersKey: ['filters'],
        },
        owners: ['owners'],
        windows: false,
      }),
});
MachineImage.lookup()
new ec2.Instance(this, 'EC2', {
      machineImage: ec2.MachineImage.lookup({
        // AMI名
        // 日本語版 Windows AMI 名では末尾に付けられている日付部分を、ワイルドカードで指定
        // name: 'Windows_Server-2019-Japanese-Full-Base-*',
        name: `${ec2.WindowsVersion.WINDOWS_SERVER_2019_JAPANESE_FULL_BASE}-*`,
        filters: {
          'image-type': ['machine'],
          state: ['available'],
        },
        // 日本語版 Windows AMI の場合、OwnerAlias:amazon, owner:801119661308
        owners: ['amazon'],
        windows: true,
      }),
});

filtersで指定できるのは以下ドキュメントのFilter.Nの項目
https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/APIReference/API_DescribeImages.html

hirenhiren

cdk.context.jsonが出来た!

cdk.context.json
{
  "availability-zones:account=123456789012:region=ap-northeast-1": [
    "ap-northeast-1a",
    "ap-northeast-1c",
    "ap-northeast-1d"
  ],
  "ami:account=123456789012:filters.image-type.0=machine:filters.name.0=Windows_Server-2019-Japanese-Full-Base-*:filters.platform.0=windows:filters.state.0=available:owners.0=amazon:region=ap-northeast-1": "ami-0934bcffe190197e1"
}

このスクラップは2025/02/12にクローズされました