This tutorial provides a step-by-step guide to managing services using Ansible. You’ll learn how to automate service management tasks, configure services, and handle real-world scenarios with Ansible playbooks.

Beginner30 minutes

Step 1: Step 1: Install Ansible and Set Up Your Environment

Before you can manage services with Ansible, you need to install it and set up your environment. Ansible is agentless, meaning it only requires SSH access to the target machines.

  • Install Ansible on your control machine:
- For Ubuntu: sudo apt install ansible

- For CentOS: sudo yum install ansible

  • Verify the installation: ansible --version
  • Set up your inventory file (/etc/ansible/hosts) to define the target machines.
# Example inventory file
[webservers]
192.168.1.10
192.168.1.11

[dbservers]
192.168.1.20

Practice Exercise

Create an inventory file that includes three groups: webservers, dbservers, and loadbalancers. Add at least two IP addresses or hostnames to each group.

Show Solution
# Solution
[webservers]
192.168.1.10
192.168.1.11

[dbservers]
192.168.1.20
192.168.1.21

[loadbalancers]
192.168.1.30
192.168.1.31

Step 2: Step 2: Write Your First Ansible Playbook for Service Management

Ansible playbooks are YAML files that define tasks to be executed on target machines. Let's create a playbook to start the nginx service on all webservers.

  • Create a file named start_nginx.yml.
  • Define the playbook structure:
- Specify the target hosts (webservers).

- Add a task to start the nginx service.

# start_nginx.yml
- hosts: webservers
  tasks:
    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started

Practice Exercise

Write a playbook to stop the apache2 service on all webservers. Ensure the playbook includes a task to verify that the service is stopped.

Show Solution
# Solution
- hosts: webservers
  tasks:
    - name: Ensure apache2 is stopped
      ansible.builtin.service:
        name: apache2
        state: stopped
    - name: Verify apache2 is stopped
      ansible.builtin.shell: systemctl status apache2
      register: result
    - debug: var=result.stdout

Step 3: Step 3: Manage Multiple Services with a Single Playbook

You can manage multiple services in a single playbook. For example, let's ensure nginx is running and apache2 is stopped on webservers.

  • Add multiple tasks to your playbook.
  • Use the service module for each task.
# manage_services.yml
- hosts: webservers
  tasks:
    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
    - name: Ensure apache2 is stopped
      ansible.builtin.service:
        name: apache2
        state: stopped

Practice Exercise

Create a playbook to start the mysql service and stop the postgresql service on all dbservers. Include a task to verify the status of both services.

Show Solution
# Solution
- hosts: dbservers
  tasks:
    - name: Ensure mysql is running
      ansible.builtin.service:
        name: mysql
        state: started
    - name: Ensure postgresql is stopped
      ansible.builtin.service:
        name: postgresql
        state: stopped
    - name: Verify mysql status
      ansible.builtin.shell: systemctl status mysql
      register: mysql_status
    - name: Verify postgresql status
      ansible.builtin.shell: systemctl status postgresql
      register: postgresql_status
    - debug: var=mysql_status.stdout
    - debug: var=postgresql_status.stdout

Step 4: Step 4: Handle Service Dependencies and Conditions

Some services depend on others. For example, nginx might require php-fpm to be running. Use Ansible's when condition to handle dependencies.

  • Add a task to check if php-fpm is running.
  • Use the when condition to start nginx only if php-fpm is running.
# service_dependencies.yml
- hosts: webservers
  tasks:
    - name: Ensure php-fpm is running
      ansible.builtin.service:
        name: php-fpm
        state: started
    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
      when: "'active (running)' in ansible_facts.services['php-fpm'].state"

Practice Exercise

Write a playbook to start tomcat only if java is installed on the target machine. Use the when condition to check if java is installed.

Show Solution
# Solution
- hosts: webservers
  tasks:
    - name: Check if java is installed
      ansible.builtin.shell: which java
      register: java_installed
      ignore_errors: yes
    - name: Ensure tomcat is running
      ansible.builtin.service:
        name: tomcat
        state: started
      when: java_installed.rc == 0

