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

VagrantでVirtualBoxにVMを立ち上げる

Posted at

こんにちは。
株式会社クラスアクト インフラストラクチャ事業部の大塚です。

以前Kubuntu(Ubuntu)24.04にVirtualBoxをインストールして、最後の方に余談でVBoxManageコマンドを使ってVirtualBox上のVMを起動したり、停止したりしてみました。

この記事はその派生として、Vagrantを使って新規VMをコマンドベースでVirtualBox上にデプロイしていきたいと思います。

環境イメージ

既にVirtualBoxを使ってVMを立ち上げることが出来るKubuntuの環境に、Vagrantの環境を作り、VagrantでVirtualBoxのVMを管理出来るようにしていきます。
Kubuntu-ページ2.drawio.png

Vagrantを使わないと・・・

Vagrantを使わなくてもVMのOSとかVDIとかをコマンドベースで作ることは可能です。
以下のようなコマンドで作成・起動することが出来ます。

VMの名前やOSの指定
shota@shota-20f5a2v5jp:~$ VBoxManage createvm --name "ubuntu01" --ostype "Ubuntu_64" --register
Virtual machine 'ubuntu01' is created and registered.
UUID: 63265b8f-d72c-4af8-85e7-82ca4b54291a
Settings file: '/home/shota/VirtualBox VMs/ubuntu01/ubuntu01.vbox'

指名がちゃんと認識されていることを確認
shota@shota-20f5a2v5jp:~$ VBoxManage list vms
"kali-linux-2024.4-virtualbox-amd64" {c9d5399e-9c50-4a58-8f32-7ccdaa832e5d}
"ubuntu01" {63265b8f-d72c-4af8-85e7-82ca4b54291a}

VMのメモリ設定
shota@shota-20f5a2v5jp:~$ VBoxManage modifyvm "ubuntu01" --memory 2048

VMのCPU設定
shota@shota-20f5a2v5jp:~$ VBoxManage modifyvm "ubuntu01" --cpus 2

VMのvramの設定
shota@shota-20f5a2v5jp:~$ VBoxManage modifyvm "ubuntu01" --vram 128

仮想NICに当てはめる物理NICの確認
shota@shota-20f5a2v5jp:~$ VBoxManage list bridgedifs
Name:            wlp4s0
GUID:            f0000000-def6-4b62-8000-f48c50525c88
DHCP:            Disabled
IPAddress:       192.168.0.111
NetworkMask:     255.255.255.0
IPV6Address:     2407:c800:2f21:d7c::2
IPV6NetworkMaskPrefixLength: 128
HardwareAddress: f4:8c:50:52:5c:88
MediumType:      Ethernet
Wireless:        Yes
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-wlp4s0

Name:            enp0s31f6
GUID:            f0000000-3f38-466e-8000-c85b76aefc4d
DHCP:            Disabled
IPAddress:       0.0.0.0
NetworkMask:     0.0.0.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: c8:5b:76:ae:fc:4d
MediumType:      Ethernet
Wireless:        No
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-enp0s31f6

Name:            docker0
GUID:            f0000000-8c10-4ef3-8000-024263e208fb
DHCP:            Disabled
IPAddress:       172.17.0.1
NetworkMask:     255.255.0.0
IPV6Address:
IPV6NetworkMaskPrefixLength: 0
HardwareAddress: 02:42:63:e2:08:fb
MediumType:      Ethernet
Wireless:        No
Status:          Up
VBoxNetworkName: HostInterfaceNetworking-docker0

仮想NICの設定
shota@shota-20f5a2v5jp:~$ VBoxManage modifyvm "ubuntu01" --nic1 bridged --bridgeadapter1 "wlp4s0"

仮想ディスクの設定
shota@shota-20f5a2v5jp:~$ VBoxManage createhd --filename "/home/shota/VirtualBox VMs/ubuntu01/ubuntu01.vdi" --size 20000
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
Medium created. UUID: edf7b0a1-2e17-44de-87e6-5fe80cef5d34

ストレージコントローラの設定
shota@shota-20f5a2v5jp:~$ VBoxManage storagectl "ubuntu01" --name "ubuntu01_SATA_Controller" --add sata --controller IntelAhci

仮想ディスクとストレージコントローラの紐づけ
shota@shota-20f5a2v5jp:~$ VBoxManage storageattach "ubuntu01" --storagectl "ubuntu01_SATA_Controller" --port 0 --device 0 --type hdd --medium "/home/shota/VirtualBox VMs/ubuntu01/ubuntu01.vdi"

