ちょっと話題の記事

VagrantでAmazon Linux 2を実行する

2017.12.20

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

ども、大瀧です。
先日発表されたAmazon Linux 2はオンプレミス向けの仮想マシンデータが提供されています。ところが、自分が手元で一番使う仮想マシン環境であるVagrantが含まれていなかったので、公開されているVirtualBoxの仮想マシンデータをVagrantで使うための手順をご紹介してみたいと思います。

更新履歴 : 2018/01/05 実行時の不具合を解消するパッチについて注意書きを追記

動作確認環境

  • OS: macOS High Sierra
  • Virutalbox: バージョン 5.1.30 r118389
  • Vagrant: バージョン 1.9.8(ちょっと古かった(^^;)
  • Amazon Linux 2: LTS Candidate 2017.12.0.20171212.2

1. ISOイメージファイルの作成

オンプレミス向けAmazon Linuxでは、仮想マシンの初期設定としてCDイメージをマウントしてCloud-initの設定ファイルを読み込ませることができます。公開されているREADMEを参考に、以下のファイルを含むISOイメージファイルを作成します。

  • config/meta-data: ホスト名の指定。今回はcloudimgにしました
  • config/user-data: Vagrantで使用するvagrantユーザーの設定。パスワードなしsudoとGitHubで公開されているセキュアではないSSH公開鍵をセットします。
$ mkdir config
$ { echo local-hostname: cloudimg; } > config/meta-data
$ vim config/user-data
#cloud-config
users:
  - name: vagrant
    groups: sudo
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    ssh-authorized-keys:
      - ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key
    lock_passwd: true
$ hdiutil makehybrid -o seed.iso -hfs -joliet -iso -default-volume-name cidata config/

これでISOイメージファイルseed.isoを作成しました。

2. VirtualBox仮想マシンの作成

続いて、Vagrant Box(Vagrantの仮想マシンイメージ)の元となるVirtualBoxの仮想マシンを作成します。VirtualBoxの[新規]から、以下の設定で仮想マシンを作成します。

  • 名前: 任意のマシン名で構いませんが、後ほどvagrant packageコマンドで指定するタイミングがあります。今回は「Amazon Linux 2」としました
  • オペレーティングシステム: 「Linux 2.6/3.x/4.x(64-bit)」を選択
  • ハードディスク: 公開されているイメージデータの拡張子.vdiファイルをダウンロードし、指定します
  • 光学ドライブ: 先ほど作成したseed.isoを指定
  • ネットワーク: アダプター1の[高度]からポートフォワーディングで[ホストポート]に任意のポート(今回は8022)、ゲストポートに22を設定

仮想マシンを起動したら、以下の様に公開されているセキュアではないSSH秘密鍵をダウンロード、SSH接続で使用します。

$ wget https://raw.githubusercontent.com/hashicorp/vagrant/master/keys/vagrant -O vagrant-private.key
  :
$ chmod 600 vagrant-private.key
$ ssh -i vagrant-private.key -p 8022 vagrant@localhost

接続したらseed.isoファイルをejectしつつ、VirtualBox Guest Additionsをインストールするために必要な開発ツールをインストールしておきます。

[vagrant@cloudimg ~]$ sudo eject
[vagrant@cloudimg ~]$ sudo yum groupinstall -y 'Development Tools'

仮想マシンのウィンドウをフォーカスしつつ、メニューから[Devices] - [Insert Guest Additions CD image...]をクリックしてVirtualBox Guest Additionsのイメージを光学ドライブにセットします。

以下のコマンドでVirtualBox Guest Additionsをインストールします。

[vagrant@cloudimg ~]$ sudo mount /dev/cdrom /mnt
mount: /dev/sr0 is write-protected, mounting read-only
[vagrant@cloudimg ~]$ sudo /mnt/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.1.30 Guest Additions for Linux...........
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
vboxadd.sh: Starting the VirtualBox Guest Additions.

Could not find the X.Org or XFree86 Window System, skipping.
[vagrant@cloudimg ~]$ sudo eject

あとは、Vagrantの共有ディレクトリとして利用するマウントポイント/vagrantを作成しておきましょう。

[vagrant@cloudimg ~]$ sudo mkdir /vagrant
[vagrant@cloudimg ~]$ exit
$

これで仮想マシンの設定はOKです。VirtualBoxの仮想マシン一覧ウィンドウから仮想マシンを選択し右クリック、[閉じる] - [ACPIシャットダウン]で仮想マシンをシャットダウンします。

3. Vagrantの設定

続いて、VirtualBoxの仮想マシンをVagrantのイメージであるVagrant Boxにインポートします。

$ vagrant package --base 'Amazon Linux 2'
==> Amazon Linux 2 のクローン: Clearing any previously set forwarded ports...
==> Amazon Linux 2 のクローン: Exporting VM...
==> Amazon Linux 2 のクローン: Compressing package to: /Users/ryuta/Desktop/amazonlinux2/package.box
$ vagrant box add --name amazonlinux2rc package.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'amazonlinux2rc' (v0) for provider:
    box: Unpacking necessary files from: file:///Users/ryuta/Desktop/amazonlinux2/package.box
==> box: Successfully added box 'amazonlinux2rc' (v0) for 'virtualbox'!
$

これでOKです。

動作確認

では、Vagrantfileを作成して動作を確認してみます。まずはファイルを生成しましょう。

$ mkdir vagrant
$ cd vagrant
$ vagrant init amazonlinux2rc
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
$

一点だけポイントがあって、Amazon Linux 2だとVagrantがゲストOSの認識に失敗し以下のようなエラーメッセージがvagrant upのログに表示されてしまいます。

The guest operating system of the machine could not be detected!
Vagrant requires this knowledge to perform specific tasks such
as mounting shared folders and configuring networks. Please add
the ability to detect this guest operating system to Vagrant
by creating a plugin or reporting a bug.

このエラーを抑止するために、以下のようにVagrantfileの仮想マシン設定でゲストOSを明示してあげます。

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = "amazonlinux2rc"
  config.vm.guest = :linux

上記不具合を解消するパッチのPull Requestが挙がっているので、程なく解消するかもしれません。
Modify the matching pattern of guest os for amazon linux by wink-y · Pull Request #9307 · hashicorp/vagrant

では、起動してみます。

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'amazonlinux2rc'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1513690533869_33596
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection reset. Retrying...
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/ryuta/Desktop/amazonlinux2/vagrant
$

起動してきました。SSHで接続してみると...

$ vagrant ssh
Last login: Tue Dec 19 14:02:25 2017 from gateway

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
[vagrant@cloudimg ~]$ ls /vagrant
Vagrantfile

正常に接続でき、共有ディレクトリも動作していることが確認出来ました!

まとめ

VagrantでAmazon Linux 2を実行する様子をご紹介しました。これで手元のマシンでのAmazon Linux 2の検証が捗ること間違い無しです! なお、Amazon Linux 2はまだRC(リリース候補)の段階なので、正式リリース(GA)後は様子が変わるかもしれません。また、ChefやPuppetなどは元の仮想マシンにインストールしていないので、Vagrantfile内でプロビジョニング周りの機能を使う場合はそれらを事前に入れておく必要がありそうです。

参考URL