Batch 4: Cloud Ansible & OpenShift AWS & Azure Docker & Podman Apache & NGINX ← Full TOC

← Ansible Index

⚡ Ansible Ad-hoc & Modules — Ad-hoc commands, essential modules, Jinja2 templating

Ansible ad-hoc commands run single tasks without a playbook. Mastering the core modules — apt, copy, template, service, user, file, command — covers 90% of automation needs.

📋 Reference

ItemSyntax / ValueDescription
ansible -m pingansible all -i inventory -m pingTest connectivity to all hosts
ansible -m commandansible webservers -m command -a 'uptime'Run a command on hosts
ansible -m shellansible webservers -m shell -a 'df -h | grep /dev'Run shell command (supports pipes)
ansible -m aptansible webservers -m apt -a 'name=nginx state=present' -bInstall package
ansible -m copyansible webservers -m copy -a 'src=file.txt dest=/tmp/'Copy file to hosts
ansible -m fetchansible webservers -m fetch -a 'src=/etc/hostname dest=./hosts/'Fetch file from hosts
ansible -m setupansible web01 -m setupGather all facts about a host
ansible -m setup -a filteransible web01 -m setup -a 'filter=ansible_*ip*'Filter facts
apt modulename: / state: present/absent/latest / update_cache:Install/remove packages (Debian/Ubuntu)
yum/dnf modulename: / state: present/absent/latestInstall/remove packages (RHEL/CentOS)
copy modulesrc: / dest: / owner: / group: / mode:Copy file from controller to hosts
template modulesrc: jinja2.j2 / dest: /path/configRender Jinja2 template and copy
file modulepath: / state: file/directory/absent/link / mode:Manage files and directories
service modulename: / state: started/stopped/restarted / enabled:Manage system services
user modulename: / state: present/absent / groups: / shell:Manage system users
group modulename: / state: present/absent / gid:Manage system groups
command modulecmd: / creates: / removes: / chdir:Run command (no shell — safer)
shell modulecmd: / executable: /bin/bashRun shell command (supports pipes/redirects)
lineinfile modulepath: / line: / regexp: / state:Ensure line present/absent in file
blockinfile modulepath: / block: / marker:Insert/update block of text in file
replace modulepath: / regexp: / replace:Regex find-and-replace in file
uri moduleurl: / method: / status_code: / body:HTTP requests from Ansible
get_url moduleurl: / dest: / checksum:Download file from URL
unarchive modulesrc: / dest: / remote_src:Extract tar/zip archives
git modulerepo: / dest: / version:Clone or update git repository
cron modulename: / job: / minute: / hour: / day:Manage cron jobs
debug modulemsg: / var:Print debug messages
set_fact modulekey: valueSet variables dynamically
include_tasksinclude_tasks: other_tasks.ymlDynamically include task file
import_tasksimport_tasks: other_tasks.ymlStatically import task file
Jinja2 vars{{ variable_name }}Variable interpolation
Jinja2 filter{{ var | upper | default('N/A') }}Transform variable value
Jinja2 condition{% if condition %}...{% endif %}Conditional in template
Jinja2 loop{% for item in list %}...{% endfor %}Loop in template

💡 Example

# ── Ad-hoc commands ──────────────────────────────────────────
# Test connectivity
ansible all -i inventory -m ping

# Run command on all web servers
ansible webservers -i inventory -m command -a "uptime" -u ubuntu

# Get disk usage
ansible all -i inventory -m shell -a "df -h | tail -1" -b

# Install package
ansible webservers -i inventory -m apt \
  -a "name=apache2 state=present update_cache=yes" -b

# Copy file
ansible webservers -i inventory -m copy \
  -a "src=index.html dest=/var/www/html/index.html owner=www-data mode=0644" -b

# Restart service
ansible webservers -i inventory -m service \
  -a "name=apache2 state=restarted" -b

# Create user
ansible all -i inventory -m user \
  -a "name=deploy groups=www-data shell=/bin/bash state=present" -b

# Get all facts
ansible web01 -i inventory -m setup | head -50

# ── Jinja2 Templates ──────────────────────────────────────────
# templates/apache.conf.j2
cat > /tmp/apache.conf.j2 << 'TEMPLATE'
# Generated by Ansible — {{ ansible_managed }}
# Host: {{ inventory_hostname }}
# Date: {{ ansible_date_time.date }}

<VirtualHost *:{{ app_port | default(80) }}>
    ServerName  {{ server_name | default(ansible_fqdn) }}
    ServerAdmin {{ admin_email | default("webmaster@" + ansible_domain) }}
    DocumentRoot {{ app_dir }}

    {% if enable_https | default(false) %}
    # Redirect HTTP to HTTPS
    RewriteEngine On
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
    {% endif %}

    {% for alias in server_aliases | default([]) %}
    ServerAlias {{ alias }}
    {% endfor %}

    <Directory {{ app_dir }}>
        Options +ExecCGI {% if disable_indexes | default(true) %}-Indexes{% endif %}
        AllowOverride {{ allow_override | default('All') }}
        Require all granted
    </Directory>

    ErrorLog  ${APACHE_LOG_DIR}/{{ app_name }}_error.log
    CustomLog ${APACHE_LOG_DIR}/{{ app_name }}_access.log \
      {% if log_format is defined %}{{ log_format }}{% else %}combined{% endif %}

</VirtualHost>
TEMPLATE

# ── Common Playbook Patterns ──────────────────────────────────
cat > /tmp/patterns.yml << 'YAML'
---
- name: Deployment patterns
  hosts: webservers
  become: true

  tasks:
    # Register + debug
    - name: Get disk usage
      ansible.builtin.shell: df -h / | awk 'NR==2{print $5}'
      register: disk_usage
      changed_when: false

    - name: Show disk usage
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} disk: {{ disk_usage.stdout }}"

    # Conditional
    - name: Install Apache (Debian only)
      ansible.builtin.apt:
        name: apache2
        state: present
      when: ansible_os_family == 'Debian'

    - name: Install httpd (RedHat only)
      ansible.builtin.yum:
        name: httpd
        state: present
      when: ansible_os_family == 'RedHat'

    # Loop with dict
    - name: Create app directories
      ansible.builtin.file:
        path:  "{{ item.path }}"
        owner: "{{ item.owner }}"
        mode:  "{{ item.mode }}"
        state: directory
      loop:
        - { path: /var/www/html,    owner: www-data, mode: '0755' }
        - { path: /var/log/app,     owner: www-data, mode: '0750' }
        - { path: /etc/app/conf.d,  owner: root,     mode: '0755' }

    # Block with rescue
    - name: Deploy application
      block:
        - name: Pull latest code
          ansible.builtin.git:
            repo:    https://github.com/myorg/myapp.git
            dest:    /var/www/html
            version: main
        - name: Restart service
          ansible.builtin.service:
            name: apache2
            state: restarted
      rescue:
        - name: Rollback on failure
          ansible.builtin.command: git -C /var/www/html checkout HEAD~1
        - name: Notify on failure
          ansible.builtin.debug:
            msg: "Deployment failed on {{ inventory_hostname }} — rolled back"
YAML
echo "Patterns written to /tmp/patterns.yml"

# Run: ansible-playbook -i inventory patterns.yml -v

← OpenShift & Kubernetes  |  🏠 Index