ISOをVMに紐づけ
shota@shota-20f5a2v5jp:~$ VBoxManage storageattach "ubuntu01" --storagectl "ubuntu01_SATA_Controller" --port 1 --device 0 --type dvddrive --medium "/home/shota/ドキュメント/ubuntu-24.04.1-live-server-amd64.iso"

設定したVMの起動
shota@shota-20f5a2v5jp:~$ VBoxManage startvm "ubuntu01" --type headless
Waiting for VM "ubuntu01" to power on...
VM "ubuntu01" has been successfully started.

起動するとLinuxの初期設定画面が確認できます。今回はUbuntuで試しているので、Ubuntuの初期設定画面が表示されていますね。
ここまでは良いのですが、VirtualBoxのコマンドでは、この初期設定をコマンドベースで設定することが出来ません。
一度や二度であればこの設定を入れるのも楽しいのですが、インフラエンジニアとして生きているとこの設定は何度も何度もなんどもなんども~(以下ループ)するわけでここも自動化したいですよね。
Vagrantを使って、VM立ち上げをより楽にしていきましょう。
image05.png

Vagrant環境構築と実行

以下の公式サイトにOSごとの設定手順が記載されていますので、コピペして実行していきましょう。

今回はKubuntu24.04(≒Ubuntu24.04)になりますので、以下のコマンドを実行しました。
インストール後、vagrantコマンドを実行して、バージョンが表示されていればOKです。

root@shota-20f5a2v5jp:~# wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
root@shota-20f5a2v5jp:~# echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
root@shota-20f5a2v5jp:~# apt update && apt install vagrant
root@shota-20f5a2v5jp:~# vagrant --version
Vagrant 2.4.3

インストールが上手くいかなかったら以下のコマンドを実行したうえで再度インストールしてみてください。

apt --fix-broken install

VagrantでVMを起動するにあたり、VagrantのProjectディレクトリが必要になりますので作成しました。
今回はvagrant_ubuntu01というディレクトリ名にしました。

shota@shota-20f5a2v5jp:~$ ls
'VirtualBox VMs'   snap                ダウンロード   デスクトップ   ビデオ     ミュージック
 dev               thinclient_drives   テンプレート   ドキュメント   ピクチャ   公開
shota@shota-20f5a2v5jp:~$ cd ドキュメント
shota@shota-20f5a2v5jp:~/ドキュメント$ ls
kali-linux-2024.4-installer-amd64.iso  kali-linux-2024.4-virtualbox-amd64  ubuntu-24.04.1-live-server-amd64.iso
shota@shota-20f5a2v5jp:~/ドキュメント$ mkdir vagrant_ubuntu01
shota@shota-20f5a2v5jp:~/ドキュメント$ cd vagrant_ubuntu01/

Project内で初期化を行っていきます。
vagrant initコマンドを実行するとVagrantfileというファイルが作成されていきます。
このファイルにVMの設定を入れ込んでいき、VM初期設定を自動化していくことになります。

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ vagrant init
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.
shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ ls
Vagrantfile
shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ cp -p Vagrantfile Vagrantfile.bak

Vagrantで使用するboxというものを確認していきます。
以下Vagrant Cloudというサイトでどんなものがダウンロードできるか確認できます。

image06.png

DockerでいうところのDocker HubでDocker imageを見れるかと思いますが、それに近いと思って頂くとイメージしやすいんじゃないでしょうか?

Kubuntu-ページ3.drawio.png

今回はUbuntuのboxを使ってみます。
Ubuntuのバージョンが最も新しくて、かつ公式っぽいubuntu/jammy64を使ってみることにしました。
image07.png

以下のコマンドを実行してローカルにboxをインストールしていきます。

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ vagrant box add ubuntu/jammy64
==> box: Loading metadata for box 'ubuntu/jammy64'
    box: URL: https://vagrantcloud.com/api/v2/vagrant/ubuntu/jammy64
==> box: Adding box 'ubuntu/jammy64' (v20241002.0.0) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/ubuntu/boxes/jammy64/versions/20241002.0.0/providers/virtualbox/unknown/vagrant.box
==> box: Successfully added box 'ubuntu/jammy64' (v20241002.0.0) for 'virtualbox'!

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ vagrant box list
ubuntu/jammy64 (virtualbox, 20241002.0.0)

