0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PackerでAMI作成時にuser_dataを実行する

Last updated at Posted at 2021-12-15

これはなに

AWSのAMIをPackerで作成する中で、Ansibleではなくuser_dataの実行方法についてのメモです。
Jsonでの記述方法がWeb上には多数ありますが、今回はHLC2で記述します。

ファイル構成

root@user2:~/example-packer# tree .
.
├── build.pkr.hcl
├── scripts
│   └── user_data.txt
├── sources.pkr.hcl
└── variables.pkr.hcl

バージョン

・Packer v1.7.7

ファイル内容

variables.pkr.hcl

variables.pkr.hcl
variable "region" {
  default = "ap-northeast-1"
}

variable "ami_name" {
  default = "作成されるAMIの名前"
}

variable "owners_id" {
  default = "AWSアカウントID"
}

variable "source_ami_name" {
  default = "作成する元となるAMIの名前"
}

sources.pkr.hcl

sources.pkr.hcl
source "amazon-ebs" "server" {
  region        = "${var.region}"
  ami_name      = "${var.ami_name}"
  instance_type = "t2.micro"
  ssh_username  = "ec2-user"
  tags = {
    Name = "${var.ami_name}"
  }

  source_ami_filter {
    owners      = ["${var.owners_id}"]
    most_recent = true

    filters = {
      virtualization-type = "hvm"
      name                = "${var.source_ami_name}"
      root-device-type    = "ebs"
    }
  }
}

build.pkr.hcl
user_dateを記述するファイルはこちらになります。
inline = []の中に実行したいスクリプトを記述していきます。
今回は試しにhttpdのインストールを行います。

build.pkr.hcl
build {
  name = "build_ami"
  sources = [
    "source.amazon-ebs.server"
  ]
    provisioner "shell" {
    inline = [
      "sudo yum update -y",
      "sudo yum install -y httpd",
      "sudo systemctl start httpd",
      "sudo systemctl enable httpd"
    ]
  }
}

実行

root@user2:~/example-packer# packer build .

・最後に、AMIからEC2を起動して期待通りのスクリプトが実行されていれば完了です。
image.png

追記

上記、方法とは別にsources.pkr.hcluser_data_fileを使用することでuser_dataを実行することもできます。

sources.pkr.hcl
source "amazon-ebs" "server" {
  region        = "${var.region}"
  ami_name      = "${var.ami_name}"
  instance_type = "t2.micro"
  ssh_username  = "ec2-user"
  user_data_file= "./scripts/user_data.txt"
  tags = {
    Name = "${var.ami_name}"
  }

  source_ami_filter {
    owners      = ["${var.owners_id}"]
    most_recent = true

    filters = {
      virtualization-type = "hvm"
      name                = "${var.source_ami_name}"
      root-device-type    = "ebs"
    }
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?