
Course overview covering all topics: introduction to Ansible and how it works; lab environment setup including installation and managed node configuration; core components (inventory, modules, playbooks, configuration); playbook syntax and first playbook; modules (command, file, copy, others); conditions (when, with_items, notify, handlers); variables; additional concepts (shell script conversion, gather facts, error handling, tags); multi-task playbooks; Ansible Vault for secure data management; and Ansible Roles for playbook organization and Git integration.
Introduction to Ansible as an open source IT automation engine. Covers what Ansible can automate: configuration management (updating server configurations), provisioning (creating VMs, cloud instances, containers, pods), application deployment (jar, exe, and other application types), and orchestration (executing tasks sequentially). Details why Ansible is preferred: simple YAML format with no special coding skills required, tasks execute in sequential order, powerful (handles multiple purposes), agentless architecture using OpenSSH, secure, efficient with low resource consumption, open source and free, and flexible as a single tool for various automation tasks instead of maintaining multiple tools.
Architecture overview of Ansible: control node (where Ansible is installed) manages multiple managed nodes (client servers) using SSH with passwordless authentication enabled. Core components explained: inventory (list of managed node information), playbooks (actual tasks to execute on target systems), and modules (units of code with specific functionality that perform actions). Key terminologies defined: control node, managed nodes, inventory (also called host file), modules (predefined or custom code units), tasks (units of action), and playbooks (ordered lists of tasks). Modules come preinstalled with Ansible and are used by tasks within playbooks.
Lab environment setup overview: control node on Amazon Linux managing client nodes across multiple operating systems (RHEL, Amazon Linux, Ubuntu) to demonstrate Ansible's cross-platform compatibility. Ansible installation limited to Linux (cannot be installed on Windows), but Windows can be managed nodes. Setup steps for each node: create server, enable passwordless authentication between control node and client, and register in the Ansible inventory file. Once configured, Ansible commands can be executed against all managed nodes.
Prerequisites and setup for Ansible control node on AWS: launch EC2 instance (Amazon Linux 2, t2.micro), configure security group (ports 22, 80, 8080), and download key pair. System configuration: set hostname, create dedicated user (ans_admin), add user to sudoers file with NOPASSWD privileges, generate SSH key pair (public and private keys stored in ~/.ssh), and enable password-based authentication by editing etc/ssh/sshd_config to uncomment passwordAuthentication yes and comment out passwordAuthentication no, then restart SSH service.
Installation steps for Ansible on EC2: prerequisites (EC2 instance prepared from previous lecture), install Python and pip (using yum), install Ansible via pip (pip install ansible), verify with ansible --version (example: 2.9.2). Create /etc/ansible directory and copy ansible.cfg configuration file from official Ansible documentation. Create hosts file (inventory) in /etc/ansible using touch command; inventory file remains empty until managed nodes are created and registered.
Setup steps for RHEL as Ansible managed node: launch EC2 instance using existing key pair from control node, configure security group (use existing ansible_sg), set hostname (RHEL managed node), create ans_admin user with consistent password (ans_admin@123), add user to sudoers file with NOPASSWD privileges, and enable password-based authentication by editing etc/ssh/sshd_config (uncomment passwordAuthentication yes, comment out passwordAuthentication no). No SSH key generation needed on managed node; keys are copied from control node to enable passwordless authentication. Managed node configuration then ready to be registered in Ansible inventory.
Adding RHEL managed node to Ansible inventory: update /etc/ansible/hosts file with RHEL server's private IP address, use ssh-copy-id command to copy SSH public key from ans_admin user on control node to managed node (requires service sshd restart/reload after sshd_config changes), establish passwordless SSH authentication. Introduction to ad-hoc commands: ansible command-line tool for automating single tasks on managed nodes. Ad-hoc syntax: ansible <pattern> -m <module-name> -a <module-options>. Testing connectivity with ping module (ansible all -m ping): "all" targets all servers in inventory file, responses show successful (pong) or failed connectivity status.
Practical examples of ad-hoc command modules: command module executes Unix commands directly (uptime, date, who); stat module checks file existence with path attribute; yum module installs packages using name attribute (requires -b flag to become root); user module creates users with name attribute (requires -b for root privileges, output shows yellow for changed status, green for no changes); setup module retrieves complete system information without attributes (processor cores, distribution, OS family, network, CPU, memory). Demonstrates color-coded output: yellow indicates changes made, green indicates success with no changes.
Definition and purpose: inventory is a collection of hosts or nodes managed by Ansible. Default inventory location: /etc/ansible/hosts. Three ways to define inventory: default (/etc/ansible/hosts), custom file using -i flag (ansible all -m ping -i custom_hosts), or in ansible.cfg configuration file. Creating custom inventory files and overriding default location in ansible.cfg. Creating groups in inventory using [groupname] syntax to organize servers; "all" targets all servers in inventory, group name targets only servers in that group. Best practice: avoid default inventory in teams; create separate inventory files per project/team to prevent unintended execution on wrong servers.
Introduction to ansible.cfg: provides default values when Ansible commands lack specific parameters. Key parameters: inventory (default host file), library (module location), forks (batch size for parallel execution), ask_pass (password prompt), module_name (default module when -m not specified; default is command), privilege escalation settings (become=false, become_method=sudo, become_ask_pass=false). Configuration file priority hierarchy: environment variable > current directory ansible.cfg > home directory ansible.cfg > /etc/ansible/ansible.cfg. Creating custom ansible.cfg in current working directory with only necessary parameters; custom config merges with defaults. Example: setting become=true eliminates need for -b flag in commands, allowing root privilege escalation without explicit flag.
Definition of modules: reusable standalone scripts that Ansible executes locally or remotely on behalf of users. Modules interact with local system and remote APIs to perform tasks including creating users, installing packages, updating configurations, and spinning up instances. Modules are programs that perform actual work of tasks within plays. Ansible ships with thousands of modules (~3300+) available in official documentation organized by categories (cloud, clustering, command, etc.). Accessing module documentation: ansible.org module index for detailed information, parameters, and usage examples; ansible-docs -l command lists all installed modules on system. Detailed module information includes parameters, examples, and playbook usage.
Introduction to Ansible playbooks: set of instructions (plays) for executing tasks on single or group of target hosts. Playbook basics: text file in YAML format (.yml extension), starts with three dashes (---) as document marker, uses spaces for indentation to indicate structure, items start with single dash followed by space. Mandatory fields: hosts (inventory targets) and tasks (activities to perform). Modules used within tasks to perform actual work. Converting ad-hoc command (ansible all -m user -a name=john -b) to playbook format. Playbook structure: hosts declaration, become flag for privilege escalation, tasks section with module name and parameters. Execution using ansible-playbook command; output includes gathering facts step and task status (changed/ok/failed).
Expanding environment from one to three managed nodes: provisioning two additional EC2 instances (Amazon Linux, Ubuntu) using existing security group and key pair. Configuration steps identical to RHEL setup: hostname, ans_admin user, sudoers file, password-based authentication enable, sshd reload. Ubuntu-specific considerations: user add -m -d flags required to create home directory (/home/ans_admin) as Ubuntu doesn't create by default. Creating custom hosts file in /opt/ansible with groups (web_servers, app_servers, db_servers) to organize managed nodes; nodes can belong to multiple groups. Using ssh-copy-id to copy SSH keys from ans_admin to new managed nodes, establishing passwordless authentication. Verifying connectivity: ansible all -m ping on custom hosts file confirms all three managed nodes reachable.
Executing playbook with ansible-playbook -i command on custom hosts file. Understanding output: gather_facts task (default, runs setup module), task execution, color-coded status (yellow=changed, green=ok), play recap with statistics (ok, changed, unreachable, failed, skipped, rescued, ignored). Idempotent behavior: running same playbook again on systems where desired state already exists produces no changes. Adding "name" statement to tasks for readable descriptions in output. Playbook structure: name, hosts, become at same indentation; each task starts with dash, followed by optional name statement; modules with attributes specified on same line use equals, on new lines use colon space with proper indentation.
Using yum module to install packages via Ansible playbooks. Specifying target group in hosts field (web_servers) to run only on specific servers. Key yum module parameters: name (package name), state (installed/latest/present/absent/removed). Creating playbook with become flag for privilege escalation. Installing packages with -b flag from command line when become not specified in playbook. Handling playbook execution failures: missing groups in inventory causes "no hosts matched" error and skips execution. Verifying package installation on target systems.
Using file module to manage files and directories on target systems. Key parameters: path (required, specifies file/directory location and name), state (touch for file, directory for folder, absent for removal). Creating playbook targeting all hosts; become flag affects file ownership (become true creates as root, commented out creates as ans_admin). Verifying file/directory creation with ls -l to confirm ownership and permissions. Removing files by changing state to absent. Module applies consistently across different OS distributions (RHEL, Amazon Linux, Ubuntu).
Using copy module to copy files from Ansible control node to managed nodes. Key parameters: src (source file location), dest (destination path on remote), mode (file permissions like 0600), owner (file ownership). Creating index.html file on control node, then copying to target systems with specified permissions and owner (john user). Using --check flag to preview changes without executing, --syntax-check to validate YAML syntax before running playbook. Become flag required when changing file ownership; not required for basic file copy operations. Verifying copied files with ls -l to confirm permissions and ownership applied correctly.
Installing Apache (httpd) using yum module and starting service with service module. Creating playbook with multiple tasks targeting web_servers group; each task at same indentation level. Service module parameters: name (service name), state (started/stopped/restarted/reloaded). Creating ansible.cfg in current directory to define inventory path, eliminating need for -i flag in ansible-playbook commands. Installing httpd with -b flag for privilege escalation, verifying service running with ps and rpm commands, accessing web server via browser. Uninstalling process: stop service first, then remove package using yum state=removed. Verified successful install/removal by checking service status and package presence.
Installing Apache on Ubuntu using apt module (not yum, as yum not available on Ubuntu). Package name apache2 (not httpd). Targeting db_servers group since Ubuntu is only managed node in that group. Apt module parameters: name (apache2), state (present/absent/latest/fixed; installed not valid for apt). Starting apache2 service with service module (name=apache2, state=started). Using ansible-playbook without -i flag (inventory defined in ansible.cfg). Verifying installation by accessing web server via browser, confirming Apache2 running on Ubuntu system.
Using notify and handlers for conditional task execution: handler runs only when notify task makes changes. Handlers declared at same indentation level as tasks. When package installation task makes changes, notify triggers corresponding handler to start service; if package already installed, no changes occur and handler doesn't execute. Handler names must match notify names exactly. Advantage: skips unnecessary tasks when desired state already exists. Example workflow: notify "start apache" in yum task triggers handler "start apache" only if installation succeeds. Re-running playbook on already-configured system skips handler execution.
Gathering facts: automatic default task executed before playbook tasks to collect system information from remote nodes. Information gathered: IP addresses, volumes, CPU, memory, kernel versions, OS versions, ansible_os_family (debian for Ubuntu, redhat for RHEL/Amazon Linux). Equivalent to setup module (ansible all -m setup). Useful during installations to check system status and OS details. Disabling gather facts with gather_facts: no reduces execution time for large environments when system information not needed. Re-enabling by commenting out gather_facts: no restores default behavior.
Using when condition to conditionally execute tasks based on system properties. Single playbook handles multiple OS distributions using ansible_os_family variable (gathered from gather_facts). When syntax: when ansible_os_family == "RedHat" for RHEL/Amazon, when ansible_os_family == "Debian" for Ubuntu. Tasks are skipped on systems that don't match condition; output shows "skipped" status. Requires gather_facts enabled to access ansible_os_family; disabling gather_facts causes condition evaluation error. Allows unified playbook approach instead of separate files per OS.
Updating uninstall playbook with when conditions to support RHEL and Ubuntu. Remove httpd via yum (state=removed) when ansible_os_family=="RedHat"; stop httpd service. Remove apache2 via apt (state=absent) when ansible_os_family=="Debian"; stop apache2 service. Executing on all hosts with OS-specific filtering; state=removed for yum, state=absent for apt.
Enhancing install_apache_httpd.yml playbook with copy task. Modifying index.html with custom content "welcome to apache tomcat". Adding copy task: src (index.html), dest (/var/www/html), mode (0666 for read/write), become flag for root privileges. Copy module works same across RHEL and Ubuntu, no when condition needed. Executing playbook copies index.html to target servers; file replaces previous content. Verifying via browser refresh shows updated content on all managed nodes.
Installing multiple packages with single task using list syntax: name parameter takes array of packages [git, make, gcc, wget, telnet, gzip]. Executing on target systems installs all packages in one task. Alternative deprecated method: with_items loop (deprecated in version 2.11+, not recommended). Verifying package installation: rpm -qa (RHEL) and apt list --installed (Ubuntu) to check installed packages. List method preferred; with_items generates deprecation warnings.
Ansible variable definition methods: within playbook (vars section), external files (vars_files), inventory, command line (-e or --extra-vars). Syntax: {{ variable_name }} with braces; quotes required if variable starts value. Naming rules: underscore, numbers allowed; no hyphens. Priority: command line > external file > playbook vars. Example: create_user.yml with hardcoded "John" replaced with {{ user }} variable. Enables reusable playbooks; single value change updates all references. Command line variables override all other definitions.
Are you just started working on your DevOps career? or are you a typical system administrator who doesn't know how to automate tasks? Then this course is for you.
Ansible for DevOps Beginners and System Admins course helps you to understand how Ansible works and automate your day-to-day activities. We have discussed various topics like ad-hoc commands, playbooks, variables, inventory, and roles with detailed examples.
I am sure that you will be able to automate your regular tasks using Ansible after the completion of this course.
I will continue to enhance this course according to the feedback and reviews.
What are you waiting for? Join me to learn Ansible now!
in this course, we have covered
what is ansible
why do we need ansible
how ansible works
how to prepare an ansible system on AWS
installing ansible on EC2 instance
setup and RHEL as an ansible managed node
Ansible Ad-hoc commands
Ansible Inventory
Ansible configuration file - ansible.cfg
Ansible modules
create your 1st ansible-playbook
setup additional managed nodes
run a ansible playbook
Yum module to install packages
file module to create or remove a file
copy module to copy a file
Install apache on Rhel
install apache on ubuntu
notify and handlers in a playbook
how to gather facts works
how when condition works
uninstall apache using when the condition
adding copy task to apache playbook
ansible variables
convert shell commands into ansible-playbook
using tags in a playbook
error handling in the ansible playbook
ansible vault introduction
using ansible vault with git
ansible roles
convert a playbook into a role
push your playbooks onto GitHub