Learning Ansible 2.7(Third Edition)
上QQ阅读APP看书,第一时间看更新

Creating a test environment with Vagrant

To be able to learn Ansible, we will need to make quite a few playbooks and run them.

Doing this directly on your computer will be very risky. For this reason, I would suggest using virtual machines.

It's possible to create a test environment with cloud providers in a few seconds, but it is often more useful to have those machines locally. To do so, we will use Vagrant, which is a piece of software by Hashicorp that allows users to quickly set up virtual environments independently from the virtualization backend used on the local system. It does support many virtualization backends (in the Vagrant ecosystem these are known as Providers) such as Hyper-V, VirtualBox, Docker, VMWare, and libvirt. This allows you to use the same syntax no matter what operating system or environment you are in.

First we will install vagrant. On Fedora, it will be enough to run the following code:

    $ sudo dnf install -y vagrant  

On Red Hat/CentOS/Scientific Linux/Unbreakable Linux, we will need to install libvirt first, enable it, and then install vagrant from the Hashicorp website:

$ sudo yum install -y qemu-kvm libvirt virt-install bridge-utils libvirt-devel libxslt-devel libxml2-devel libvirt-devel libguestfs-tools-c
$ sudo systemctl enable libvirtd
$ sudo systemctl start libvirtd
$ sudo rpm -Uvh https://releases.hashicorp.com/vagrant/2.2.1/vagrant_2.2.1_x86_64.rpm
$ vagrant plugin install vagrant-libvirt

If you use Ubuntu or Debian, you can install it using the following code:

    $ sudo apt install virtualbox vagrant

For the following examples, I'll be virtualizing CentOS 7 machines. This is for multiple reasons; the main ones are as follows:

  • CentOS is free and 100% compatible with Red Hat, Scientific Linux, and Unbreakable Linux.
  • Many companies use Red Hat/CentOS/Scientific Linux/Unbreakable Linux for their servers.
  • These distributions are the only ones with SELinux support built in, and, as we have seen earlier, SELinux can help you make your environment much more secure.

To test that everything went well, we can run the following commands:

$ sudo vagrant init centos/7 && sudo vagrant up

If everything went well, you should expect an output ending with something like this:

==> default: Configuring and enabling network interfaces...
default: SSH address: 192.168.121.60:22
default: SSH username: vagrant
default: SSH auth method: private key
==> default: Rsyncing folder: /tmp/ch01/ => /vagrant

So, you can now execute vagrant ssh, and you will find yourself in the machine we just created.

There will be a Vagrant file in the current folder. In this file, you can create the directives with  vagrant init to create the virtual environment.