DevOps · K8s · Volleyball · Travel  •  DevOps · K8s · Volleyball · Travel  •  DevOps · K8s · Volleyball · Travel
Explore NY Tech

Ansible Part2 DEVOPS ONLINE TRAINING

July 14, 2026 — LiveStream

Ansible Part2 DEVOPS ONLINE TRAINING
🛒 Recommended gear on Amazon

Disclosure: some links above are affiliate links — if you buy through them I may earn a small commission at no extra cost to you. Thanks for supporting the channel!

As an Amazon Associate I earn from qualifying purchases.

Ready to level up your DevOps game? This comprehensive guide dives deep into Ansible Part 2 DEVOPS ONLINE TRAINING, exploring configuration, inventory management, ad-hoc commands, and powerful playbooks to automate your infrastructure efficiently. Mastering these concepts is crucial for any aspiring or seasoned DevOps engineer looking to streamline system administration and achieve true infrastructure as code.

The Core of Automation: Understanding Ansible Configuration and Inventory

Dekho bhai, in the world of DevOps, automation isn't just a buzzword; it's the backbone of efficiency and reliability. And when we talk about automation, Ansible stands out as a simple, agentless, and powerful tool. If you've covered the basics in Part 1, then in this Ansible Part 2 DEVOPS ONLINE TRAINING session, we’re going to get into the nitty-gritty – setting up your Ansible environment correctly and defining your target machines. Think of it like preparing your tools and knowing exactly which machines you’re going to work on before you even begin the actual work.

Deep Dive into ansible.cfg: Your Global Control Panel

Every good plan starts with a solid foundation, right? For Ansible, that foundation is often the ansible.cfg file. This isn't just a random text file; it's your control panel for customizing Ansible's behavior globally, per project, or even per user. It's where you define default paths, connection parameters, and other critical settings.