Step 5: Step 5: Automate Service Restarts on Configuration Changes

When configuration files change, services often need to be restarted. Use Ansible's notify and handlers to automate this.

  • Add a task to update the configuration file.
  • Use notify to trigger a handler that restarts the service.
# restart_service.yml
- hosts: webservers
  tasks:
    - name: Update nginx configuration
      ansible.builtin.copy:
        src: /path/to/nginx.conf
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx
  handlers:
    - name: Restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Practice Exercise

Create a playbook to update the mysql configuration file and restart the mysql service only if the file changes. Use notify and handlers.

Show Solution
# Solution
- hosts: dbservers
  tasks:
    - name: Update mysql configuration
      ansible.builtin.copy:
        src: /path/to/my.cnf
        dest: /etc/mysql/my.cnf
      notify: Restart mysql
  handlers:
    - name: Restart mysql
      ansible.builtin.service:
        name: mysql
        state: restarted

Step 6: Step 6: Manage Services Across Different Operating Systems

Ansible can manage services across different operating systems. Use the ansible_facts variable to determine the OS and adjust tasks accordingly.

  • Use ansible_facts to check the OS.
  • Use when conditions to handle OS-specific tasks.
# multi_os_service.yml
- hosts: all
  tasks:
    - name: Ensure httpd is running on CentOS
      ansible.builtin.service:
        name: httpd
        state: started
      when: ansible_facts['os_family'] == 'RedHat'
    - name: Ensure apache2 is running on Ubuntu
      ansible.builtin.service:
        name: apache2
        state: started
      when: ansible_facts['os_family'] == 'Debian'

Practice Exercise

Write a playbook to start the ssh service on both CentOS and Ubuntu systems. Use ansible_facts to determine the OS and handle the service name accordingly.

Show Solution
# Solution
- hosts: all
  tasks:
    - name: Ensure sshd is running on CentOS
      ansible.builtin.service:
        name: sshd
        state: started
      when: ansible_facts['os_family'] == 'RedHat'
    - name: Ensure ssh is running on Ubuntu
      ansible.builtin.service:
        name: ssh
        state: started
      when: ansible_facts['os_family'] == 'Debian'

Step 7: Step 7: Use Roles to Organize Service Management Tasks

Roles help organize playbooks into reusable components. Create a role to manage services.

  • Create a role directory structure: ansible-galaxy init service_manager.
  • Move your tasks, handlers, and variables into the role.
# Example role structure
service_manager/
  tasks/
    main.yml
  handlers/
    main.yml
  defaults/
    main.yml

Practice Exercise

Create a role named web_server that includes tasks to manage nginx and apache2 services. Use the role in a playbook to apply it to webservers.

Show Solution
# Solution
# web_server/tasks/main.yml
- name: Ensure nginx is running
  ansible.builtin.service:
    name: nginx
    state: started
- name: Ensure apache2 is stopped
  ansible.builtin.service:
    name: apache2
    state: stopped

# playbook.yml
- hosts: webservers
  roles:
    - web_server

Step 8: Step 8: Monitor Services and Handle Failures

Use Ansible to monitor services and handle failures gracefully.

  • Add tasks to check service status.
  • Use failed_when to handle failures.
# monitor_services.yml
- hosts: webservers
  tasks:
    - name: Check nginx status
      ansible.builtin.shell: systemctl status nginx
      register: nginx_status
      failed_when: "'active (running)' not in nginx_status.stdout"

Practice Exercise

Write a playbook to monitor the mysql service. If the service is not running, start it and send a notification.

Show Solution
# Solution
- hosts: dbservers
  tasks:
    - name: Check mysql status
      ansible.builtin.shell: systemctl status mysql
      register: mysql_status
      failed_when: "'active (running)' not in mysql_status.stdout"
    - name: Start mysql if not running
      ansible.builtin.service:
        name: mysql
        state: started
      when: "'active (running)' not in mysql_status.stdout"
    - name: Send notification
      ansible.builtin.debug:
        msg: "MySQL was not running and has been started."

Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.

Sign in

Click to access the login or register cheese