1
2

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 5 years have passed since last update.

シェルスクリプト + Packerで超お手軽AMI作成

Last updated at Posted at 2019-09-30

AnsibleもChefも使わずシェルスクリプトだけでプロビジョニングしてAMIを作成するメモ。

Packerのインストール

ローカルにインストールする。

brew install packer

Packer設定ファイルの作成

ディレクトリ構造

.
├── files
│   ├── main.sh
│   └── nginx.conf
└── myami.json

myami.json

ポイント

  • ローカルの ./files ディレクトリを丸ごとリモートの /tmp/files にコピーしている。
    • ディレクトリ名の末尾にスラッシュをつけるかどうかでコピーの挙動が変わるので注意(詳しくは公式ドキュメントを)
    • コピーされたファイルの所有者はpacker実行時にsshしたユーザー(このサンプルでは ec2-user)になっているので、必要に応じて chmod chown すること。
  • main.shsudo つきで呼び出すことにより、main.shに書いたコマンドは全部 root として実行される。
{
  "builders": [
    {
      "type": "amazon-ebs",
      "ami_name": "MyAMI-{{isotime | clean_ami_name}}",
      "region": "ap-northeast-1",
      "source_ami": "ami-0ff21806645c5e492",
      "instance_type": "t3.micro",
      "vpc_id": "vpc-*********",
      "ssh_username": "ec2-user",
      "security_group_ids": [
        "sg-*****************"
      ],
      "subnet_id": "subnet-**************",
      "associate_public_ip_address": true
    }
  ],
  "provisioners": [
    {
      "type": "file",
      "source": "./files",
      "destination": "/tmp"
    },
    {
      "type": "shell",
      "inline": ["sudo bash /tmp/files/main.sh"]
    }
  ]
}

main.sh

# !/bin/bash

set -e

yum install -y nginx

mv -v /tmp/files/nginx.conf /etc/nginx/nginx.conf
chmod 644 /etc/nginx/nginx.conf
chown root:root /etc/nginx/nginx.conf

systemctl enable nginx

実行

バリデート

packer validate myami.json

実行

packer build myami.json

参考

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?