Ansible searches for this configuration file in a specific order:

  1. ANSIBLE_CONFIG (environment variable)
  2. ansible.cfg in the current directory
  3. ~/.ansible.cfg (user's home directory)
  4. /etc/ansible/ansible.cfg (system-wide)

This hierarchy means you can override global settings with project-specific ones, which is super useful for managing different environments. So, what kind of things do we typically configure here?

Here’s a sneak peek at what a simple ansible.cfg might look like:


[defaults]
inventory = ./inventory/hosts.ini
remote_user = devops_admin
ask_pass = False
host_key_checking = False
forks = 20
log_path = /var/log/ansible.log

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

Understanding and configuring this file properly is the first step towards a smooth automation journey. It’s like setting the rules of the game before you start playing!

Defining Your Battleground: The Ansible Inventory

Next up, the Ansible Inventory. If ansible.cfg defines how Ansible operates, the inventory defines where it operates. It's a list of all your managed nodes – your target servers, network devices, and so on. Without a correctly defined inventory, Ansible simply won't know where to run its commands or playbooks. Matlab, this is your address book for all your infrastructure.

Inventories can be static or dynamic:

Static Inventory (INI Format - Common in Ansible Part 2 DEVOPS ONLINE TRAINING)

This is the most straightforward way to start. You define hosts, and crucially, you group them. Groups are powerful because they allow you to target subsets of your infrastructure easily.


[webservers]
web1.example.com
web2.example.com
192.168.1.10 ansible_ssh_user=ubuntu

[dbservers]
db1.example.com
db2.example.com

[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_ssh_private_key_file=~/.ssh/id_rsa

A few things to note here:

Static Inventory (YAML Format)

YAML offers a more structured, readable way to define complex inventories, especially when you have many host and group variables.


all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
          ansible_ssh_host: 192.168.1.10
          ansible_ssh_user: ubuntu
    dbservers:
      hosts:
        db1.example.com:
        db2.example.com:
  vars:
    ansible_python_interpreter: /usr/bin/python3
    ansible_ssh_private_key_file: ~/.ssh/id_rsa

Whether you choose INI or YAML, the goal is the same: a clear, organized list of your infrastructure. Use the command ansible-inventory --graph to visualize your inventory, it’s a lifesaver for complex setups!

Related Reading: Managing Ansible Roles - Best Practices

Mastering Ad-Hoc Commands: Quick Wins and Debugging

Now that you’ve got your environment configured and your inventory defined, it’s time to actually *do* something. This is where Ansible ad-hoc commands come into play. Think of them as quick, one-liner instructions you give to your remote machines. They are perfect for immediate tasks, quick checks, or debugging. For a junior DevOps engineer, mastering these commands is like learning to talk to your servers directly, without writing a full script every time. It's an essential skill for any Ansible Part 2 DEVOPS ONLINE TRAINING.

The basic syntax is simple yet powerful:


ansible <pattern> -m <module> -a "<module_arguments>" [options]

Common and Invaluable Modules for Ad-Hoc Use

Let's look at some of the modules you’ll use almost daily:

1. ping Module: The Connectivity Test

This is your "hello, are you there?" command. It simply checks if Ansible can connect to your remote host and if Python is available. It's your first troubleshooting step.


ansible webservers -m ping

If you see a pong response, you’re good to go!

2. command and shell Modules: Running Raw Commands

These are your go-to for executing arbitrary commands on remote hosts. The difference is subtle but important:

Example (command): Check uptime on webservers


ansible webservers -m command -a "uptime"

Example (shell): Find large files in /tmp (requires shell features)


ansible all -m shell -a "find /tmp -size +100M -print"

When in doubt, always prefer command. Only use shell when you absolutely need shell features.

3. file Module: Managing Files and Directories

Need to create a directory, change file permissions, or delete a file? The file module is your friend. It's idempotent, meaning running it multiple times yields the same result without error.


# Create a directory
ansible all -m file -a "path=/opt/myapp state=directory mode=0755"

# Change permissions of a file
ansible all -m file -a "path=/var/log/my.log mode=0644"

# Delete a file
ansible all -m file -a "path=/tmp/junk.txt state=absent"

4. copy Module: Transferring Files

To copy files from your control node to your remote hosts, use the copy module.


# Copy a local script to all webservers
ansible webservers -m copy -a "src=/local/path/to/script.sh dest=/tmp/script.sh mode=0755"

5. apt / yum Module: Package Management

Installing or removing packages is a breeze. Ansible intelligently uses the correct package manager based on the target OS.


# Install Nginx on webservers (Ubuntu/Debian)
ansible webservers -b -m apt -a "name=nginx state=present update_cache=yes"

# Install httpd on webservers (RHEL/CentOS)
ansible webservers -b -m yum -a "name=httpd state=present"

# Ensure a package is removed
ansible all -b -m apt -a "name=unwanted-package state=absent"

The -b (--become) option here is essential because installing packages typically requires root privileges. The update_cache=yes argument for apt ensures that the package list is refreshed before installation, preventing issues with outdated information.

6. service Module: Managing Services

Starting, stopping, restarting, or checking the status of services.


# Start Nginx service on webservers
ansible webservers -b -m service -a "name=nginx state=started"

# Restart Nginx service
ansible webservers -b -m service -a "name=nginx state=restarted"

# Ensure Nginx starts on boot
ansible webservers -b -m service -a "name=nginx state=started enabled=yes"

These ad-hoc commands are incredibly useful for quick checks and interventions, but for more complex, repeatable, and robust automation, we turn to something even more powerful: Playbooks.

Internal Link: YAML Essentials for DevOps Engineers

Diving Deep into Ansible Playbooks: Orchestrating Complex Workflows

While ad-hoc commands are great for quick tasks, imagine trying to set up a complete web server with all its dependencies, configuration files, and services, using just one-liners. Impossible, right? That’s where Ansible Playbooks come in. Playbooks are the heart and soul of advanced Ansible automation, allowing you to define complex, multi-step orchestration in a human-readable YAML format. This is the real power move you learn in an Ansible Part 2 DEVOPS ONLINE TRAINING.

A playbook is essentially a list of plays, and each play consists of a list of tasks that run against a group of hosts. It describes the desired state of your systems, ensuring idempotent execution.

The Anatomy of an Ansible Playbook

Let's break down the typical structure of a playbook. If you're familiar with YAML, you'll find this pretty intuitive. If not, thoda YAML ki practice kar lo, it's fundamental for DevOps automation.


--- # This is a YAML document separator, often used at the beginning
- name: Configure Webservers and Deploy Application
  hosts: webservers # Which hosts from your inventory this play will run on
  become: yes       # Elevate privileges (sudo) for this play
  gather_facts: yes # Gather facts about the remote hosts (OS, memory, etc.)

  vars:             # Variables specific to this play
    nginx_port: 80
    app_version: 1.0.0

  pre_tasks:        # Tasks to run before regular tasks
    - name: Ensure system is updated
      ansible.builtin.apt:
        update_cache: yes
        upgrade: dist
      when: ansible_os_family == "Debian"

  tasks:            # The core tasks of this play
    - name: Install Nginx package
      ansible.builtin.apt:
        name: nginx
        state: present
      notify: Restart Nginx

    - name: Create Nginx configuration file
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/default
        mode: '0644'
      notify: Restart Nginx

    - name: Ensure Nginx service is started and enabled
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: yes

    - name: Deploy application code
      ansible.builtin.copy:
        src: files/my_app.html
        dest: /var/www/html/index.html
        mode: '0644'

  handlers:         # Tasks that are only triggered by `notify` directives
    - name: Restart Nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Let's unpack the key components:

Key Playbook Features for Robust Automation

1. Variables: Making Playbooks Dynamic

Variables allow you to create flexible and reusable playbooks. You can define them in many places, with specific precedence rules:

Using variables keeps your playbooks DRY (Don't Repeat Yourself) and makes them adaptable to different environments or configurations. For example, using {{ nginx_port }} instead of hardcoding 80 allows you to easily change it later.

2. Conditionals: "When" to Execute Tasks

The when keyword allows you to execute a task only if a certain condition is met. This often leverages Ansible facts.


- name: Install Apache on RedHat systems
  ansible.builtin.yum:
    name: httpd
    state: present
  when: ansible_os_family == "RedHat"

- name: Install Nginx on Debian systems
  ansible.builtin.apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

This ensures your playbook is smart enough to handle different operating systems with a single file. Bada useful hai yeh!

3. Loops: Repeating Tasks Efficiently

When you need to perform the same action multiple times with different values, loops are your best friend. The loop keyword (or older with_items) is commonly used.


- name: Create multiple users
  ansible.builtin.user:
    name: "{{ item }}"
    state: present
    shell: /bin/bash
  loop:
    - alice
    - bob
    - charlie

- name: Install multiple packages
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
  loop:
    - vim
    - htop
    - net-tools

This avoids repetitive task definitions, keeping your playbook clean and concise.

4. Handlers: Idempotent Service Management

Handlers are special tasks that only run when explicitly "notified" by another task. They are executed at the end of a play, and crucially, they run only once, even if multiple tasks notify them. This is perfect for restarting services only when their configuration files have actually changed.

In the example playbook above, the Restart Nginx handler is notified when either the Nginx package is installed or its configuration file is updated. This ensures Nginx only restarts if necessary, maintaining uptime.

Mastering playbooks is a significant leap in your Ansible Part 2 DEVOPS ONLINE TRAINING. They allow you to define repeatable, testable, and version-controlled infrastructure deployments, aligning perfectly with the Infrastructure as Code (IaC) principles of DevOps.

Best Practices, Troubleshooting, and the DevOps Mindset with Ansible

A senior DevOps engineer ke saath chai pe baat karte hue, you'll quickly realize that knowing the commands and syntax is only half the battle. The other half is about knowing *how* to use them effectively, troubleshoot issues, and adopt a mindset that leverages these tools for maximum impact. This section of our Ansible Part 2 DEVOPS ONLINE TRAINING focuses on practical wisdom.

Structuring Your Ansible Project for Scale and Maintainability

As your infrastructure grows, a haphazard collection of playbooks and inventory files becomes a nightmare. A well-structured project is vital:

This structure helps organize your code, promotes reusability, and makes it easier for team members to understand and contribute. Aur haan, always keep your Ansible project under Version Control (Git). This is non-negotiable in DevOps.

Debugging and Testing: Your Automation Superpowers

Even the best playbooks will have issues. Knowing how to debug and test effectively saves hours of frustration:

Security Considerations: Protecting Your Automation

Automating infrastructure means your automation tool has significant power. Protect it!

The DevOps Mindset: Beyond the Commands

Ultimately, Ansible is a tool. The true power comes from how you integrate it into your DevOps philosophy:

Bhai, this isn't just about learning syntax; it's about shifting your approach to system administration from manual, error-prone processes to robust, reliable, and scalable automation. That's the real essence of Ansible Part 2 DEVOPS ONLINE TRAINING.

Key Takeaways

Frequently Asked Questions

What is the primary difference between ansible.cfg and an inventory file?

ansible.cfg configures Ansible's *behavior* (how it connects, where it logs, default users, etc.), defining the rules of engagement. An inventory file, on the other hand, defines *where* Ansible will operate by listing all the target hosts and organizing them into groups. Think of ansible.cfg as your tool's settings, and the inventory as your list of machines to work on.

When should I use ad-hoc commands versus playbooks?

Use ad-hoc commands for quick, one-off tasks like checking host uptime (ansible all -m command -a "uptime"), installing a single package, or restarting a service quickly. They are great for immediate diagnostics or simple changes. Use playbooks for complex, multi-step, repeatable, and version-controlled automation, such as deploying an entire application, configuring multiple services, or setting up a new server from scratch. Playbooks provide structure, error handling, and logical flow that ad-hoc commands lack.

What is idempotence in Ansible, and why is it important?

Idempotence means that running a task multiple times will produce the same result as running it once, without causing unintended side effects or errors on subsequent runs. For example, if you tell Ansible to ensure a package is "present," it will install it if missing, but do nothing if it's already there. This is crucial in automation because it allows you to safely re-run playbooks to enforce desired states, apply minor changes, or recover from failures without worrying about breaking existing configurations. Ansible modules are designed to be idempotent, which is a key strength.

How can I manage sensitive information like passwords in Ansible?

You should never hardcode sensitive information directly in your playbooks or inventory files. The recommended way to manage secrets is using Ansible Vault. Ansible Vault allows you to encrypt variables, entire files, or even whole directories. You'll typically store encrypted variables in dedicated files (e.g., vault.yml) and Ansible will prompt you for a vault password to decrypt them at runtime when you execute a playbook. This ensures your secrets are protected both at rest and in transit.

This journey through Ansible Part 2 DEVOPS ONLINE TRAINING should give you a solid footing in automating your infrastructure. To see these concepts in action and get practical demonstrations, make sure to watch the full video on the @explorenystream YouTube channel. Don't forget to subscribe for more valuable DevOps insights and training!

Report Abuse

Contributors