Create vagrant box from CentOS 7 VirtualBox

This time I will show you, how to create a basic Vagrant box from a CentOS 7 VirtualBox. Caution, use only for educational purposes and not for productive environments!

Preparation

Network configuration

On VirtualBox select mode “NAT” or “Bridged”.

$ vi /etc /sysconfig/network-scripts/ifcfg-enp0s3
$ service network restart

Install virtualbox guest additions 

# Update
$ yum update -y

# Install development tools
$ yum groupinstall -y "Development Tools"

# restart vm
$ reboot

# insert cd
# Devices -> Install Guest Additions

# mount cd
$ mount /dev/cdrom /mnt

# start guest additions installation
$ sh /mnt/VBoxLinuxAdditions.run --nox11

Prepare Vagrant SSH access

# Edit sudoers file to disable requiretty
$ visudo

# Defaults    requiretty

# add user vagrant 
$ useradd vagrant

# set password for user vagrant (vagrant)
$ passwd vagrant

# create vagrant sudoers file 
$ visudo -f /etc /sudoers.d/vagrant

vagrant ALL=(ALL) NOPASSWD:ALL

# change to user vagrant
$ su - vagrant

# create ssh folder with access rights
$ mkdir .ssh && chmod 0700 .ssh && cd .ssh

# create authorized_keys file
$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key" > authorized_keys

# set access rights for authorized_keys file
$ chmod 0600 authorized_keys

# clear history and switch back to root user
$ history -c && exit

# clear history and shutdown
$ history -c && shutdown -h 0

Create Vagrant box

# create new folder for Vagrant project and change into VM folder
$ mkdir ~/VagrantProject && cd ~/VirtualBox\ VMs/

# create base box from VM
$ vagrant package --base CentOS7 --output ~/VagrantProject/CentOS7.box

# change back to Vagrant project folder
$ cd ~/VagrantProject

# add box
$ vagrant box add lupin/centos7 CentOS7.box

# check vagrant boxes
$ vagrant box list

Create project and start with work

# create project
$ vagrant init lupin/centos7

# edit vagrantfile 
$ vim Vagrantfile

  config.vm.provision "shell", inline: <<-SHELL
     sudo yum update -y
     sudo yum install -y vim tree
  SHELL

# creates and configures guest machine 
$ vagrant up

# SSH into a running Vagrant machine
$ vagrant ssh

# ... do your stuff ...

# stop Vagrant machine
$ vagrant halt