Using Ansible for System Configuration

Tutorial 2 of 5

1. Introduction

1.1 Tutorial's goal

This tutorial aims to provide a comprehensive guide on using Ansible for system configuration. By the end of this tutorial, you should be able to write and run Ansible playbooks to manage and configure your systems.

1.2 Learning outcomes

  • Understand the core concepts of Ansible
  • Learn how to install Ansible
  • Write and execute Ansible Playbooks
  • Understand how to use Ansible for system configuration

1.3 Prerequisites

  • Basic understanding of YAML syntax
  • Familiarity with command line interface
  • A Linux or Unix-based system (recommended)

2. Step-by-Step Guide

2.1 Installing Ansible

Ansible is a simple and agentless automation tool. You can install it using the default package manager for your system. For instance, on a Ubuntu system, the command would be:

sudo apt-get update
sudo apt-get install ansible

2.2 Understanding Ansible Playbooks

Playbooks are Ansible’s configuration, deployment, and orchestration language. They are expressed in YAML format and describe a policy to be enacted on your remote systems.

Example:

---
- name: Playbook to install nginx
  hosts: webservers
  tasks:
  - name: ensure nginx is at the latest version
    apt: name=nginx state=latest

The above playbook ensures that nginx is installed on all your web servers.

2.3 Running Ansible Playbooks

To run the playbook, you can use the ansible-playbook command followed by the playbook file name.

ansible-playbook playbook.yml

3. Code Examples

3.1 Example: Installing a software package

Here is an example playbook that installs git on a server:

---
- name: Install git
  hosts: servers
  tasks:
    - name: Ensure git is installed
      apt:
        name: git
        state: present

3.2 Example: Starting a service

This playbook ensures the nginx service is started:

---
- name: Start nginx
  hosts: webservers
  tasks:
    - name: Ensure nginx is started
      service:
        name: nginx
        state: started

4. Summary

In this tutorial, we learned how to use Ansible for system configuration. We understood what Ansible is, how to install it, and how to write and run Ansible playbooks. We also saw practical examples of Ansible playbooks.

To explore more about Ansible, you can visit the official Ansible documentation.

5. Practice Exercises

5.1 Exercise 1: Write a playbook to install vim

Hint: This is similar to the git installation playbook.

5.2 Exercise 2: Write a playbook to stop a service

Hint: This is similar to the playbook for starting a service.

5.3 Exercise 3: Write a playbook to remove a software package

Hint: For this, you need to ensure the state is 'absent' instead of 'present'.