Ansible Part2 DEVOPS ONLINE TRAINING
July 14, 2026 — LiveStream
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!
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.
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.
ansible.cfg: Your Global Control PanelEvery 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:
ANSIBLE_CONFIG (environment variable)ansible.cfg in the current directory~/.ansible.cfg (user's home directory)/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?
inventory: This tells Ansible where to find your list of managed hosts. By default, it looks for /etc/ansible/hosts, but you'll often point it to a project-specific file like inventory/hosts or hosts.ini. This is critical for getting your Ansible basics right.remote_user: The user Ansible will use to connect to your remote machines. It's usually a non-root user with sudo privileges.ask_pass: Set to True if you want Ansible to prompt for the SSH password to connect to the remote hosts. For automation, we often prefer SSH keys, so this might be False.become: This section configures privilege escalation (e.g., sudo, su). If you want Ansible tasks to run with elevated permissions (like installing packages), you'll enable become = True and might specify become_method = sudo.host_key_checking: Set this to False initially for quick lab setups, but for production, you should keep it True. It ensures Ansible verifies the host key, preventing man-in-the-middle attacks. Trust me, security is paramount.forks: The number of parallel processes Ansible will use to communicate with remote hosts. Default is 5, but you might increase it for larger environments.log_path: Where Ansible should write its log messages. Very helpful for debugging!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!
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:
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:
[webservers] and [dbservers] are groups. You can target all hosts in a group.192.168.1.10 ansible_ssh_user=ubuntu).[all:vars] applies variables to all hosts. You can also define variables for specific groups (e.g., [webservers:vars]).
[production:children]
webservers
dbservers
Now, if you target production, it includes both webservers and dbservers.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!
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]
<pattern>: Specifies which hosts from your inventory to target (e.g., all, webservers, dbservers, or even specific IPs/hostnames).-m <module>: The Ansible module you want to execute. Modules are the units of work Ansible performs.-a "<module_arguments>": Arguments to pass to the module.[options]: Additional options like -i (inventory path), -u (remote user), -b (become/sudo), -K (ask for sudo password).Let's look at some of the modules you’ll use almost daily:
ping Module: The Connectivity TestThis 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!
command and shell Modules: Running Raw CommandsThese are your go-to for executing arbitrary commands on remote hosts. The difference is subtle but important:
command: Executes commands directly, without processing them through a shell. Safer, but limited (e.g., no shell features like pipes, redirects, variables).shell: Executes commands through a shell (/bin/sh by default). Gives you full shell capabilities, but be cautious with untrusted inputs.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.
file Module: Managing Files and DirectoriesNeed 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"
copy Module: Transferring FilesTo 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"
apt / yum Module: Package ManagementInstalling 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.
service Module: Managing ServicesStarting, 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 EngineersWhile 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.
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:
---: Indicates the start of a YAML document.- name:: A descriptive name for your play or task. Crucial for readability and debugging.hosts:: Specifies which groups or hosts from your inventory this particular play should target.become:: Equivalent to the -b option for ad-hoc commands; enables privilege escalation for all tasks in the play.gather_facts:: By default, Ansible gathers "facts" (system information like OS, IP addresses, memory) about the target hosts. Set to no if you don't need them to speed up execution.vars:: Defines variables that are specific to this play.pre_tasks:: Tasks that run before the main tasks block.tasks:: The core of your playbook. A list of individual tasks to be executed. Each task typically calls an Ansible module.handlers:: Special tasks that are only run when explicitly notified by a task. They are typically used for restarting services after a configuration change.Variables allow you to create flexible and reusable playbooks. You can define them in many places, with specific precedence rules:
vars: keyword (as shown above).host_vars/<hostname>.yml files.group_vars/<groupname>.yml files.-e): Passed on the command line: ansible-playbook -e "env=production db_port=3306" my_playbook.yml. These have high precedence.ansible_os_family, ansible_memtotal_mb).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.
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!
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.
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.
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.
As your infrastructure grows, a haphazard collection of playbooks and inventory files becomes a nightmare. A well-structured project is vital:
project_root/: Your main directory.
ansible.cfg: Project-specific configurations.inventory/: Contains your inventory files (e.g., hosts.ini, production.yml, staging.yml).playbooks/: Your main playbooks (e.g., site.yml, webservers.yml).group_vars/: YAML files defining variables for groups (e.g., all.yml, webservers.yml).host_vars/: YAML files defining variables for specific hosts (e.g., server1.example.com.yml).roles/: Directory for reusable roles (more advanced, often covered in Ansible Part 3, but good to know it exists).templates/: Jinja2 templates for configuration files.files/: Static files to be copied to target hosts.scripts/: Any auxiliary scripts needed by playbooks.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.
Even the best playbooks will have issues. Knowing how to debug and test effectively saves hours of frustration:
-v, -vv, -vvv, -vvvv):
ansible-playbook my_playbook.yml -vvv
The more 'v's, the more detailed the output. This shows you exactly what Ansible is doing under the hood, including module parameters, SSH connections, and task results.check Mode (Dry Run):
ansible-playbook my_playbook.yml --check
This runs the playbook without making any actual changes on the remote hosts. It's excellent for verifying syntax and logical flow.diff Mode:
ansible-playbook my_playbook.yml --check --diff
Combined with --check, this shows you what changes *would have been made* to files, giving you a detailed preview. Indispensable for configuration tasks.--step Mode:
ansible-playbook my_playbook.yml --step
Ansible pauses before each task and asks for your confirmation to proceed. Great for debugging tricky tasks one by one.debug Module: Inject debug tasks into your playbook to print variable values or messages at specific points.
- name: Print OS family
ansible.builtin.debug:
msg: "The OS family is {{ ansible_os_family }}"
This helps you verify if variables are correctly populated.--limit):
ansible-playbook my_playbook.yml --limit webservers[0]
Run your playbook only on a specific host or subset of hosts to test changes safely before a wider rollout.failed_when and changed_when: You can customize when a task is considered failed or changed based on output patterns or conditions. This gives you fine-grained control over task state.Automating infrastructure means your automation tool has significant power. Protect it!
ansible-vault create vars/secret_vars.yml
ansible-vault encrypt my_playbook.yml
ansible-playbook my_playbook.yml --ask-vault-pass
become judiciously.host_key_checking = True in ansible.cfg for production environments to prevent connecting to imposter hosts.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.
ansible.cfg is your configuration hub: Customize Ansible's global and project-specific behaviors for paths, users, and privilege escalation.ping, command, shell, file, copy, apt/yum, and service for immediate actions and debugging.when), loops, and handlers to build robust and repeatable automation.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.
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.
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.
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!