次にVagrantfileの内容を詰めていきます。
今回は以下のような設定にしてみました。
先程ダウンロードしたboxを指定し、メモリとCPUの設定を行い、IPアドレスやDNSを指定し、hostnameをwordpressとしました。
VagrantでVMを起動するとProject名(ディレクトリ名)+ホスト名でVM名が決まるようです。

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ cat Vagrantfile
Vagrant.configure("2") do |config|
  # 使用するボックス(Ubuntu 22.04)
  config.vm.box = "ubuntu/jammy64"

  # 仮想マシンのリソース設定
  config.vm.provider "virtualbox" do |vb|
    vb.memory = "2048"  # メモリ設定
    vb.cpus = 2         # CPU設定
  end

  # ネットワーク設定(ブリッジ接続)とIPアドレスの固定化
  config.vm.network "public_network", bridge: "wlp4s0", ip: "192.168.0.113"

  # 仮想マシンのホスト名を設定
  config.vm.hostname = "wordpress"

  # 仮想マシン名の設定
  config.vm.define "wordpress" do |wordpress|
    # 仮想マシンを起動した際に実行するシェルスクリプト
    wordpress.vm.provision "shell", inline: <<-SHELL
      sudo apt-get update
      echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf
      echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolv.conf
    SHELL
  end
end

vagrant upコマンドを実行することでVagrantfileをベースにVMがデプロイされていきます。
VBoxManage list vmsコマンドを実行するとVagrantでVMがデプロイされていることがわかります。

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ vagrant up

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ VBoxManage list vms
"kali-linux-2024.4-virtualbox-amd64" {c9d5399e-9c50-4a58-8f32-7ccdaa832e5d}
"vagrant_ubuntu01_wordpress_1737192557121_16068" {f207061e-b3cf-4e81-8d5c-4d67de561495}

VirtualBoxのGUIからも確認できます。
image.png

デプロイされたVMにSSHするためにはvagrant sshコマンドで可能です。
SSH後、hostnameやIPアドレスを確認してみるとVagrantfileに記載の通り設定されていることがわかると思います。

shota@shota-20f5a2v5jp:~/ドキュメント/vagrant_ubuntu01$ vagrant ssh
Welcome to Ubuntu 22.04.5 LTS (GNU/Linux 5.15.0-130-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/pro

 System information as of Sat Jan 18 09:30:48 UTC 2025

  System load:             0.79
  Usage of /:              4.3% of 38.70GB
  Memory usage:            11%
  Swap usage:              0%
  Processes:               109
  Users logged in:         0
  IPv4 address for enp0s3: 10.0.2.15
  IPv6 address for enp0s3: fd00::e5:4ff:fe58:6a0c


Expanded Security Maintenance for Applications is not enabled.

1 update can be applied immediately.
1 of these updates is a standard security update.
To see these additional updates run: apt list --upgradable

Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status

New release '24.04.1 LTS' available.
Run 'do-release-upgrade' to upgrade to it.


vagrant@wordpress:~$ hostname
wordpress
vagrant@wordpress:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 02:e5:04:58:6a:0c brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 metric 100 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86348sec preferred_lft 86348sec
    inet6 fd00::e5:4ff:fe58:6a0c/64 scope global dynamic mngtmpaddr noprefixroute
       valid_lft 86348sec preferred_lft 14348sec
    inet6 fe80::e5:4ff:fe58:6a0c/64 scope link
       valid_lft forever preferred_lft forever
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:e9:02:66 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.113/24 brd 192.168.0.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 2407:c800:2f21:d7c::15/128 scope global dynamic noprefixroute
       valid_lft 604750sec preferred_lft 604750sec
    inet6 2407:c800:2f21:d7c:a00:27ff:fee9:266/64 scope global dynamic mngtmpaddr noprefixroute
       valid_lft 86386sec preferred_lft 86386sec
    inet6 fe80::a00:27ff:fee9:266/64 scope link
       valid_lft forever preferred_lft forever

ちなみに、vagrant関連の初歩的なコマンドを以下にメモっておきます。

Vagrantで管理しているVM一覧
vagrant global-status
id       name      provider   state    directory
---------------------------------------------------------------------------
8e7fb45  wordpress virtualbox poweroff /home/shota/ドキュメント/vagrant_ubuntu01

Vagrantで管理しているVM一覧を更新するコマンド(消したはずなのにglobal-statusで依然出てくるVMがある場合に使うと良い)
 vagrant global-status --prune

VagrantでデプロイしたVMを停止するコマンド(≒shutdown)
vagrant halt wordpress

稼働中のVMにVagrantfileの変更を反映させるコマンド
vagrant reload

Vagrantで管理しているVMを削除する
vagrant destroy -f

SSH接続に必要な設定情報を表示するコマンド
vagrant ssh-config wordpress
Host wordpress
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /home/shota/ドキュメント/vagrant_ubuntu01/.vagrant/machines/wordpress/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL
  PubkeyAcceptedKeyTypes +ssh-rsa
  HostKeyAlgorithms +ssh-rsa
1
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
1
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?