Rocky Linux 8 の AMI

Rocky Linux 8のEC2インスタンスが欲しいが、それなりに古いAMIであるため初回のyum updateの実行に時間がかかる。
そこでyum update済みのAMIを作成してみる。

Packer

Packerのインストール

Install Packer を参考にPackerをインストールする。

macOSの場合はHomebrewでインストールできる。

$ brew install hashicorp/tap/packer

VPCとサブネットの作成

PackerでAMIを作成するための準備としてVPCとそのVPCに紐づいたサブネットを作成しておく必要がある。

Packerの設定ファイル

以下のPackerの設定ファイルを作成する。

packer {
  required_plugins {
    amazon = {
      version = ">= 1.2.7"
      source  = "github.com/hashicorp/amazon"
    }
  }
}

source "amazon-ebs" "example" {
  ami_name      = "packer-example-{{timestamp}}"
  instance_type = "t2.micro"
  region        = "ap-northeast-1"
  vpc_id        = "vpc-xxxxxxxxxxxxxxxxx"
  subnet_id     = "subnet-xxxxxxxxxxxxxxxxx"
  source_ami    = "ami-0ddb05e945a674cf5"
  ssh_username  = "rocky"
}

build {
  name    = "example-builder"
  sources = ["source.amazon-ebs.example"]

  provisioner "shell" {
    inline = [
      "sudo yum -y update"
    ]
  }
}

source_amiにはRocky Linux 8のAMIであるami-0ddb05e945a674cf5を指定する。
AMI IDを調べるには【AWS】マーケットプレイスのAMIのAMI IDを調べる方法 を参照。 このAMIのデフォルトユーザはrockyであるためssh_usernameにはrockyを指定する。

また実行したいyum updateコマンドはbuildブロックのshellで実行する。

Packerの実行

packerコマンドで事項する。

$ packer build web-server.pkr.hcl
...
==> Wait completed after 16 minutes 17 seconds

==> Builds finished. The artifacts of successful builds are:
--> example-builder.amazon-ebs.example: AMIs were created:
ap-northeast-1: ami-xxxxxxxxxxxxxxxxx

実行が成功するとAMIが作成される。

AMI