Server Management in Linux with Vagrant

Server Management in Linux with Vagrant | First, we will be setting up httpd service on CentOS and we will deploy some HTML templates. This is a very basic website. A ready-built website will be downloaded from the internet and run it on a CentOS operating system.

Next, we will be using the Ubuntu operating system and we will set up a LAMP stack. Its long form is Linux, Apache, MySQL, and PHP. There are many application that runs on LAMP stack. So, we’ll set up an Ubuntu VM, set up the LAMP stack on that, and deploy the WordPress template. WordPress is a very popular blogging application that you can run on your Linux machines.

We will be doing all these manually first. And then we are going to automate these setups by using vagrant provisioning. So, in the end, we will have two vagrant files, one to set up HTML templates automatically, and the other to set up WordPress templates automatically.

Table of Contents


Simple Website on CentOS

We want to set up a website on CentOS and there are ready-made templates available on the internet, we can use them.

$ mkdir /c/install/vagrant-vms/finance
$ cd /c/install/vagrant-vms/finance
$ vagrant box list
$ vagrant init eurolinux-vagrant/centos-stream-9
$ nano Vagrantfile

It will create a Vagrantfile. Let us change the public IP by editing the Vagrantfile using any text editor.

# Change IP
config.vm.network "private_network", ip: "192.168.56.99"
# Enable Public Network
config.vm.network "public_network"
# RAM Config
config.vm.provider "virtualbox" do |vb|
   vb.memory = "1024"
end

Start the vagrant, SSH it, and log in as root user.

$ vagrant up
$ vagrant ssh
$ sudo -i
# cat /etc/os-release
# yum install httpd wget vim unzip zip -y
# systemctl start httpd
# systemctl status httpd
# systemctl enable httpd
# ip addr show
# hostname -i

We had configured the IP 192.168.56.99. From the host machine, open the browser and go to the IP address 192.168.56.99, it will show the default HTTP server test page. On the browser, we can read:- “For systems using the Apache HTTP Server: You may now add content to the directory /var/www/html/. Note that until you do so, people visiting your website will see this page and not your content.

# cd /var/www/html/
# ls
# vim index.html

In the file write some welcome message, save and close.

Welcome to KnowProgram.

Whenever we change something in the service, we have to restart/reload the httpd service.

# systemctl restart httpd

Refresh the browser http://192.168.56.99/ and you will get the latest modified content.

Now let us download the template file and use it as content/template for the website.

# cd /tmp/
# wget https://www.tooplate.com/zip-templates/2135_mini_finance.zip
# ls
# unzip 2135_mini_finance.zip
# cd 2135_mini_finance/
# ls
# cp -r * /var/www/html/
cp: overwrite '/var/www/html/index.html'? y

# ls /var/www/html/
# systemctl restart httpd
# systemctl status httpd

The firewall should be in stop mode.

# systemctl status firewalld
# systemctl stop firewalld
# systemctl disable firewalld

Now in the browser refresh http://192.168.56.99/

Ubuntu VM with LAMP Stack

Let us set up Ubuntu VM with LAMP Stack (Apache2, MySQL, and PHP) and deploy a WordPress template on it. We will follow these:- steps to install and configure WordPress on Ubuntu.

We will use Ubuntu 20 for the VM box:-

$ mkdir /c/install/vagrant-vms/wordpress
$ cd /c/install/vagrant-vms/wordpress
$ vagrant init ubuntu/focal64

It will create a Vagrantfile. Let us change the public IP by editing the Vagrantfile using any text editor. We will need around 1.5 GB of RAM. If you don’t have that many resources you can keep it one GB also but one and a half GB will be good.

# Change IP
config.vm.network "private_network", ip: "192.168.56.26"
# Enable Public Network
config.vm.network "public_network"
# RAM Config
config.vm.provider "virtualbox" do |vb|
   vb.memory = "1600"
end

Start the vagrant, SSH it, and log in as root user.

$ vagrant up
$ vagrant ssh
$ sudo -i
# cat /etc/os-release

Let us begin with the installation of dependencies (PHP and Apache):-

sudo apt update
sudo apt install apache2 \
                 ghostscript \
                 libapache2-mod-php \
                 mysql-server \
                 php \
                 php-bcmath \
                 php-curl \
                 php-imagick \
                 php-intl \
                 php-json \
                 php-mbstring \
                 php-mysql \
                 php-xml \
                 php-zip -y

Install WordPress:- Create the installation directory and download the file from WordPress.org.

sudo mkdir -p /srv/www
sudo chown www-data: /srv/www
curl https://wordpress.org/latest.tar.gz | sudo -u www-data tar zx -C /srv/www

The last command downloads the latest version of WordPress and extracts it directly into the /srv/www directory as the www-data user. This ensures that the extracted files have the correct ownership.

Verify the download:-

ls -ld /srv/www/
ls -l /srv/www/
ls -l /srv/www/wordpress/

