Operations 16 min read

Master Ansible: From Facts to Playbooks, Templates, and Roles

This guide walks you through Ansible fundamentals, covering how to gather host facts, use modules like script, selinux, and template, write YAML playbooks, manage variables, apply Jinja2 templates, and organize tasks with roles for efficient automation.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Ansible: From Facts to Playbooks, Templates, and Roles

setup : Retrieve facts of specified hosts.

Facts are built‑in variables that contain host information such as CPU count and memory size. They can be used to make decisions, e.g., using yum on RedHat families and apt on Debian families.

<code>ansible 10.1.6.68 -m setup</code>

script : Send a script to managed nodes and execute it without parameters.

<code>ansible all -m script -a 'test.sh'</code>

selinux : Manage SELinux state.

conf      # SELinux configuration file
state=enforcing|permissive|disabled   # Corresponds to SELINUX in the config
policy=targeted|minimum|mls        # Corresponds to SELINUXTYPE
Disable SELinux: <code>ansible all -m selinux -a 'state=disabled'</code>

template : Use Jinja2 format as a file template to replace variables inside documents.

5. Playbook: Running a Playbook

A playbook is a yaml file that stacks multiple modules.

1. Introduction

YAML is a human‑readable data‑serialization format, inspired by XML, C, Python, Perl, and RFC2822. It was first published in 2001 by Clark Evans, Ingy döt Net, and Oren Ben‑Kiki.

2. Features

Good readability Excellent interaction with scripting languages Uses native data types of the implementation language Consistent data model Easy to implement Stream‑based processing Strong expressive power and extensibility

YAML syntax uses indentation for structure, "-" for list items, and ":" for key‑value pairs.

- hosts: 10.1.0.1
  vars:
    var1: value
    var2: value
  tasks:
    - name: # task name
      # module invocation here
  handlers:
    - name:
  remote_user: root

- hosts: web
  vars:
  tasks:
  handlers:
  remote_user:

YAML files usually have the .yaml or .yml extension.

Playbooks

1. Core Elements:

Tasks: list of operations defined by modules

Variables

Templates: files using template syntax for variable substitution

Handlers: tasks triggered by specific conditions

Roles

2. Basic Components of a Playbook:

Hosts: target hosts for the tasks
remote_user: user to execute tasks on remote hosts
sudo_user: user with sudo rights (if needed)
tasks: list of tasks
  module, module arguments:
    (1) action: module arguments
    (2) module: arguments

Example 1:

Save as test.yaml or

test.yml
- hosts: all
  remote_user: root
  tasks:
  - name: install a group
    group: name=mygrp system=true
  - name: install a user
    user: name=user1 group=mygrp system=true

- hosts: websrvs
  remote_user: root
  tasks:
  - name: install httpd package
    yum: name=httpd
  - name: start httpd service
    service: name=httpd state=started

3. Running a Playbook with ansible‑playbook

(1) Syntax check

ansible-playbook --syntax-check /path/to/playbook.yaml

(2) Test run (check mode)

ansible-playbook -C /path/to/playbook.yaml
--list-hosts
--list-tasks
--list-tags
ansible-playbook --check /path/to/playbook.yaml

(3) Execute

ansible-playbook /path/to/playbook.yaml
-t TAGS, --tags=TAGS
--skip-tags=SKIP_TAGS   # skip specified tags
--start-at-task=START_AT # start execution after a given task

Tags are defined in tasks as:

- name: NAME
  module: arguments
  tags: TAG_ID

6. Variables

Built‑in: (1) facts Custom:

(1) Command‑line variables (highest priority): -e VAR=VALUE (2) Define host‑specific variables in the inventory ( /etc/ansible/hosts).

(a) Assign different variables to different hosts
   10.1.6.72 qzx=httpd
   10.1.6.73 qzx=nginx

(b) Assign the same variable to all hosts in a group
   [groupname:vars]
   variable_name=value

(3) Define variables inside a playbook (recommended):

vars:
  - var_name: value
  - var_name: value

(4) Inventory connection parameters (e.g., ansible_ssh_host, ansible_ssh_user).

(5) Pass variables when invoking a role:

roles:
  - { role: ROLE_NAME, var: value, ... }

Variable usage:

{{ var_name }}

7. Templates

Templates are text files that embed a template language (Jinja2) to render variables.

Jinja2, written in Python, is ideal for text‑based templating.

Purpose

Replace template variables with actual values on the target host, e.g., {{ ansible_processor_vcpus }} becomes the host’s CPU count.

Jinja2 Syntax

Literal values: strings, numbers, lists, tuples, dictionaries, booleans
Arithmetic: + - * / // % **
Comparison: == != > < >= <=
Logical: and or not

Execute a template with the template module.

Key parameters for the template module:

backup   # create a timestamped backup
dest     # absolute path on remote node
group    # group ownership of the file
mode     # file permissions (chmod style)
owner    # file owner
src      # local Jinja2 template path

Example: Deploy an Nginx configuration using a template.

- hosts: ngxsrvs
  remote_user: root
  tasks:
  - name: install nginx package
    yum: name=nginx state=latest
  - name: install conf file
    template: src=/root/nginx.conf.j2 dest=/etc/nginx/nginx.conf tags=ngxconf notify: reload nginx service
  - name: start nginx service
    service: name=nginx state=started enabled=true
  handlers:
  - name: reload nginx service
    shell: /usr/sbin/nginx -s reload

Conditional Execution

- hosts: all
  remote_user: root
  tasks:
  - name: start nginx on CentOS 6
    shell: service nginx start
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
  - name: start nginx on CentOS 7
    shell: systemctl start nginx.service
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"

Loops

Iterate over items using with_items (list, string, or dictionary).

- hosts: websrvs
  remote_user: root
  tasks:
  - name: install packages
    yum: name={{ item }} state=latest
    with_items:
    - httpd
    - php
    - php-mysql
    - php-mbstring
    - php-gd

8. Roles

Roles organize tasks, variables, handlers, templates, and files into a standardized directory structure, similar to functions.

mkdir ./{nginx,memcached,httpd,mysql}/{files,templates,vars,handlers,meta,default,tasks} -pv

Typical role layout:

role_name/
  files/      # files used by copy or script modules
  tasks/      # at least main.yml defining tasks
  handlers/   # at least main.yml defining handlers
  vars/       # at least main.yml defining variables
  templates/  # Jinja2 template files
  meta/       # at least main.yml defining dependencies
  defaults/   # at least main.yml defining default variables

Invoke roles in a playbook:

- hosts: HOSTS
  remote_user: USERNAME
  roles:
  - ROLE1
  - ROLE2
  - { role: ROLE3, VARIABLE: VALUE }
  - { role: ROLE4, when: CONDITION }

Example: Install Nginx using a role.

- name: copy nginx package
  copy: src=nginx-1.10.0-1.el7.ngx.x86_64.rpm dest=/tmp/nginx-1.10.0-1.el7.ngx.x86_64.rpm

- name: install nginx package
  yum: name=/tmp/nginx-1.10.0-1.el7.ngx.x86_64.rpm state=present

- name: install nginx.conf file
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf tags=ngxconf notify: reload nginx service

- name: install default.conf file
  template: src=default.conf.j2 dest=/etc/nginx/conf.d/default.conf tags=ngxconf notify: reload nginx service

- name: start nginx service
  service: name=nginx enabled=true state=started
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

YAMLJinja2Rolesplaybookconfiguration-management
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.