Introduction to Ansible - Part 3

Introduction to Ansible - Part 3

In the past 2 posts I did a quick Introduction to Ansilble and a quick overview of some of the important config files that you should be familiar with, you can find the links to Part 1 and Part 2 here:

https://bobbyiliev.com/blog/introduction-to-ansible-part-1

https://bobbyiliev.com/blog/introduction-to-ansible-part-2

Overview

In this part we will focus on what Ansible Ad-hoc commands are and we will introduce a few basic commands so make sure to have your 3 servers up and running and be able to follow along.

If you don't have your 3 servers yet make sure to check the part 2 of the series! You can get a free $50 credit that you could use to deploy your virtual machines and test the guide yourself on a few Digital Ocean servers:

Digital Ocean $50 Free Credit

Ansible commands

There are two ways of running Ansible commands:

  •   - Ad-hoc commands
  •   - Playbooks

The Ad-hoc commands are just like single bash command that we want to execute. Playbooks on the other side are like scripts and can target different node groups.

To run Ansible Ad-hoc commands you can just use the ansible command and then specify a host and the command that you want to run.

For example if you want to check the disk space on a specific remote server you could run:

ansible host-name -i hosts -a "df -h"

The output that you would get would look something like this:

Ansible Disk check Ad-hoc command

 

Ansible modules

You can also run modules. This is almost the same but the we use -m flag rather than the -a flag for an action, for example:

ansible host-name -m setup
Output:
 
Ansible ad-hoc  modules

 

What the setup module does is it hooks up with the host and shows us all of the information that Ansible master has about the host. As you can see this returns a lot of infomration that can be used in a countless different ways.

Here's another Ad-hoc command example:

 ansible host-name -m ping
Output:
 
Ansible ping pong

 

This simply pings our host, that way we can test the connectivity to the host in question.

We can also install some packages on the host:

 ansible host-name -b -m apt -a "name=apache2 state=latest"

Rundown of the command:

-b - means become which essentially means that the command would be ran with sudo privileges

-m - specifies the module that we want to use

-a - specifies the flags, in our case we specify that we want to install the latest apache2 version

 

Install apache ansible

 

We could also start the service with the service module:

ansible host-name -b -m service -a "name=apache2 state=started"
 
Ansible start apache

 

That's pretty much it for the ad-hoc commands. We can now move to the Ansible Playbooks:

https://bobbyiliev.com/blog/introduction-to-ansible-part-4

Feel free to reach out to me in case that you have any questions!

Coffee For Me