Configure Apache for WordPress. Open the wordpress.conf file in the VIM text editor:-

vi /etc/apache2/sites-available/wordpress.conf

Put the following content in the file:-

<VirtualHost *:80>
    DocumentRoot /srv/www/wordpress
    <Directory /srv/www/wordpress>
        Options FollowSymLinks
        AllowOverride Limit Options FileInfo
        DirectoryIndex index.php
        Require all granted
    </Directory>
    <Directory /srv/www/wordpress/wp-content>
        Options FollowSymLinks
        Require all granted
    </Directory>
</VirtualHost>

Enable the site, enable URL rewriting, and disable the default “It Works” site:

sudo a2ensite wordpress
sudo a2enmod rewrite
sudo a2dissite 000-default
sudo service apache2 reload
ls -l /etc/apache2/sites-enabled/
ls -l /etc/apache2/sites-available/

Now let us begin with MySQL database configuration:-

sudo mysql -u root

It will open the MySQL prompt as the root user. Type below MySQL commands:-

CREATE DATABASE wordpress;
show databases;
CREATE USER wordpress@localhost IDENTIFIED BY 'root';
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER ON wordpress.* TO wordpress@localhost;
FLUSH PRIVILEGES;
quit

Enable MySQL with:-

sudo service mysql start
sudo service mysql status

Configure WordPress to connect to the database:-

cat /srv/www/wordpress/wp-config.php
sudo -u www-data cp /srv/www/wordpress/wp-config-sample.php /srv/www/wordpress/wp-config.php
sudo -u www-data sed -i 's/database_name_here/wordpress/' /srv/www/wordpress/wp-config.php
sudo -u www-data sed -i 's/username_here/wordpress/' /srv/www/wordpress/wp-config.php
sudo -u www-data sed -i 's/password_here/root/' /srv/www/wordpress/wp-config.php
cat /srv/www/wordpress/wp-config.php

Finally, in a terminal session open the configuration file in nano/vi:

sudo -u www-data nano /srv/www/wordpress/wp-config.php

Find the following:

define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );

Delete those lines (ctrl+k will delete a line each time you press the sequence). Then replace it with the content of https://api.wordpress.org/secret-key/1.1/salt/. (This address is a randomiser that returns completely random keys each time it is opened.) This step is important to ensure that your site is not vulnerable to “known secrets” attacks.

Save and close the configuration file by typing ctrl+x followed by y then enter.

Find the IP address of the guest machine, we had configured 192.168.56.26 in the Vagrantfile.

ip addr show

Open this IP address in the host browser, and now we should see the WordPress setup steps. After the setup, log into the WordPress site.

WordPress Installation

Clean up:- exit from the VM and destroy the vagrant.

exit
vagrant destroy --force
vagrant global-status --prune

Automating Simple Website on CentOS

We did the setup of a website on CentOS, and we set up the WordPress blog on Ubuntu. Now we will be doing all this automatically, we will be writing a vagrant file that can provision the website automatically, and then we will do the same for the WordPress template.

Go to the folder where the finance project is located, and create a copy of it. Rename the copied folder as financeIAC, and delete the ./vagrant folder within it. Edit the vagrantFile.

# Change IP
config.vm.network "private_network", ip: "192.168.56.28"
# Enable Public Network
config.vm.network "public_network"
# RAM Config
config.vm.provider "virtualbox" do |vb|
   vb.memory = "1024"
end

Now add all the required commands to the Vagrant file:-

config.vm.provision "shell", inline: <<-SHELL
  # Install necessary packages
  yum install httpd wget vim unzip zip -y

  # Start the Apache HTTP server
  systemctl start httpd

  # Enable Apache to start on boot
  systemctl enable httpd

  # Create a temporary directory for the finance project
  mkdir -p /tmp/finance

  # Change to the temporary directory
  cd /tmp/finance

  # Download the finance template from Tooplate
  wget https://www.tooplate.com/zip-templates/2135_mini_finance.zip

  # Unzip the downloaded template file, overwrite if necessary
  unzip -o 2135_mini_finance.zip

  # Move the contents of the template to the Apache web root directory
  cp -r 2135_mini_finance/* /var/www/html/

  # Restart the Apache HTTP server to apply changes
  systemctl restart httpd

  # Change back to the /tmp directory
  cd /tmp/

  # Remove the temporary finance directory
  rm -rf /tmp/finance
SHELL

Explanation:

  1. yum install httpd wget vim unzip zip -y: Installs the packages httpd (Apache HTTP server), wget (command-line file downloader), vim (text editor), unzip (tool to extract compressed files), and zip (tool to compress files). -y: Automatically answers “yes” to all prompts.
  2. systemctl start httpd: Starts the Apache HTTP server.
  3. systemctl enable httpd: Enables Apache to start automatically at boot.
  4. mkdir -p /tmp/finance: Creates the /tmp/finance directory if it does not exist. The -p option ensures that parent directories are also created as needed.
  5. cd /tmp/finance: Changes the current directory to /tmp/finance.
  6. wget https://www.tooplate.com/zip-templates/2135_mini_finance.zip: Download the finance template zip file from the specified URL.
  7. unzip -o 2135_mini_finance.zip: Extracts the contents of the downloaded zip file. The -o option overwrites any existing files without prompting.
  8. cp -r 2135_mini_finance/* /var/www/html/: Recursively copies the contents of the 2135_mini_finance directory to the Apache web root directory /var/www/html/.
  9. systemctl restart httpd: Restart the Apache HTTP server to apply the changes.
  10. cd /tmp/: Changes the current directory to /tmp/.
  11. rm -rf /tmp/finance: Removes the /tmp/finance directory and its contents. The -rf options forcefully remove files and directories recursively.

This provisioner script sets up an Apache HTTP server, downloads a template, extracts it, moves the content to the web server directory, and ensures that Apache is running and configured correctly.

Now in the host machine, move to the directory where this Vagrant file is located and start the VM:-

cd /c/install/vagrant-vms/financeIAC/
vagrant up

We had configured IP 192.168.56.28, so open this IP on the browser, and you can access the website.

Clean up:- Destroy the vagrant.

vagrant destroy 
vagrant global-status --prune

Keep this Vagrant file with you, we can use it in AWS while doing the same thing.

Automating Ubuntu VM with WordPress (LAMP Stack)

Go to the folder where the WordPress project is located, and create a copy of it. Rename the copied folder as wordprssIAC, and delete the ./vagrant folder within it. Edit the vagrantFile.

# Change IP
config.vm.network "private_network", ip: "192.168.56.38"
# Enable Public Network
config.vm.network "public_network"
# RAM Config
config.vm.provider "virtualbox" do |vb|
   vb.memory = "1600"
end

Now add all the required commands to the Vagrant file:-

config.vm.provision "shell", inline: <<-SHELL
  # Update package list
  sudo apt update

  # Install Apache, MySQL, PHP, and required PHP extensions
  sudo apt install apache2 \
                  ghostscript \
                  libapache2-mod-php \
                  mysql-server \
                  php \
                  php-bcmath \
                  php-curl \
                  php-imagick \
                  php-intl \
                  php-json \
                  php-mbstring \
                  php-mysql \
                  php-xml \
                  php-zip -y

  # Create the /srv/www directory
  sudo mkdir -p /srv/www

  # Change ownership of the /srv/www directory to www-data
  sudo chown www-data: /srv/www

  # Download the latest WordPress package and extract it to /srv/www as the www-data user
  curl https://wordpress.org/latest.tar.gz | sudo -u www-data tar zx -C /srv/www

  # Create Apache virtual host configuration for WordPress
  cat > /etc/apache2/sites-available/wordpress.conf <<EOF
<VirtualHost *:80>
        DocumentRoot /srv/www/wordpress
        <Directory /srv/www/wordpress>
            Options FollowSymLinks
            AllowOverride Limit Options FileInfo
            DirectoryIndex index.php
            Require all granted
        </Directory>
        <Directory /srv/www/wordpress/wp-content>
            Options FollowSymLinks
            Require all granted
        </Directory>
</VirtualHost>
EOF
  # There should be no extra space in the beginning or end of EOF.

  # Enable the WordPress site and necessary Apache modules
  sudo a2ensite wordpress
  sudo a2enmod rewrite
  sudo a2dissite 000-default

  # Configure MySQL database for WordPress
  mysql -u root -e 'CREATE DATABASE wordpress;'
  mysql -u root -e 'CREATE USER wordpress@localhost IDENTIFIED BY "root";'
  mysql -u root -e 'GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER ON wordpress.* TO wordpress@localhost;'
  mysql -u root -e 'FLUSH PRIVILEGES;'

  # Configure WordPress settings
  sudo -u www-data cp /srv/www/wordpress/wp-config-sample.php /srv/www/wordpress/wp-config.php
  sudo -u www-data sed -i 's/database_name_here/wordpress/' /srv/www/wordpress/wp-config.php
  sudo -u www-data sed -i 's/username_here/wordpress/' /srv/www/wordpress/wp-config.php
  sudo -u www-data sed -i 's/password_here/root/' /srv/www/wordpress/wp-config.php

  # Restart MySQL and Apache services
  systemctl restart mysql
  systemctl restart apache2
SHELL

Now in the host machine, move to the directory where this Vagrant file is located and start the VM:-

cd /c/install/vagrant-vms/wordpressIAC/
vagrant up

We had configured IP 192.168.56.38, so open this IP on the browser, and you can access the website.

Clean up:- Destroy the vagrant.

vagrant destroy 
vagrant global-status --prune

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *