# Ansible By Example — Full Content > Complete article content from ansiblebyexample.com. 1576 technical articles covering Ansible modules, playbooks, roles, troubleshooting, and enterprise automation. ## Install Google Chrome on Red Hat Using Ansible URL: https://www.ansiblebyexample.com/articles/install-google-chrome-in-redhat-like-systems-ansible-module-rpm-key-yum-repository-and-yum Description: Use Ansible to install Google Chrome on Red Hat. Follow our detailed playbook to add repositories and install Chrome efficiently. How to Install Google Chrome in RedHat-like systems with Ansible? ## Ansible install Google Chrome in RedHat-like systems - Add Google Chrome key => ansible.builtin.rpm_key - Add Google Chrome repository => ansible.builtin.yum_repository - Update yum cache and install Google Chrome => ansible.builtin.yum In order to install Google Chrome on a RedHat-like system, we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.rpm_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Google releases. The second step is to add the add Google Chrome repository to the distribution. It’s an extra website where `yum/dnf`, your distribution package manager looks like for software. You are going to use the `ansible.builtin.yum_repository` Ansible module. The third step is to update the yum cache for the available packages and install Google Chrome using the `ansible.builtin.yum` Ansible module. ## Parameters - `rpm_key` `key` string — URL - `rpm_key` `state` string — present/absent - `yum_repository` `name` string — repository - `yum_repository` `baseurl` string — URL - `yum_repository` `gpgcheck` boolean — enable GPG - `yum_repository` `gpgkey` string — GPG check and key URL - `yum` `name` string — name or package-specific - `yum` `state` string — latest/present/absent - `yum` `update_cache` boolea... --- ## 🎉 Schedule LIVE! KubeCon + CloudNativeCon Europe 2025 URL: https://www.ansiblebyexample.com/articles/kubecon-cloudnativecon-europe-2025 Description: Get ready for the premier cloud-native event, KubeCon + CloudNativeCon Europe 2025, happening in London, 1-4 April 2025. ## 🎊 Welcome to KubeCon + CloudNativeCon Europe 2025! The much-anticipated **KubeCon + CloudNativeCon Europe 2025** is set to take place from **1-4 April 2025** in **London**. Hosted by the **Cloud Native Computing Foundation (CNCF)**, this event promises to bring together **cloud-native enthusiasts, developers, and leaders** for an unforgettable conference experience. --- ## 🚀 Why Attend? Join **#TeamCloudNative** for an event packed with: - **Expert-Led Talks**: Hear from industry leaders and gain insights into cutting-edge topics like Kubernetes, AI integration, and platform engineering. - **CNCF-Hosted Events**: Explore **16 co-located events** covering specific cloud-native projects and innovations. - **Hands-On Learning**: Participate in **ContribFest**, **Maintainer Tracks**, and other interactive sessions to deepen your Kubernetes expertise. - **Networking Opportunities**: Meet and collaborate with fellow enthusiasts, contributors, and CNCF project maintainers. - **Swag and Celebrations**: Enjoy fun evening events and exclusive conference swag. --- ## 🌟 Featured Sessions The conference boasts a lineup of incredible sessions, including: - **Kubernetes and AI to Protect Our Forests**: Andrea Giardini discusses how cloud-native tools are used for wildfire prevention. - **From Metal to Apps: LinkedIn’s Kubernetes-Based Compute Platform**: Insights from Ahmet Alp Balkan and Ronak Nathani. - **Superpowers for Humans of Kubernetes**: Discover how K8sGPT is transf... --- ## 🛟 How to Navigate 2022 IT Turbulent Time — Weathering New Challenges URL: https://www.ansiblebyexample.com/articles/how-to-navigate-2022-it-turbulent-time-weathering-new-challenges Description: How to navigate the storm and increase your value and hireability in the IT market, keeping your skills sharp, and learning new technologies and languages. ## 10th November, 2022 Hello Ansible Pilot Community, This article is a bit different from the usual one because we are all living in some turbulent times, and I would like to share with you some personal thoughts and maybe relate to you. Just for reference, this article was written on November 10th, 2022 and I would like to empathize with IT engineers navigating an uncertain Market. I could understand because also my personal life was a bit of chaos. I made many changes, so I have learned some lessons on this topic. What's the matter today is some recent layoffs from significant players like Stripe, Lyft, and other IT tech companies. Today is the news of a looming layoff in Meta and Twitter. Also, the news reports these days for companies such as Google, Microsoft, and Apple, a slowing down the hiring process or a hiring freeze season. I think that all of us should have a framework for how to navigate this uncertain market time. I'm deep inside of me an optimist. Because the world survived many wars, the incredible Codiv pandemic and several the financial crisis (the latest in 2008), and many, many events such as the oil crisis of the 70s. We are facing an important period because the economy is probably slowing down; we don't know if there is a recession, not I'm not an economist, but I see many different signs affecting every business. Every employee like us, IT Engineers, working in technology are part of every business. Some of us need to provide for a family, and we ne... --- ## AAP 2.7 PostgreSQL 17 and Django 5.2 LTS: What Changed Under the Hood URL: https://www.ansiblebyexample.com/articles/aap-2-7-postgresql-17-and-django-5-2-lts-what-changed-under-the-hood Description: AAP 2.7 platform internals explained: PostgreSQL 16/17 support, Django 5.2 LTS, gateway-only architecture, and what it means for your inventory. Red Hat Ansible Automation Platform 2.7 lands with a quiet but consequential foundation refresh: PostgreSQL 16 and 17 support, a Django 5.2 LTS upgrade, and a gateway-only architecture where every inter-component call is routed through the platform gateway. None of this changes a single playbook you write, but it changes what you should check before an upgrade. ## Verify database and dependency readiness before upgrading [code example] ## What this does and why it matters The play does two things a migration runbook should always do first: confirm the database engine is on a version the new platform release actually supports, and confirm the gateway is the single reachable entry point for the stack. - **PostgreSQL 16/17**: AAP 2.7 adds support for PostgreSQL 16 and 17 alongside continued support for earlier supported versions, so this is the moment to plan a database engine upgrade if you're still on an older release. Checking `major_version` against an explicit allow-list before you touch the platform install avoids a failed migration mid-upgrade. - **Django 5.2 LTS**: the controller's API layer now runs on Django 5.2 LTS. This is an internal dependency bump — no controller/EDA/gateway API contract change is implied by itself — but it means the underlying async ORM, security patch cadence, and Python version compatibility window all shift to match Django's own LTS support timeline. Custom scripts that shell out to `manage.py` or import controller internals directly (not... --- ## Add Secondary Groups to Linux Users with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/add-a-user-to-a-second-group-on-linux-ansible-module-user Description: Learn how to add secondary groups to Linux users with an Ansible playbook. This step-by-step guide includes YAML configuration and execution details. ## How to add a user to a second group on Linux with Ansible? ## Ansible adds a user to second a group - `ansible.builtin.user` - Manage user accounts Today we're talking about the Ansible module `user`. The full name is ansible.builtin.user, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts. It supports a huge variety of Linux distributions, SunOS and macOS and FreeBSD. For Windows, use the `ansible.windows.win_user` module instead. ## Parameters - `name` string - username - `group` - user's primary group (only one) - `groups` list / elements=string - list of groups user will be added to - `append` boolean - `no`/`yes` - If `yes`, add the user to the groups specified in groups. If no, replace. This module has many parameters, let me highlight the use for our use-case. The only required is "`name`", which is the username. The primary group is specified in the "group" parameter, every user needs to be part of only one group. The "`groups`" parameter specifies the list of additional groups that the user will be added to. This type of group sometimes is called also "secondary", "additional" or "supplementary". The parameter "append" is very important. With the "`yes`" option, the user is going to be added to the specified groups. With the "`no`" option, all group members are going to be overwritten with the specified groups. So to Conclusion is you specif... --- ## Adding Commas Between Elements in Jinja2 URL: https://www.ansiblebyexample.com/articles/adding-commas-between-elements-in-jinja2 Description: Create comma-separated lists in Jinja2 — loop.last, join filter, custom delimiters, and practical Ansible template examples. ## Introduction Creating a comma-separated list from a collection of items is one of the most common Jinja2 templating tasks. Whether generating configuration files, SQL statements, JSON payloads, or CSV output, you need to place a delimiter between elements without a trailing comma after the last one. This article covers every approach — `loop.last`, the `join` filter, custom delimiters, and real-world Ansible template patterns. ## Method 1: The join Filter (Recommended) The simplest and most Pythonic approach — use the `join` filter: [code example] ### Ansible Playbook Example [code example] **Output:** [code example] ### With Type Conversion When list elements are not all strings: [code example] ## Method 2: loop.last in Jinja2 Templates For more complex formatting in template files, use `loop.last`: [code example] ### Template File Example **Template** (`templates/allowed_hosts.conf.j2`): [code example] **Playbook:** [code example] **Output file:** [code example] ## Method 3: loop.first for Leading Delimiters Sometimes you need the first item without a delimiter and all subsequent items with one: [code example] This produces identical output to `loop.last` but is useful when the delimiter logic is more natural at the start. ## Available Loop Variables Jinja2 provides several useful variables inside `{% for %}` loops: | Variable | Description | |---|---| | `loop.index` | Current iteration (1-indexed) | | `loop.index0` | Current iteration (0-inde... --- ## Advanced Ansible Techniques: Leveraging Jinja2 Filters for Smart Data Transformations URL: https://www.ansiblebyexample.com/articles/leveraging-jinja2-filters-for-smart-data-transformations Description: Unveiling the power of Ansible's Jinja2 filters for advanced data transformations: A step-by-step exploration of smart automation. ## Advanced Ansible and Jinja2 Ansible's power lies in its ability to handle complex data structures with minimal code. By leveraging Jinja2 filters, you can elegantly transform data to meet automation requirements. This article explores a practical example of converting a simple list into a structured list of dictionaries, highlighting the flexibility and efficiency of Jinja2 in Ansible. ## Scenario: Transforming `vmlist` to `vmlist2` Imagine you have a list of virtual machine names (`vmlist`), and you need to convert it into a list of dictionaries (`vmlist2`), where each dictionary includes the key `name` with the corresponding value from `vmlist`. ### Input Data [code example] ### Desired Output [code example] ## The Jinja2 Solution Here’s a compact and efficient way to achieve this transformation using Jinja2 filters: [code example] ### Step-by-Step Breakdown 1. **`map('regex_replace', '(.*)', '{"name": "\\1"}')`**: - Applies a regex to each element in `vmlist`, wrapping it into a JSON string. - Example: `"a"` becomes `{"name": "a"}`. 2. **`map('from_json')`**: - Converts the JSON string into a Python dictionary. - Example: `{"name": "a"}` is now a usable dictionary in Ansible. 3. **`list`**: - Ensures the final output is a proper list of dictionaries. ### Usage in an Ansible Playbook Here’s how to use this transformation in an actual playbook: [code example] ### Output When you run the playbook, the output will be: [code example] ## Al... --- ## AI DevOps Ansible Community on Skool URL: https://www.ansiblebyexample.com/articles/ai-devops-ansible-community-on-skool Description: Join Luca Berton's AI DevOps Ansible Community for top-tier training in Ansible, Kubernetes, and Terraform. Access 50+ hours of courses and career support! ## Luca Berton Launches the AI DevOps Ansible Community on Skool Luca Berton, a seasoned expert in AI, DevOps, and cloud technologies, has officially launched the **AI DevOps Ansible Community** on Skool, bringing together a global network of professionals passionate about automation, cloud infrastructure, and career development in the world of DevOps. With over 18 years of industry experience and a reputation for delivering high-quality, hands-on training, Luca's new community aims to empower both aspiring and seasoned DevOps engineers. ### What is the AI DevOps Ansible Community? The **AI DevOps Ansible Community** is a membership-based platform where members gain access to more than **50 hours of expert-led courses** on a range of cutting-edge technologies, including **AI, Ansible, Kubernetes, Terraform, and cloud computing**. The community is designed to be a hub for like-minded professionals, providing not only education but also **mentorship, hands-on labs, and career development workshops**. With Luca’s extensive background, including his work for companies like JPMorgan Chase, Red Hat, and Dell Technologies, members are assured top-tier instruction and guidance. His teaching has already reached over **15,000 students** on platforms like Udemy, Coursera, and Pluralsight, earning him a stellar 4.5+ rating across courses. ### Why Join the Community? Luca Berton’s community goes beyond traditional online courses. It’s built to offer members a hands-on learning expe... --- ## AIOps: The Future of IT Operations with AI-Driven Automation URL: https://www.ansiblebyexample.com/articles/aiops Description: Discover how AIOps enhances IT operations by leveraging AI, machine learning, and automation. Learn how it reduces downtime, improves efficiency. ## 🔍 Introduction to AIOps In today’s fast-paced digital world, IT operations teams are under immense pressure to maintain uptime, optimize performance, and manage **increasingly complex hybrid cloud environments**. Traditional **manual monitoring and troubleshooting** approaches are no longer enough. Enter **AIOps**—**Artificial Intelligence for IT Operations**. AIOps is a modern IT operations approach that **combines AI, machine learning, and big data analytics** to **automate and enhance problem resolution**. It enables IT teams to **detect anomalies, predict failures, and trigger automated responses in real-time**, significantly reducing downtime and improving system reliability. --- ## 🚀 How Does AIOps Work? ### 1️⃣ Data Collection and Aggregation AIOps relies on vast amounts of **operational data**, including: - System logs - Network traffic - Application performance metrics - Security alerts - Authentication attempts - Firewall logs This data is collected from multiple sources and **organized into a centralized repository**. ### 2️⃣ Data Processing and Correlation Once gathered, **AI and machine learning models analyze the data** to: - Detect anomalies and trends - Identify root causes of failures - Correlate events across systems Advanced AIOps platforms use **natural language processing (NLP)** and **deep learning** to **extract meaningful insights from unstructured logs**. ### 3️⃣ Automated Remediation and Decision Making AIOps doesn’t just detect problem... --- ## Amazon AWS Collection 10.3.1 — Bugfixes for S3, ASG, and KMS URL: https://www.ansiblebyexample.com/articles/amazon-aws-collection-10-3-1-bugfixes-for-s3-asg-and-kms Description: Amazon.aws 10.3.1 release fixes s3_object_info, autoscaling_group, kms_key, and CloudFront module bugs. Upgrade guide and changelog for Ansible AWS. # Amazon AWS Collection 10.3.1 — Bugfixes for S3, ASG, and KMS ## Introduction The `amazon.aws` collection version 10.3.1 was released in May 2026 with important bugfixes for four modules: `s3_object_info` (duplicate dictionary fix), `autoscaling_group` (key assignment reliability), `kms_key` (key assignments), and CloudFront module utilities (TypeError fix). If you manage AWS infrastructure with Ansible, upgrade to avoid hitting these bugs. ## What's Fixed ### s3_object_info — Duplicate Dictionary Keys Previous versions could produce duplicate keys in the returned dictionary when listing S3 objects with common prefixes, leading to lost data in results. [code example] ### autoscaling_group — Key Assignment Reliability Fixed an issue where Auto Scaling Group configuration could fail with duplicate key assignments when updating launch templates or mixed instance policies. [code example] ### kms_key — Key Assignment Fix Resolved duplicate key assignment issues when managing KMS keys with complex policies and grants. [code example] ### CloudFront Utilities — TypeError Fix Fixed a `TypeError` in CloudFront module utilities that could occur during distribution configuration updates. [code example] ## Upgrade [code example] [code example] ## Version History (Recent) | Version | Date | Highlights | |---------|------|-----------| | 10.3.1 | May 2026 | S3, ASG, KMS, CloudFront bugfixes | | 10.3.0 | Apr 2026 | New features | | 10.2.0 | Mar 2026 | EC2 improvements | |... --- ## Amazon.aws 11.4.0 Released - aws_ssm Connection Plugin Overhaul and RDS Active Directory Support URL: https://www.ansiblebyexample.com/articles/amazon-aws-11-4-0-released-aws-ssm-connection-plugin-overhaul-and-rds-active-directory-support Description: Amazon.aws 11.4.0 brings aws_ssm plugin improvements for Windows, rds_instance AD domain join support, and RFC-compliant docs. # Amazon.aws 11.4.0 Released - aws_ssm Connection Plugin Overhaul and RDS Active Directory Support ## Introduction The `amazon.aws` collection provides the core Ansible modules and plugins for managing AWS resources, including EC2, RDS, Route 53, VPC, and the `aws_ssm` connection plugin used to reach instances via AWS Systems Manager instead of SSH or WinRM. Version 11.4.0 has been published to Galaxy, and it focuses on a significant refactor of the `aws_ssm` connection plugin (particularly for Windows targets), new Active Directory support in `rds_instance`, and a broad documentation cleanup that replaces realistic-looking IPs, keys, and fingerprints with RFC-compliant placeholder values. ## Whats New ### aws_ssm connection plugin refactor The bulk of the functional changes in this release land in the `aws_ssm` connection plugin, tracked under PR #2909: - Added the `endpoint_url` option (alias `aws_endpoint_url`) for connecting to alternate AWS endpoints. - Extracted Windows command execution logic into a dedicated `WindowsCommandExecutor` class, improving code organisation for Windows-targeted sessions. - Refactored the plugin to inherit from `AWSConnectionBase`, giving it consistent AWS credential handling shared with the other AWS connection/inventory plugins. - Renamed several connection options for consistency across the collection, while keeping the old names as aliases: | Old option | New option | |---|---| | `aws_access_key_id` | `access_key` | | `aws_secret_a... --- ## amazon.aws 11.5.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/amazon-aws-11-5-0-released-whats-new-and-how-to-test Description: amazon.aws 11.5.0 adds use_deprecated_tags to aws_ec2 inventory, drops module_utils.six, and fixes ec2_spot_instance, rds_cluster, aws_sqs_queue, aws_ssm. # amazon.aws 11.5.0 Released - Whats New and How to Test ## Introduction `amazon.aws` is the Ansible collection that provides modules, inventory plugins, and the `aws_ssm` connection plugin used to manage Amazon Web Services resources and connect to EC2 instances through AWS Systems Manager. Version 11.5.0 has been published on Ansible Galaxy, replacing 11.4.0. This is a minor release: it introduces a new option on the `aws_ec2` inventory plugin, removes a deprecated compatibility shim in favor of the Python standard library, and ships five bugfixes affecting `ec2_spot_instance`, `aws_sqs_queue`, `rds_cluster`, and the `aws_ssm` connection plugin. ## Whats New ### Minor Changes - The deprecated `ansible.module_utils.six` compatibility shims have been replaced with their Python standard library equivalents. `ansible.module_utils.six` is deprecated starting in ansible-core 2.21 and is scheduled for removal in 2.24 (PR #3039). - The `aws_ec2` inventory plugin gains a `use_deprecated_tags` option, which allows disabling the deprecated `tags` host variable (and its associated deprecation and reserved-name warnings) independently of the global deprecation warning settings (issue #3028). ### Bugfixes - **aws_sqs_queue** - Fixed UUID generation in the EDA event source plugin so that `meta.uuid` is set as a flat key readable by ansible-rulebook. The SQS `MessageId` is now validated as a proper RFC 4122 UUID, falling back to a deterministic UUID5 when it is invalid (PR #3034). ... --- ## Ansible & Kubernetes — Automate K8s with Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-kubernetes-k8s-automation-playbook-guide Description: Use Ansible to manage Kubernetes clusters: deploy pods, services, and Helm charts with kubernetes.core.k8s. Complete playbook examples for K8s automation. ## Introduction Ansible and Kubernetes are complementary: Kubernetes orchestrates containers at runtime, while Ansible automates the infrastructure around it — cluster provisioning, application deployment, config management, and Day 2 operations. The `kubernetes.core` collection provides modules to manage any Kubernetes resource directly from Ansible playbooks. ## Prerequisites Install the `kubernetes.core` collection and Python dependencies: [code example] Verify: [code example] ## Authentication Ansible connects to your cluster using the same kubeconfig as `kubectl`: [code example] ### Explicit kubeconfig [code example] ### In-cluster Authentication (Running Inside K8s) [code example] ## kubernetes.core.k8s Module The main module — create, update, and delete any Kubernetes resource: ### Create a Namespace [code example] ### Deploy an Application [code example] ### Load from YAML Files [code example] ## Query Resources with k8s_info [code example] ## Manage Secrets [code example] ## Helm Charts with Ansible [code example] ## Wait for Resources [code example] ## Rolling Updates [code example] ## Delete Resources [code example] ## Ansible vs kubectl vs Helm | Feature | Ansible + k8s | kubectl | Helm | |---------|--------------|---------|------| | Idempotent | ✅ Built-in | ❌ `apply` only | ✅ | | Templating | ✅ Jinja2 + vars | ❌ Basic | ✅ Go templates | | Multi-cluster | ✅ Easy with vars | Manual context switch | Manual | | Non-K8s resources | ... --- ## Ansible + Datadog — Deploy Monitoring Agents and APM URL: https://www.ansiblebyexample.com/articles/ansible-datadog-monitoring-apm-integration Description: Deploy Datadog agents with Ansible. Configure monitoring, APM tracing, log collection, custom checks, dashboards, and alerting across your infrastructure. # Ansible + Datadog — Deploy Monitoring Agents and APM ## Introduction Datadog is one of the most popular cloud monitoring platforms, providing infrastructure monitoring, APM (Application Performance Monitoring), log management, and custom metrics. Deploying and configuring Datadog agents manually across hundreds of servers is tedious — Ansible automates the entire process, from agent installation to integration configuration. ## Install the Datadog Ansible Collection [code example] ## Basic Agent Deployment [code example] ## Custom Agent Configuration [code example] ## Log Collection [code example] ## APM Tracing Setup [code example] [code example] ## Custom Checks [code example] ## Monitor and Alert Configuration [code example] ## Multi-Environment Deployment [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Prometheus Grafana Integration - Ansible Nagios Monitoring - Ansible Fluent Bit Log Forwarding - Ansible Rsyslog Centralized Logging - Ansible Vault Encrypt Decrypt ## Conclusion The Datadog Ansible collection makes it straightforward to deploy monitoring agents, configure integrations, set up log collection, and enable APM tracing across your entire infrastructure. Use Ansible Vault for API keys, group_vars for environment-specific config, and custom checks for application-specific metrics. --- ## Ansible + Envoy Proxy — Deploy and Configure L7 Proxy URL: https://www.ansiblebyexample.com/articles/ansible-envoy-proxy-service-mesh-configuration Description: Deploy Envoy proxy with Ansible. Configure listeners, clusters, routes, TLS termination, rate limiting, and observability for microservices and API. # Ansible + Envoy Proxy — Deploy and Configure L7 Proxy ## Introduction Envoy is a high-performance L7 proxy designed for microservices architectures. It powers service meshes like Istio and is widely used as an API gateway, sidecar proxy, and edge proxy. Deploying Envoy with Ansible gives you repeatable, version-controlled proxy configuration across your infrastructure. ## Install Envoy [code example] ## Envoy Configuration Template [code example] ## TLS Termination [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Traefik Reverse Proxy - Ansible HAProxy Load Balancer - Ansible Nginx Web Server - Ansible Istio Service Mesh - Ansible Let's Encrypt TLS ## Conclusion Envoy's powerful L7 proxy features — routing, load balancing, TLS, health checking, and observability — become fully automated with Ansible. Use Jinja2 templates for dynamic configuration, handlers for zero-downtime reloads, and the admin API for health verification. This pattern scales from a single edge proxy to a fleet of sidecar proxies. --- ## Ansible + Flux — GitOps Kubernetes Deployments URL: https://www.ansiblebyexample.com/articles/ansible-flux-gitops-kubernetes-deployment Description: Bootstrap and manage Flux CD GitOps toolkit on Kubernetes with Ansible. Configure Git repositories, Kustomizations, HelmReleases, image automation. # Ansible + Flux — GitOps Kubernetes Deployments ## Introduction Flux CD is a CNCF graduated GitOps toolkit for Kubernetes. It continuously reconciles your cluster state with declarations in Git — when you push a change to your repository, Flux automatically applies it to the cluster. Managing Flux with Ansible lets you bootstrap multiple clusters, configure Git sources, and set up deployment pipelines as code. ## Prerequisites [code example] ## Bootstrap Flux with Ansible [code example] ## Configure Git Sources [code example] ## Deploy Applications with Kustomization [code example] ## HelmRelease Deployments [code example] ## Multi-Cluster Setup [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Kubernetes Guide - Ansible Helm Chart Deployments - Ansible CI/CD with GitHub Actions - Ansible GitLab CI/CD Integration - Ansible Istio Service Mesh ## Conclusion Ansible + Flux creates a powerful GitOps pipeline: use Ansible to bootstrap and configure Flux across clusters, then let Flux continuously reconcile your desired state from Git. This combination gives you infrastructure-as-code provisioning (Ansible) plus continuous delivery (Flux) in a single workflow. ## Further reading To go deeper, Ansible for Kubernetes by Example expands on these patterns in production. --- ## Ansible + Foreman/Satellite — Server Provisioning URL: https://www.ansiblebyexample.com/articles/ansible-foreman-satellite-server-provisioning Description: Integrate Ansible with Foreman and Red Hat Satellite for server provisioning. Dynamic inventory, host registration, content management, Puppet. # Ansible + Foreman/Satellite — Server Provisioning ## Introduction Foreman (and its downstream Red Hat Satellite) is a lifecycle management platform for provisioning, configuring, and managing physical and virtual servers. Ansible integrates with Foreman in two key ways: using Foreman as a dynamic inventory source, and using Ansible to automate Foreman itself. ## Dynamic Inventory from Foreman ### Install the Collection [code example] ### Configure Foreman Inventory [code example] ### Test Dynamic Inventory [code example] ## Manage Foreman with Ansible ### Create Host Groups [code example] ### Content Management (Satellite) [code example] ### Provision Hosts [code example] ## Troubleshooting [code example] ## Related Articles - Ansible VMware vSphere Automation - Ansible AWS Cloud Automation - Ansible Dynamic Inventory Plugins - Ansible Automation Platform - Ansible Kickstart Provisioning ## Conclusion Foreman/Satellite + Ansible creates a complete lifecycle management pipeline: provision servers through Foreman's UI or API, use Foreman's dynamic inventory to discover hosts in Ansible, and manage content views and host groups programmatically. The theforeman.foreman collection provides modules for every Foreman API endpoint. --- ## Ansible + GitLab CI/CD — Automate Deployments with Pipelines URL: https://www.ansiblebyexample.com/articles/ansible-gitlab-ci-cd-pipeline-integration Description: Integrate Ansible with GitLab CI/CD pipelines. Deploy infrastructure, run playbooks in stages, manage secrets with Vault, and implement rolling. # Ansible + GitLab CI/CD — Automate Deployments with Pipelines ## Introduction GitLab CI/CD is one of the most popular platforms for automating software delivery. Combining GitLab pipelines with Ansible creates a powerful deployment workflow: Git push triggers a pipeline that runs Ansible playbooks to configure infrastructure, deploy applications, and verify results. This guide covers the complete integration — from basic pipeline setup to advanced patterns with Ansible Vault secrets, rolling deployments, and multi-environment promotion. ## Basic Pipeline Setup ### .gitlab-ci.yml \`\`\`yaml --- stages: - lint - test - deploy-staging - verify-staging - deploy-production variables: ANSIBLE_HOST_KEY_CHECKING: "False" ANSIBLE_FORCE_COLOR: "True" PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache" cache: paths: - .pip-cache/ - venv/ # Base job template .ansible-base: image: python:3.12-slim before_script: - python -m venv venv - source venv/bin/activate - pip install ansible-core ansible-lint pytest-testinfra - ansible --version - ansible-galaxy install -r requirements.yml lint: extends: .ansible-base stage: lint script: - ansible-lint playbooks/ - ansible-playbook playbooks/site.yml --syntax-check test: extends: .ansible-base stage: test script: - ansible-playbook playbooks/site.yml --check --diff -i inventories/staging/hosts deploy-staging: extends: .ansible-base stage: deploy-staging script: ... --- ## Ansible + Grafana Loki — Deploy Log Aggregation URL: https://www.ansiblebyexample.com/articles/ansible-grafana-loki-log-aggregation Description: Deploy Grafana Loki with Ansible for log aggregation. Configure Promtail agents, storage backends, retention policies, LogQL queries, and Grafana. # Ansible + Grafana Loki — Deploy Log Aggregation ## Introduction Grafana Loki is a horizontally scalable log aggregation system inspired by Prometheus. Unlike Elasticsearch, Loki indexes only labels (not full text), making it significantly cheaper to operate at scale. Combined with Promtail for log collection and Grafana for visualization, it forms a lightweight but powerful logging stack. ## Deploy Loki Server [code example] ## Loki Configuration Template [code example] ## Deploy Promtail Agents [code example] ## Promtail Configuration [code example] ## LogQL Query Examples [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Fluent Bit Log Forwarding - Ansible Rsyslog Centralized Logging - Ansible Prometheus Grafana - Ansible Elasticsearch Cluster - Ansible Datadog Monitoring ## Conclusion Loki + Promtail + Grafana provides a cost-effective alternative to the ELK stack. Ansible automates the full deployment — Loki servers with retention policies, Promtail agents with per-role scrape configs, and Grafana data source configuration. The label-based indexing means you get fast queries at a fraction of the storage cost. --- ## Ansible + InSpec — Compliance Testing for Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-inspec-compliance-testing-infrastructure Description: Validate infrastructure compliance with Chef InSpec and Ansible. CIS benchmarks, STIG profiles, custom controls, kitchen-ansible testing, and audit. # Ansible + InSpec — Compliance Testing for Infrastructure ## Introduction Chef InSpec is an open-source compliance testing framework that verifies infrastructure state against security policies. While Ansible configures systems, InSpec validates that the configuration is correct — checking file permissions, running services, open ports, kernel parameters, and compliance with CIS benchmarks or STIG profiles. Together, Ansible + InSpec creates a configure → verify loop for compliance automation. ## Install InSpec [code example] ## Basic InSpec Profile [code example] ## Run InSpec Against Ansible-Managed Hosts [code example] ## CIS Benchmark Profile [code example] ## Configure → Verify Workflow [code example] ## Supermarket Profiles [code example] ## CI/CD Integration [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Compliance as Code - Ansible + Testinfra - Ansible Molecule Testing - Ansible SSH Hardening - Ansible assert Module ## Conclusion InSpec complements Ansible perfectly — Ansible enforces desired state, InSpec validates it. Use community CIS/STIG profiles for industry-standard compliance checks, custom controls for application-specific requirements, and CI/CD pipelines for continuous compliance monitoring. --- ## Ansible + Istio — Deploy Service Mesh on Kubernetes URL: https://www.ansiblebyexample.com/articles/ansible-istio-service-mesh-kubernetes Description: Deploy and configure Istio service mesh on Kubernetes with Ansible. Traffic management, mTLS, observability, canary deployments, and VirtualService. # Ansible + Istio — Deploy Service Mesh on Kubernetes ## Introduction Istio is the most widely adopted service mesh for Kubernetes, providing traffic management, security (mTLS), and observability without modifying application code. Managing Istio with Ansible brings repeatability and version control to service mesh configuration — deploy Istio, configure routing rules, enable mTLS, and set up monitoring with playbooks. ## Prerequisites \`\`\`yaml # requirements.yml --- collections: - name: kubernetes.core version: ">=3.0.0" - name: community.general \`\`\` \`\`\`bash pip install kubernetes openshift ansible-galaxy collection install -r requirements.yml \`\`\` ## Install Istio with Ansible ### Download and Install istioctl \`\`\`yaml --- - name: Install Istio on Kubernetes hosts: localhost connection: local vars: istio_version: "1.24.0" istio_profile: "default" # minimal, default, demo, production tasks: - name: Download istioctl ansible.builtin.get_url: url: "https://github.com/istio/istio/releases/download/{{ istio_version }}/istioctl-{{ istio_version }}-linux-amd64.tar.gz" dest: "/tmp/istioctl.tar.gz" - name: Extract istioctl ansible.builtin.unarchive: src: "/tmp/istioctl.tar.gz" dest: /usr/local/bin/ remote_src: true - name: Install Istio with profile ansible.builtin.command: cmd: "istioctl install --set profile={{ istio_profile }} -y" register: istio_ins... --- ## Ansible + Packer — Build Machine Images Automatically URL: https://www.ansiblebyexample.com/articles/ansible-packer-machine-image-automation Description: Build machine images with Packer and Ansible provisioner. Create AMIs, Docker images, Vagrant boxes, and VMware templates with automated Ansible. # Ansible + Packer — Build Machine Images Automatically ## Introduction HashiCorp Packer automates machine image creation for multiple platforms (AWS AMIs, Docker images, VMware templates, Vagrant boxes). The Ansible provisioner lets you use existing Ansible playbooks to configure images during the build — no need to rewrite configuration as shell scripts or Dockerfiles. ## Install Packer [code example] ## Basic Packer Template with Ansible [code example] ## Ansible Playbook for Image Configuration [code example] ## Docker Image with Ansible [code example] ## Build Commands [code example] ## Troubleshooting [code example] ## Related Articles - Ansible + Terraform - Ansible AWS Automation - Ansible VMware Templates - Ansible Docker Container Management ## Conclusion Packer + Ansible = immutable infrastructure done right. Packer handles the image lifecycle (build, test, publish) while Ansible handles configuration. Reuse your existing Ansible roles and playbooks without rewriting them as shell scripts. --- ## Ansible + Serverspec — Test Infrastructure Code URL: https://www.ansiblebyexample.com/articles/ansible-serverspec-infrastructure-testing Description: Test Ansible-managed infrastructure with Serverspec. Write RSpec tests to verify packages, services, ports, files, and configurations are correctly. # Ansible + Serverspec — Test Infrastructure Code ## Introduction Serverspec is a Ruby-based testing framework that verifies your server configuration matches expectations. Combined with Ansible, it creates a test-driven infrastructure workflow: Ansible provisions servers, Serverspec validates the results. This catches configuration drift, broken playbooks, and missing dependencies before they hit production. ## Install Serverspec [code example] ## Directory Structure [code example] ## Write Serverspec Tests [code example] ## Test Database Servers [code example] ## Test Security Hardening [code example] ## Spec Helper [code example] ## Integrate with Ansible Workflow [code example] ## CI/CD Pipeline [code example] ## Run Tests [code example] ## Serverspec vs Other Testing Tools | Feature | Serverspec | Testinfra | InSpec | |---------|------------|-----------|--------| | Language | Ruby/RSpec | Python/pytest | Ruby DSL | | License | MIT | Apache 2.0 | Apache 2.0 | | Compliance | Basic | Basic | Built-in profiles | | Ansible fit | Good | Excellent | Good | ## Troubleshooting [code example] ## Related Articles - Ansible Testinfra — Validate Infrastructure - Ansible InSpec Compliance Testing - Ansible Dry Run Check and Diff Mode - Ansible CI/CD Pipeline Integration ## Conclusion Serverspec brings TDD to infrastructure. Write tests first, run Ansible to converge, validate with Serverspec. This catches drift and broken playbooks before they reach product... --- ## Ansible + Terraform — Enterprise Infrastructure as Code Pipeline URL: https://www.ansiblebyexample.com/articles/ansible-terraform-enterprise-infrastructure-as-code-pipeline Description: Build a production IaC pipeline combining Terraform for provisioning and Ansible for configuration. Integrate with CI/CD, manage state, and automate the. ## Introduction Terraform provisions infrastructure; Ansible configures it. This isn't a versus — it's a pipeline. Terraform creates the VMs, networks, load balancers, and DNS records. Ansible installs packages, deploys applications, hardens security, and manages ongoing configuration. Together they provide full-stack infrastructure as code, from cloud API calls to application-ready servers. This guide covers the integration patterns used in production enterprise environments. ## When to Use Which | Task | Tool | Why | |------|------|-----| | Create VPC, subnets, security groups | Terraform | Declarative cloud resource management | | Provision EC2/VM instances | Terraform | Cloud provider API, state tracking | | Install packages, configure services | Ansible | Agentless, idempotent configuration | | Deploy application code | Ansible | Rolling updates, handlers, templates | | Manage DNS records | Terraform | State-tracked, plan/apply workflow | | Rotate certificates | Ansible | Procedural workflow with handlers | | Database schema migrations | Ansible | Sequential, host-targeted execution | | Kubernetes cluster creation | Terraform | Infrastructure lifecycle | | Kubernetes app deployment | Ansible / kubectl | Configuration management | ## Architecture [code example] ## Pattern 1: Terraform Outputs → Ansible Dynamic Inventory ### Terraform Configuration [code example] ### Generate Ansible Inventory from Terraform State [code example] [code example] ### Alternative:... --- ## Ansible + Testinfra — Validate Infrastructure with Python Tests URL: https://www.ansiblebyexample.com/articles/ansible-testinfra-serverspec-validate-infrastructure Description: Test Ansible playbook results with Testinfra and pytest. Validate packages, services, files, ports, and configurations. Infrastructure testing best. # Ansible + Testinfra — Validate Infrastructure with Python Tests ## Introduction Writing Ansible playbooks is only half the job. How do you verify that your automation actually produced the desired state? Testinfra is a Python testing framework that validates infrastructure state — checking packages, services, files, ports, users, and more — using familiar pytest syntax. Combined with Molecule, Testinfra creates a complete test-driven infrastructure workflow: provision → configure → verify. ## Install Testinfra \`\`\`bash # Install testinfra with SSH backend pip install pytest-testinfra paramiko # Or with Molecule pip install molecule[docker] pytest-testinfra \`\`\` ## Basic Test Structure \`\`\`python # tests/test_webserver.py import pytest def test_nginx_is_installed(host): """Verify nginx package is installed.""" nginx = host.package("nginx") assert nginx.is_installed assert nginx.version.startswith("1.") def test_nginx_is_running(host): """Verify nginx service is running and enabled.""" nginx = host.service("nginx") assert nginx.is_running assert nginx.is_enabled def test_nginx_listening_on_port_80(host): """Verify nginx is listening on port 80.""" socket = host.socket("tcp://0.0.0.0:80") assert socket.is_listening def test_nginx_config_exists(host): """Verify nginx configuration file exists.""" config = host.file("/etc/nginx/nginx.conf") assert config.exists assert config.is_file assert config.u... --- ## Ansible 13 Upgrade — Migration Guide URL: https://www.ansiblebyexample.com/articles/upgrade-ansible-13-migration-guide-ansible-core-2-20 Description: Step-by-step guide to upgrade from Ansible 12 to Ansible 13 (ansible-core 2.20). Handle Python version changes, deprecated features, and collection updates. ## Introduction Ansible 13 ships with ansible-core 2.20, released November 2025. This major release drops support for older Python versions, removes long-deprecated features, and introduces new capabilities including play argument specs (tech preview) and third-party fact injection plugins. This guide walks you through a safe upgrade from Ansible 12 (ansible-core 2.19) to Ansible 13. ## What Changed in Ansible 13 ### Python Version Changes | Component | Ansible 12 (core 2.19) | Ansible 13 (core 2.20) | |-----------|----------------------|----------------------| | Controller (minimum) | Python 3.11 | Python 3.12 | | Controller (added) | — | Python 3.14 | | Target (minimum) | Python 3.8 | Python 3.9 | | Target (added) | — | Python 3.14 | | Dropped controller | Python 3.10 | Python 3.11 | | Dropped target | — | Python 3.8 | **This is the most impactful change.** If your Ansible controller runs Python 3.11, you must upgrade to 3.12+ before installing Ansible 13. ### Key New Features - **Play argument specs (tech preview)** — validate play-level variables with type checking - **Third-party fact injection plugins** — extend fact gathering with custom plugins - **Register projections** — selectively register parts of task results - **Updated ansible-test container images and VMs** - **Python 3.14 support** for both controller and target ### Removed Deprecated Features - `DEFAULT_TRANSPORT` no longer supports `smart` value - `vault`/`unvault` filters: `vaultid` parameter rem... --- ## Ansible 14 Community Package RC1 — What's New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-14-community-package-rc1-whats-new-and-how-to-test Description: Ansible community package 14.0.0rc1 is available for testing. New collections, ansible-core 2.20 dependency, breaking changes, and upgrade guide for. # Ansible 14 Community Package RC1 — What's New and How to Test ## Introduction Ansible community package 14.0.0rc1 has been released for testing (June 2026). This is the first release candidate for the next major version, which depends on ansible-core 2.20. If you maintain playbooks, roles, or collections, now is the time to test before the final release. ## Install the RC [code example] ## What's New ### ansible-core 2.20 Ansible 14 requires ansible-core 2.20, which brings: - **Python 3.10+ minimum** on the controller (Python 3.9 dropped) - **Python 3.7+ on managed nodes** (Python 3.6 dropped) - **Deprecated features removed** from ansible-core 2.18/2.19 cycle - **Performance improvements** in task execution and fact gathering - **New `skipped` callback behavior** (see deprecation section below) ### Collection Updates Major collection version bumps expected in Ansible 14: | Collection | Expected Version | Notable Changes | |-----------|-----------------|-----------------| | community.general | 10.x | Module removals from 9.x deprecations | | amazon.aws | 11.x | API changes, new resources | | ansible.netcommon | 9.x | Paramiko deprecation enforcement | | community.docker | 5.x | Compose v2 default | | ansible.mysql | 6.x | Replaces community.mysql | ### Breaking Changes to Watch [code example] ## Test Your Playbooks [code example] ### Automated Testing [code example] ## Upgrade Guide ### Step 1: Check Python Version [code example] ### Step 2: Update requ... --- ## Ansible 14.3.1 Released - Symlink Loop Fix in infinidat.infinibox URL: https://www.ansiblebyexample.com/articles/ansible-14-3-1-released-symlink-loop-fix-in-infinidat-infinibox Description: Ansible 14.3.1 fixes a recursive symlink loop bug in infinidat.infinibox 1.8.4 that bloated the 14.3.0 package. Upgrade details inside. # Ansible 14.3.1 Released - Symlink Loop Fix in infinidat.infinibox ## Introduction Ansible 14.3.1 is a targeted patch release of the community package, published on 2026-08-14. It follows Ansible 14.3.0 and addresses a single, specific packaging bug rather than introducing any new functionality. Anyone running 14.3.0 in production should read this before deciding whether to upgrade, since the issue affects the size and integrity of the installed package. ## What Changed From 14.3.0 Ansible 14.3.1 ships the exact same `ansible-core` version as 14.3.0, `ansible-core` 2.21.3. Only one collection was bumped compared to the previous release: | Collection | Ansible 14.3.0 | Ansible 14.3.1 | Notes | |---|---|---|---| | infinidat.infinibox | 1.8.4 | 1.8.5 | No machine-readable changelog provided by the collection maintainers | Every other collection in the bundle is unchanged between 14.3.0 and 14.3.1. ### The Bug Being Fixed The `infinidat.infinibox` 1.8.4 release included in Ansible 14.3.0 contained a recursive symlink loop inside its package tree. When `setuptools` built the sdist/wheel, it followed that loop instead of erroring out, and for unknown reasons it expanded the loop 41 levels deep before stopping. The practical result was that the Ansible 14.3.0 release ended up containing many duplicate copies of the `infinidat.infinibox` collection, inflating the package size. `infinidat.infinibox` 1.8.5, shipped in Ansible 14.3.1, is functionally identical to 1.8.4 in term... --- ## Ansible 14.4.0 Community Package - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-14-4-0-community-package-whats-new-and-how-to-test Description: Ansible 14.4.0 bumps ansible-core to 2.21.4 and updates several collections including ansible.netcommon, ansible.windows, cisco.ios. # Ansible 14.4.0 Community Package - Whats New and How to Test ## Introduction Ansible 14.4.0 has been published on PyPI, replacing the previous 14.3.1 release. This is a maintenance release: the package itself does not introduce new features, but it bundles a newer ansible-core version and bumps a set of collections to their latest available releases at the time of the build. As usual for the `ansible` community package, the actual bugfixes and improvements live inside the individual collections and inside ansible-core, not in the meta-package itself. ## Whats New ### ansible-core bump Ansible 14.4.0 ships **ansible-core 2.21.4**, up from **ansible-core 2.21.3** in the previous release (14.3.1). The detailed list of ansible-core changes is published in the combined changelog on the `ansible-build-data` repository; no ansible-core changes were singled out in the release summary provided for this release. ### Changed collections Compared to 14.3.1, the following collections were bumped in 14.4.0. Unless explicitly noted, the individual bugfixes for each collection are listed in the combined changelog. | Collection | Ansible 14.3.1 | Ansible 14.4.0 | Notes | |---|---|---|---| | ansible.netcommon | 8.6.1 | 8.6.2 | | | ansible.windows | 3.7.0 | 3.8.0 | | | cisco.ios | 11.5.0 | 11.5.1 | | | cisco.iosxr | 12.4.0 | 12.4.2 | | | cisco.meraki | 2.25.0 | 2.25.1 | The collection did not have a changelog in this version | | cloudscale_ch.cloud | 2.5.3 | 2.7.0 | | | community.cryp... --- ## Ansible 14.4.0 Released - Ansible-Core 2.21.4 and Collection Bumps URL: https://www.ansiblebyexample.com/articles/ansible-14-4-0-released-ansible-core-2-21-4-and-collection-bumps Description: Ansible 14.4.0 ships ansible-core 2.21.4 and updates ansible.netcommon, ansible.windows, cisco.ios, cisco.iosxr, cloudscale_ch.cloud and more. # Ansible 14.4.0 Released - Ansible-Core 2.21.4 and Collection Bumps ## Introduction Ansible 14.4.0 has been published on PyPI, replacing the previous 14.3.1 release. As is typical for a point release of the community `ansible` package, this version does not introduce new features of its own: it is a coordinated bump of `ansible-core` plus a set of included collections, each pinned to a newer upstream release that carries its own bugfixes. The release notes come from the `ansible-community/ansible-build-data` repository, dated 2026-09-08. ## Whats New ### Ansible-Core Update Ansible 14.4.0 bundles `ansible-core` 2.21.4, up from 2.21.3 in Ansible 14.3.1. The full set of `ansible-core` changes for this point release is documented in the combined changelog referenced by the build-data repository; no changelog entries specific to 2.21.4 were broken out separately in the notes provided. ### Changed Collections The table below lists every collection whose version changed between Ansible 14.3.1 and 14.4.0. Unless otherwise noted, the individual bugfixes for each bump are reported in the combined changelog rather than duplicated here. | Collection | Ansible 14.3.1 | Ansible 14.4.0 | Notes | |---|---|---|---| | ansible.netcommon | 8.6.1 | 8.6.2 | | | ansible.windows | 3.7.0 | 3.8.0 | | | cisco.ios | 11.5.0 | 11.5.1 | | | cisco.iosxr | 12.4.0 | 12.4.2 | | | cisco.meraki | 2.25.0 | 2.25.1 | Collection did not ship a changelog for this version | | cloudscale_ch.cloud | 2.5.3 | 2.... --- ## Ansible 14.5.0 Community Package - What's New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-14-5-0-community-package-what-s-new-and-how-to-test Description: Ansible 14.5.0 ships ansible-core 2.21.5 plus bumps to ansible.netcommon, ansible.utils, arista.eos, cisco.ios and cisco.iosxr. Details and install steps. # Ansible 14.5.0 Community Package - What's New and How to Test ## Introduction Ansible 14.5.0 is now available on PyPI. This release is a dependency-bump release of the community package: the overall Ansible 14 series stays the same, but `ansible-core` moves from 2.21.4 to 2.21.5, and a handful of networking-related collections are updated to newer upstream versions. No collections were removed or added to the package in this release, and no new major features are introduced at the community package level - all functional changes live in the bumped collections and in ansible-core itself. ## What's New ### ansible-core bump Ansible 14.5.0 contains **ansible-core 2.21.5**, up from 2.21.4 in Ansible 14.4.0. The fixes shipped in this ansible-core point release are covered in the combined changelog published alongside the release and are not broken out separately in the `ansible-build-data` notes for this version. ### Changed Collections Compared to Ansible 14.4.0, the following collections were bumped in Ansible 14.5.0: | Collection | Ansible 14.4.0 | Ansible 14.5.0 | Notes | |---|---|---|---| | ansible.netcommon | 8.6.2 | 8.7.1 | See combined changelog | | ansible.utils | 6.1.0 | 6.1.1 | See combined changelog | | arista.eos | 12.2.0 | 12.3.0 | See combined changelog | | cisco.ios | 11.5.1 | 11.6.0 | See combined changelog | | cisco.iosxr | 12.4.2 | 12.5.0 | See combined changelog | As with most 14.x point releases, these bumps are primarily bugfix-driven on the networ... --- ## Ansible 2.16.0: Major Enhancements and Updates URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-16-0 Description: Ansible 2.16.0 introduces support for Python 3.12, new remote options, and improved CLI functionality. This release also includes deprecated feature. ## Introduction Ansible, the open-source automation platform, has released a new version with numerous enhancements, bug fixes, and security updates. Ansible has become a fundamental tool for managing IT infrastructure and applications, streamlining workflows, and maintaining infrastructure as code (IaC) principles. ## Ansible 2.16 Let’s delve into the key changes introduced in this release: Important Changes: - Drop Python 3.5 support for module execution. - Drop Python 3.9 support for the controller. - Add Python 3.12 support. - Preserve display context when proxying display over the queue. - Update `TaskExecutor` to not unnecessarily establish persistent `ansible-connection` when not needed. ### Ansible Enhancements - Collection Path The INI config option “collections_paths” has been deprecated; please use the singular form “collections_path” instead. Additionally, the environment variable “ANSIBLE_COLLECTIONS_PATHS” is now deprecated, and you should use the singular form “ANSIBLE_COLLECTIONS_PATH” instead. - Removed Support for Windows Server 2012 and 2012 R2 as Microsoft’s support end of life on October 10th, 2023. - Remote Support New remotes have been added, including Alpine 3.18, Fedora 38, Fedora 38 container, FreeBSD 13.2 remote, RHEL 8.8 remotes, and RHEL 9.2 remotes, expanding compatibility across various platforms. - Python 3.12 Support Support for testing with Python 3.12 has been introduced, keeping Ansible up-to-date with the latest Python version. - ... --- ## Ansible 2.17.0-rc1: Elevating Automation with ‘Gallows Pole’ URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-17-0-rc1 Description: Ansible 2.17.0-rc1, codenamed "Gallows Pole," introduces critical updates including phasing out support for older Python versions, tightened security. ## Introduction In the rapidly evolving world of IT, efficiency and security are not just aspirations but necessities. Ansible, a stalwart in the realm of automation, has introduced its latest version, 2.17.0-rc1, aptly nicknamed 'Gallows Pole.' This release marks a significant stride forward in the Ansible journey, promising enhancements that cater to the ever-growing demands for faster, more secure, and more efficient IT operations. ## What’s New in Ansible 2.17.0-rc1? **Python Compatibility and Enhancements** One of the standout features of the 'Gallows Pole' release is its shift in Python compatibility. Ansible has phased out support for Python 2.7 and 3.6, transitioning entirely to Python 3.7 and newer versions. This move not only streamlines development and reduces overhead but also leverages the newer Python features and optimizations, enhancing Ansible's performance and security posture. **Security Tightening** Security in automation tools is paramount, given their access and control over IT environments. Ansible 2.17 addresses several key vulnerabilities, ensuring that the automation platform does not become a liability. Noteworthy improvements include hardened templating to prevent injection attacks and enhanced logging capabilities that adhere to strict security standards without compromising on performance. **User Experience and Functionality Improvements** Ansible 2.17.0-rc1 has introduced several enhancements aimed at improving the user experience and expan... --- ## Ansible 2022 Highlights: New Releases & Innovations URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-year-2022-recap-merry-christmas-and-happy-automation-year Description: Discover Ansible's major updates from 2022, including new releases, enhanced enterprise features, and community tools. Exciting innovations await in 2023! # Ansible 2022 Highlights: New Releases & Innovations ## Introduction Ansible 2022 Highlights: New Releases & Innovations. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible 2022 Highlights: New Releases & Innovations requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version contro... --- ## Ansible AAP — Enterprise Guide URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-aap-enterprise-guide Description: Understand Ansible Automation Platform (formerly Tower/AWX). Job templates, workflows, inventories, credentials, RBAC, and enterprise automation at scale. ## Introduction Ansible Automation Platform (AAP) is Red Hat's enterprise solution for scaling Ansible across organizations. It provides a web UI, REST API, RBAC, credential management, job scheduling, workflow orchestration, and audit logging — everything CLI Ansible lacks for team and enterprise use. ## AAP Components | Component | Purpose | |-----------|---------| | **Automation Controller** | Web UI + API (formerly Tower) | | **Automation Hub** | Private content repository (roles, collections) | | **Event-Driven Ansible** | React to events automatically | | **Automation Mesh** | Distributed execution across networks | | **Insights** | Analytics and recommendations | ## AAP vs AWX | Feature | AWX (Open Source) | AAP (Enterprise) | |---------|-------------------|-------------------| | Cost | Free | Subscription | | Support | Community | Red Hat | | Automation Hub | No | Yes | | Automation Mesh | No | Yes | | Event-Driven | No | Yes | | Insights | No | Yes | | Certifications | No | Yes | | SLA | No | Yes | AWX is the upstream project. AAP is the supported, enterprise-hardened product. ## Key Concepts ### Job Templates A job template wraps a playbook with everything needed to run it: - **Playbook** — which playbook to run - **Inventory** — which hosts to target - **Credentials** — SSH keys, cloud credentials, vault passwords - **Extra Variables** — runtime parameters - **Limit** — subset of inventory - **Tags** — run specific tags - **Verbosity** — output level [co... --- ## Ansible AAP 2.6 — Architecture URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-6-architecture-and-components Description: Understand Ansible Automation Platform 2.6 architecture — Platform Gateway, Automation Controller, Hub, Event-Driven Ansible, Automation Mesh, Execution. ## Introduction Ansible Automation Platform (AAP) 2.6 is Red Hat's enterprise automation solution, built from a set of integrated components that handle everything from content management to event-driven automation. The most significant architectural change in AAP 2.x is the **Platform Gateway** — a unified entry point that fronts all platform services. This article covers every component, how they interact, deployment topologies, and when to use each piece. ## Architecture Overview [code example] ## Platform Gateway The Platform Gateway is the most important architectural change in AAP 2.x. It provides: - **Single entry point** — one URL for all platform services - **Unified authentication** — SSO across Controller, Hub, and EDA - **Authorization** — centralized RBAC and organization management - **Platform UI** — unified dashboard for all components - **Service routing** — proxies requests to the appropriate backend ### How It Works [code example] Before Platform Gateway, each component had its own URL and login. Now users authenticate once and access everything through a single interface. ### Key Configuration [code example] ## Automation Controller The traditional control plane for Ansible automation. Handles: | Capability | Description | |---|---| | **Job Templates** | Define what playbook runs on which inventory with which credentials | | **Workflows** | Chain multiple job templates with conditional logic | | **Inventories** | Static and dynamic inventory ... --- ## Ansible AAP Containerized Install — RHEL URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-containerized-installation Description: Set up containerized Ansible Automation Platform on RHEL using Podman. Covers architecture, component setup, configuration, and post-install troubleshooting. ## Introduction Since September 2023, Red Hat offers a containerized version of the Ansible Automation Platform (AAP). This deployment model runs the automation controller, automation hub, and Event-Driven Ansible controller as containers on Red Hat Enterprise Linux (RHEL) using Podman — without requiring Kubernetes. This article covers the architecture, benefits, setup process, troubleshooting, and how it compares to the traditional RPM-based installation. - Containerized Ansible Automation Platform Update 2024 ## Architecture Overview The containerized AAP runs each component as an isolated Podman container: [code example] ### Components | Component | Default Port | Purpose | |---|---|---| | Automation Controller | 443 | Job execution, workflow orchestration, RBAC | | Automation Hub | 444 | Collection hosting, content management | | Event-Driven Ansible (EDA) | 445 | Event-driven automation, rulebooks | | PostgreSQL | 5432 | Shared database backend | | Redis | 6379 | Cache and message broker | ## Why Containerized? ### Problems with Traditional RPM Installation The RPM-based installation had growing complexity: - Multiple interdependent RPM packages across components - System-level Python dependency conflicts - Complex upgrade procedures affecting the entire OS - Difficulty isolating component failures ### Benefits of Containerization **1. Simplified Installation** The installer uses an Ansible playbook that pulls container images and configures Podman: [code ... --- ## Ansible AAP on OpenShift — Operator URL: https://www.ansiblebyexample.com/articles/install-ansible-automation-platform-in-red-hat-ansible-openshift-platform-operator-via-operator Description: Step-by-step guide to installing Red Hat Ansible Automation Platform (AAP) on OpenShift Container Platform using the AAP Operator — from OperatorHub to. ## Introduction The Ansible Automation Platform (AAP) Operator provides a cloud-native way to deploy and manage AAP on Red Hat OpenShift Container Platform (OCP) 4.9+. The operator handles the full lifecycle — installation, upgrades, backups, and restores — for both the Automation Controller and Automation Hub. ## Prerequisites - Red Hat OpenShift Container Platform 4.9 or later - Cluster admin access - Red Hat subscription (or 60-day trial) - Minimum resources: 4 vCPU, 16 GB RAM for the Controller ## Step 1: Install the AAP Operator ### Via OperatorHub (Web Console) 1. Log in to the OpenShift web console 2. Navigate to **Operators → OperatorHub** 3. Search for **"Ansible Automation Platform"** 4. Click **Install** ### Operator Configuration | Parameter | Description | Recommendation | |-----------|-------------|----------------| | **Update Channel** | AAP version to install | Latest stable (e.g., `stable-2.4`) | | **Installation Mode** | Cluster-wide or namespace | `All namespaces` for production | | **Installed Namespace** | Target namespace | Default: `aap` | | **Update Approval** | Manual or automatic | `Manual` for production | ### Via CLI [code example] Verify the operator is running: [code example] ## Step 2: Deploy Automation Controller [code example] Create the admin password secret: [code example] Apply the Controller CR: [code example] ## Step 3: Deploy Automation Hub [code example] [code example] ## Step 4: Access the Dashboard [code example... --- ## Ansible acl Module — Manage File Access Control Lists URL: https://www.ansiblebyexample.com/articles/ansible-acl-module-manage-file-access-control-lists Description: Ansible acl Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible acl Module — Manage File Access Control Lists ## Introduction Manage File Access Control Lists. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible acl Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible Action Plugins — Custom Task Execution Logic URL: https://www.ansiblebyexample.com/articles/ansible-action-plugins-custom-task-execution Description: Build custom Ansible action plugins to extend task behavior. Action plugin architecture, module wrapper patterns, connection handling, and practical. # Ansible Action Plugins — Custom Task Execution Logic ## Introduction Action plugins run on the controller node and execute before the module runs on the target host. They control how tasks are dispatched — handling file transfers, template rendering, connection management, and module invocation. The built-in `copy`, `template`, `fetch`, and `script` modules are all implemented as action plugins. When you need behavior that happens on the controller (not the target), or need to modify how a module is called, action plugins are the right tool. ## How Action Plugins Work [code example] ## Plugin Directory Structure [code example] Or in a role: [code example] ## Basic Action Plugin [code example] ## Using Built-In Methods ### Key ActionBase Methods [code example] ## Action Plugin with Check Mode [code example] ## Multi-Host Coordination [code example] ## Testing Action Plugins [code example] ## Troubleshooting **Plugin not found:** [code example] **Module vs action plugin confusion:** - Action plugin filename must match the module name - If `my_module` module exists, `my_module.py` action plugin wraps it automatically ## Related Articles - Ansible Custom Modules - Ansible Callback Plugins - Ansible Filter Plugins - Ansible Connection Plugins - Ansible Cache Plugins ## Conclusion Action plugins give you full control over task execution on the controller side. Use them when you need to validate before deploying, coordinate across hosts, or implement com... --- ## Ansible Ad Hoc Commands — Run Tasks Without Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-ad-hoc-commands-run-tasks-without-playbooks Description: Run quick Ansible tasks from the command line without writing playbooks. Ad hoc commands for ping, shell, copy, package, service, and user management. # Ansible Ad Hoc Commands — Run Tasks Without Playbooks ## Introduction Ad hoc commands let you run single Ansible tasks from the command line without writing a playbook. They're perfect for quick checks, one-off changes, and troubleshooting. Think of them as the `ssh` command on steroids — run any module against any number of hosts in parallel. ## Syntax [code example] | Component | Description | |-----------|-------------| | `pattern` | Host or group to target (`all`, `webservers`, `db01`) | | `-m` | Module name (default: `command`) | | `-a` | Module arguments | | `-i` | Inventory file | | `-b` | Become (sudo) | | `-u` | Remote user | | `-k` | Ask for SSH password | | `-K` | Ask for become password | | `--limit` | Further limit hosts | | `-f` | Forks (parallelism, default: 5) | | `-o` | One-line condensed output | | `--check` | Dry run | ## Connectivity Check [code example] ## Run Shell Commands [code example] ## File Operations [code example] ## Package Management [code example] ## Service Management [code example] ## User Management [code example] ## Gathering Facts [code example] ## Parallelism and Limiting [code example] ## Output Formats [code example] ## Dry Run and Diff [code example] ## Common Patterns [code example] ## Ad Hoc vs Playbooks | Feature | Ad Hoc | Playbooks | |---------|--------|-----------| | Speed | Immediate | Write first | | Repeatability | Manual | Automated | | Complexity | Single task | Multi-task | | Version control ... --- ## Ansible add_host — Create Hosts Dynamically During Play URL: https://www.ansiblebyexample.com/articles/ansible-add-host-create-hosts-dynamically-during-play Description: Use ansible.builtin.add_host to add hosts to inventory at runtime. Register new cloud instances, build dynamic groups, and chain plays across. # Ansible add_host — Create Hosts Dynamically During Play ## Introduction `ansible.builtin.add_host` adds hosts to the in-memory inventory during playbook execution. This is essential when you provision infrastructure first (cloud instances, containers, VMs) and then need to configure it in the same playbook run. Without `add_host`, you'd need separate inventory files and multiple playbook runs. ## Basic Usage [code example] ## Cloud Provisioning Pattern [code example] ## Docker Container Pattern [code example] ## Setting Host Variables [code example] ## Multiple Groups [code example] ## Conditional Registration [code example] ## add_host with run_once [code example] ## Key Behaviors | Behavior | Detail | |----------|--------| | Runs on | Controller (always, even with `delegate_to`) | | Changed status | Always reports "changed" (use `changed_when: false`) | | Scope | Current playbook run only (not persisted) | | Duplicate names | Merges variables, adds to additional groups | | Available when | Immediately — next play can target the host | ## Troubleshooting | Issue | Solution | |-------|----------| | Host unreachable in next play | Check `ansible_host` IP and SSH access; add `wait_for` for port 22 | | Duplicate "changed" noise | Add `changed_when: false` | | Host not in expected group | Group names are case-sensitive; check spelling | | Variables not available | Access via `hostvars[hostname].variable_name` | | SSH key rejected | Set `ansible_ssh_private_k... --- ## Ansible Advanced Nuclear Technology Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/ansible-advanced-nuclear-technology-infrastructure Description: Automate nuclear technology infrastructure with Ansible. Manage reactor monitoring systems, safety interlocks, regulatory compliance, and SMR deployment. ## Introduction Advanced nuclear technology — particularly Small Modular Reactors (SMRs) and next-gen fission designs — is experiencing a renaissance driven by AI data center power demands and decarbonization goals. These facilities require rigorous IT infrastructure: safety monitoring systems, regulatory compliance automation, air-gapped network management, and multi-site coordination. Ansible automates the non-reactor IT/OT infrastructure surrounding nuclear operations. ## Nuclear IT Infrastructure Stack [code example] ## Safety Monitoring Infrastructure [code example] ## Air-Gapped Network Management [code example] ## Regulatory Compliance Automation [code example] ## Multi-Site Fleet Management [code example] ## Related Articles - Ansible Autonomous Industrial Systems - Ansible Preemptive Cybersecurity - Ansible Confidential Computing - Ansible at Scale ## Conclusion Nuclear technology infrastructure demands the highest standards of safety, security, and compliance. Ansible automates the IT/OT infrastructure surrounding nuclear operations: safety monitoring systems with triple redundancy, air-gapped network management with data diodes, NRC regulatory compliance automation, and multi-site SMR fleet management. The key principle is defense in depth — Ansible enforces network segmentation, automates compliance verification, and maintains permanent audit trails required by nuclear regulators. As SMRs proliferate to power AI data centers and decarbonize energy g... --- ## Ansible Advanced Techniques — Level Up Your Automation URL: https://www.ansiblebyexample.com/articles/ansible-advanced-techniques-level-up-automation Description: Advanced Ansible patterns: custom modules, plugins, dynamic includes, complex data manipulation, delegation, error handling, and performance optimization. ## Introduction You know the basics — playbooks, roles, variables, handlers. Now level up with advanced patterns that make your automation more powerful, maintainable, and resilient. These techniques are used in production environments managing thousands of hosts. ## Custom Modules Write Python modules when no existing module fits: [code example] [code example] ## Custom Filter Plugins [code example] [code example] ## Complex Data Manipulation ### Transform and Merge [code example] ### Complex Conditionals [code example] ### JSON Query (JMESPath) [code example] ## Advanced Delegation [code example] ## Advanced Error Handling [code example] ## Dynamic Role Selection [code example] ## Custom Facts [code example] ## Ansible Vault Advanced [code example] ## Meta Tasks [code example] ## Performance Patterns [code example] ## Testing Advanced Playbooks [code example] ## Related Articles - Ansible Best Practices - Ansible Filter Plugins - Ansible Error Handling - Ansible Performance Guide - Ansible Dynamic Inventory ## Conclusion Advanced Ansible means: custom modules for unique needs, filter plugins for data transformation, JMESPath for complex queries, block/rescue for resilient deployments, dynamic role selection for flexibility, custom facts for host metadata, and meta tasks for flow control. The key shift from beginner to advanced is moving from "tasks that run" to "automation that handles failure gracefully, scales efficiently, and is maintai... --- ## Ansible AI Content Watermarking Detection Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-ai-content-watermarking-detection-infrastructure Description: Automate AI content watermarking and detection infrastructure with Ansible. Deploy watermark injection, verification APIs, and content provenance tracking. ## Introduction As AI-generated content becomes indistinguishable from human-created content, watermarking and detection infrastructure becomes essential — for regulatory compliance, content authenticity, and trust. AI content watermarking embeds imperceptible signals in AI-generated text, images, audio, and video. Ansible automates the deployment of watermarking injection services, detection APIs, and provenance tracking systems. ## Watermarking Infrastructure [code example] ## Text Watermarking Service [code example] ## Image and Media Watermarking [code example] ## Detection and Verification API [code example] ## Compliance and Reporting [code example] ## Related Articles - Ansible Digital Provenance C2PA - Ansible AI-Native Development - Ansible Preemptive Cybersecurity - Ansible AI Infrastructure Optimization ## Conclusion AI content watermarking is moving from research to regulatory requirement. The EU AI Act mandates labeling AI-generated content by 2026. Ansible automates the infrastructure: text watermarking via distribution shift methods, image watermarking with stable signatures, C2PA content credentials for provenance, unified detection APIs, and compliance dashboards. Organizations generating or hosting AI content need this infrastructure now — before the regulations take effect. --- ## Ansible AI Supercomputing — Deploy GPU Clusters and HPC Workloads URL: https://www.ansiblebyexample.com/articles/ansible-ai-supercomputing-gpu-clusters-hpc-workloads Description: Automate AI supercomputing infrastructure with Ansible. Deploy GPU clusters, SLURM schedulers, InfiniBand networking, distributed training, and HPC. ## Introduction AI supercomputing platforms — purpose-built GPU clusters for training foundation models — are a defining 2026 infrastructure trend. Deloitte and Gartner both highlight the explosion in GPU cluster deployments. Ansible automates the full stack: bare-metal GPU provisioning, SLURM job scheduling, InfiniBand fabric configuration, distributed training orchestration, and high-performance parallel storage. ## AI Supercomputing Stack | Layer | Component | Purpose | |-------|-----------|---------| | Compute | NVIDIA H100/H200, AMD MI300X | GPU acceleration | | Scheduler | SLURM, PBS Pro | Job management | | Network | InfiniBand NDR, RoCE | GPU-to-GPU communication | | Storage | Lustre, GPFS, BeeGFS | Parallel I/O | | Software | CUDA, NCCL, PyTorch | Training frameworks | | Monitoring | DCGM, Prometheus, Grafana | GPU health + utilization | ## Provision GPU Compute Nodes [code example] ## Deploy SLURM Cluster [code example] [code example] ## InfiniBand Fabric Configuration [code example] ## Parallel Storage (BeeGFS) [code example] ## GPU Monitoring (DCGM + Prometheus) [code example] ## Related Articles - Ansible AI Infrastructure - Ansible for Agentic AI - Ansible systemd Service - Ansible sysctl Module ## Conclusion AI supercomputing in 2026 demands infrastructure automation at scale. Ansible provisions GPU compute nodes with NVIDIA drivers and CUDA, deploys SLURM for job scheduling with GPU-aware resource management (gres.conf), configures InfiniBand... --- ## Ansible ai-forge — Community AI Skills for Content Development URL: https://www.ansiblebyexample.com/articles/ansible-ai-forge-community-ai-skills-for-content-development Description: Contribute to ansible-community/ai-forge — the official repo for AI-powered Ansible content development skills. Structure, test, and share automation. # Ansible ai-forge — Community AI Skills for Content Development ## Introduction The `ansible-community/ai-forge` repository is the official community project for developing AI-powered skills that assist Ansible content developers. These skills help AI assistants understand Ansible conventions, generate correct playbook code, validate automation content, and follow community best practices. As of May 2026, the project has established its core structure and is actively seeking contributions for new skills, testing strategies, and organizational improvements. ## What Are AI Skills? AI skills are structured instruction sets that teach AI assistants how to perform specific Ansible tasks correctly: [code example] ## Repository Structure [code example] ## Skill Format Each skill follows a standard structure: [code example] ## Contributing Skills ### Step 1: Identify a Gap [code example] ### Step 2: Create Your Skill [code example] ### Step 3: Add Examples [code example] [code example] ### Step 4: Submit PR [code example] ## Skill Categories Needed The project is actively seeking skills for: | Category | Status | Description | |----------|--------|-------------| | Role development | In progress | Creating standards-compliant roles | | Playbook writing | In progress | Task naming, idempotency, FQCN usage | | Collection development | Needed | Galaxy metadata, plugin structure | | Module development | Needed | Python module API, argument specs | | Testing | Need... --- ## Ansible AI-Native Software Development Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/ansible-ai-native-software-development-infrastructure Description: Automate AI-native development infrastructure with Ansible. Deploy AI coding assistants, manage GPU dev environments, and orchestrate AI-powered CI/CD. ## Introduction AI-native software development means AI is embedded in every stage of the development lifecycle — from code generation to testing to deployment. This shift requires new infrastructure: GPU-powered dev environments, model serving endpoints for coding assistants, AI-enhanced CI/CD pipelines, and automated quality gates. Ansible automates the provisioning and management of this entire stack. ## AI-Native Dev Stack [code example] ## Deploy AI Coding Assistant Infrastructure [code example] ## GPU Development Environment Provisioning [code example] ## AI-Enhanced CI/CD Pipeline [code example] ## Model Registry and Versioning [code example] ## Developer Workstation Setup [code example] ## Security and Compliance [code example] ## Related Articles - Ansible AI Infrastructure Optimization - Ansible Agentic AI Infrastructure - Ansible for CI/CD Pipelines - Ansible MCP in AAP ## Conclusion AI-native development requires infrastructure at every layer: GPU dev environments for training and experimentation, model registries for versioning, AI-powered CI/CD for automated review and testing, and security controls for AI-generated code. Ansible automates all of it — from provisioning developer GPU workstations to deploying self-hosted coding assistants to configuring AI-enhanced deployment gates. As AI becomes embedded in every stage of software development, the infrastructure to support it becomes critical competitive advantage. --- ## Ansible alternatives Module — Manage System Alternatives URL: https://www.ansiblebyexample.com/articles/ansible-alternatives-module-manage-system-alternatives Description: Ansible alternatives Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible alternatives Module — Manage System Alternatives ## Introduction Manage System Alternatives. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible alternatives Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ... --- ## Ansible and Cloud-Init — Automate VM Bootstrap at First Boot URL: https://www.ansiblebyexample.com/articles/ansible-cloud-init-vm-bootstrap-first-boot Description: Use cloud-init with Ansible for automated VM provisioning at first boot. Generate cloud-init user-data with Ansible templates, bootstrap Ansible pull. ## Introduction cloud-init is the industry standard for configuring cloud instances at first boot. Every major cloud provider (AWS, Azure, GCP) and virtualization platform (Proxmox, VMware, OpenStack) supports it. Ansible integrates with cloud-init in two powerful patterns: **generating cloud-init user-data** to bootstrap VMs, and **using cloud-init to bootstrap Ansible** (pull mode) for ongoing configuration. This guide covers both approaches. ## How cloud-init Works [code example] cloud-init runs in stages: 1. **Network** — configure networking 2. **Config** — set hostname, timezone, SSH keys, users 3. **Final** — install packages, run commands, execute scripts ## Pattern 1: Ansible Generates cloud-init User-Data ### Template user-data with Ansible [code example] ### cloud-init User-Data Template [code example] ## Pattern 2: cloud-init Bootstraps Ansible Pull Mode The most powerful pattern — cloud-init installs Ansible and runs `ansible-pull` at first boot: [code example] ### The Pull Playbook (local.yml) [code example] ## AWS EC2 with cloud-init [code example] ## Azure VM with cloud-init [code example] ## Proxmox with cloud-init [code example] ## Validate cloud-init Config [code example] ## Wait for cloud-init Completion [code example] ## Troubleshooting ### Check cloud-init Logs [code example] ### cloud-init Won't Re-Run [code example] ## Best Practices 1. **Keep cloud-init minimal** — bootstrap users, SSH keys, and Ansible; let Ansible do t... --- ## Ansible and Packer — Build Golden Images with Automated Provisioning URL: https://www.ansiblebyexample.com/articles/ansible-packer-build-golden-images Description: Use Ansible as a Packer provisioner to build golden VM images for AWS, Azure, VMware, and Proxmox. Complete HCL templates, playbook examples, CI/CD. ## Introduction Packer builds identical machine images for multiple platforms from a single configuration. Ansible is its most popular provisioner — your existing playbooks and roles configure the image during the build. The result: golden images (AMIs, Azure images, VMware templates, Docker images) that boot fully configured in seconds, with no configuration drift. ## How It Works [code example] ## Prerequisites [code example] ## AWS AMI with Ansible Provisioner ### Packer Template [code example] ### Ansible Playbook [code example] ### Build [code example] ## Azure Image with Ansible [code example] ## VMware Template with Ansible [code example] ## Docker Image with Ansible [code example] ## Project Structure [code example] ## CI/CD: GitHub Actions [code example] ## Using Ansible Roles in Packer [code example] [code example] ## Best Practices 1. **One playbook per image type** — separate web, database, and base image playbooks 2. **Clean up at the end** — remove caches, logs, and temp files to reduce image size 3. **Use roles** — reuse the same Ansible roles in Packer builds and runtime configuration 4. **Pin versions** — specify exact package versions for reproducible builds 5. **Run in CI/CD** — build images automatically on playbook changes 6. **Weekly rebuilds** — catch security patches with scheduled builds 7. **Tag images with metadata** — include build date, git commit, Packer version 8. **Test images after build** — add a validation provisio... --- ## Ansible Ansible for Network Automation — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-ansible-for-network-automation-complete-guide Description: Automate routers, switches, and firewalls with Ansible network modules. Tested on real machines with clear, copy-paste examples. # Ansible Ansible for Network Automation — Complete Guide ## Introduction Automate routers, switches, and firewalls with Ansible network modules. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Automate routers, switches, and firewalls with Ansible network modules. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Ansible Lint Rules — Write Clean Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-ansible-lint-rules-write-clean-playbooks Description: Ansible Ansible Lint Rules guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Ansible Lint Rules — Write Clean Playbooks ## Introduction Write Clean Playbooks. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Ansible Lint Rules requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible ansible-playbook Command — CLI Options and Usage URL: https://www.ansiblebyexample.com/articles/ansible-ansible-playbook-command-cli-options-and-usage Description: Master the ansible-playbook command with all essential CLI options. Learn check mode, verbose, limit, tags, extra vars, forks, and advanced execution. # Ansible ansible-playbook Command — CLI Options and Usage ## Introduction `ansible-playbook` is the primary command for running Ansible playbooks. While the basic usage is simple (`ansible-playbook site.yml`), the CLI offers dozens of options for controlling execution — targeting specific hosts, running in check mode, passing variables, controlling parallelism, and debugging. This guide covers every option you'll use regularly. ## Basic Usage [code example] ## Most-Used Options ### Check Mode (Dry Run) [code example] ### Limit (Target Specific Hosts) [code example] ### Tags [code example] ### Extra Variables [code example] ### Verbosity [code example] ### Forks (Parallelism) [code example] ## Authentication Options [code example] ## Execution Control ### Start at a Specific Task [code example] ### List Mode [code example] ### Syntax Check [code example] ## Complete Reference | Option | Short | Description | |--------|-------|-------------| | `--inventory` | `-i` | Specify inventory file/directory | | `--limit` | `-l` | Limit to specific hosts/groups | | `--check` | `-C` | Dry run (don't make changes) | | `--diff` | `-D` | Show file differences | | `--tags` | `-t` | Run only these tags | | `--skip-tags` | | Skip these tags | | `--extra-vars` | `-e` | Pass extra variables | | `--verbose` | `-v` | Increase verbosity (up to -vvvv) | | `--forks` | `-f` | Parallel processes (default 5) | | `--become` | `-b` | Run with privilege escalation | | `--become-... --- ## Ansible ansible-pull — Local Playbook Execution from Git URL: https://www.ansiblebyexample.com/articles/ansible-ansible-pull-local-playbook-execution-from-git Description: Use ansible-pull to run playbooks locally from a Git repository. Automate workstation setup, node self-configuration, and cron-based pull mode deployments. # Ansible ansible-pull — Local Playbook Execution from Git ## Introduction `ansible-pull` inverts the default push model. Instead of a central controller pushing configs to nodes, each node pulls its playbook from a Git repository and runs it locally. This is ideal for workstation setup, auto-scaling instances, edge devices, and any scenario where a central controller is impractical. ## Basic Usage [code example] ## How It Works [code example] ## Repository Structure [code example] ## Workstation Setup Example [code example] ## Cron-Based Pull [code example] ### Self-Installing Cron [code example] ## Cloud-Init Bootstrap [code example] ## Key Options | Option | Description | |--------|-------------| | `-U ` | Git repository URL (required) | | `-C ` | Checkout specific branch/tag | | `-d ` | Local directory to clone into | | `--only-if-changed` | Only run playbook if repo changed | | `--sleep ` | Random sleep before run (prevents thundering herd) | | `-i localhost,` | Use localhost inventory | | `--accept-host-key` | Accept SSH host key on first connect | | `-e key=val` | Extra variables | | `--vault-password-file` | Path to vault password file | | `--purge` | Delete local repo after run | ## Hostname-Based Configuration [code example] ## Logging [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Git clone fails | Check SSH keys or use HTTPS with token | | "No hosts matched" | Use `-i localhost,` (note trailing comma) | | Perm... --- ## Ansible ansible-runner — Run Execution Environments from CLI URL: https://www.ansiblebyexample.com/articles/run-an-ansible-execution-environment-ansible-runner-command-line-tool Description: Complete guide to ansible-runner — run Ansible playbooks inside Execution Environments (containers) from the command line. Build, configure. ## Introduction Ansible Runner (`ansible-runner`) is a command-line tool that executes Ansible playbooks inside Execution Environments (EE) — container images that package Ansible, Python dependencies, and collections into a portable runtime. This replaces managing Python virtual environments manually and ensures your development and production environments are identical. This article covers installation, project structure, running playbooks in containers, and troubleshooting. ## What Are Execution Environments? Execution Environments are container images (OCI/Docker) that serve as Ansible control nodes. They contain: - **ansible-core** (or full `ansible` package) - **Python dependencies** (boto3, pywinrm, etc.) - **Ansible collections** (community.general, amazon.aws, etc.) - **System packages** (gcc, openssl-devel, etc.) [code example] ### Why Use EEs? | Challenge | Without EE | With EE | |---|---|---| | Python conflicts | Manual venv management | Isolated container | | Collection versions | Global install collisions | Per-EE pinned versions | | Dev/Prod parity | "Works on my machine" | Same image everywhere | | CI/CD | Complex setup scripts | `docker pull` + run | | Team consistency | Each dev has different env | Shared container image | ## Installation ### Install ansible-runner [code example] ### Install Container Runtime ansible-runner needs `podman` or `docker`: [code example] ## Project Structure ansible-runner expects a specific directory layout: [cod... --- ## Ansible ansible.platform Collection Example: AAP RBAC as Code URL: https://www.ansiblebyexample.com/articles/ansible-ansible-platform-collection-example-aap-rbac-as-code Description: Manage AAP 2.7 RBAC as code with the ansible.platform collection: a runnable example playbook for organizations, teams, and role assignments. At Red Hat Tech Day Netherlands 2026 (3 June 2026, Bunnik), the Ansible team announced 12 new content collections for AAP 2.7, one of which is `ansible.platform` — built for configuration-as-code, RBAC/settings refactoring, and performance improvements on the platform itself. Instead of clicking through the AAP UI to create orgs, teams, and permissions, you define them declaratively and let a playbook reconcile the state. ## Example playbook [code example] ## What it does and why The playbook targets `localhost` because `ansible.platform` modules talk to the AAP controller API directly rather than to managed nodes — connection details (`aap_controller_host`, tokens, certs) are typically supplied via environment variables or an `ansible.cfg`/collection-level config rather than inline. Each task is idempotent: running the playbook repeatedly converges AAP toward the declared state instead of duplicating orgs, teams, or role assignments. The RBAC-specific tasks are the point of the exercise. Rather than an admin manually granting "who can run what" in the UI, `role_user_assignment` and `role_team_assignment` express permissions as versioned, reviewable YAML. That's the "RBAC as code" pattern Red Hat highlighted for AAP 2.7: your access model lives in Git, goes through pull-request review, and can be diffed and audited like any other change. ## Notes / Gotchas - **Authentication**: don't hardcode tokens in the playbook. Use `ANSIBLE_PLATFORM_URL`, `ANSIBLE_PLATFORM_TOKEN`,... --- ## Ansible any_errors_fatal and max_fail_percentage — Playbook Failure Control URL: https://www.ansiblebyexample.com/articles/ansible-any-errors-fatal-and-max-fail-percentage-playbook-failure-control Description: Control playbook failure behavior with any_errors_fatal and max_fail_percentage. Stop all hosts on one failure or allow partial failures in rolling. # Ansible any_errors_fatal and max_fail_percentage — Playbook Failure Control ## Introduction By default, when a task fails on one host, Ansible removes that host from the play but continues on other hosts. This is fine for independent servers, but dangerous for clustered services — if a database migration fails on one node, you don't want it to succeed on others. `any_errors_fatal` and `max_fail_percentage` give you control over when failures should stop everything. ## any_errors_fatal One host fails → **all hosts stop immediately**. [code example] ### Per-Task any_errors_fatal [code example] ### With serial (Rolling Updates) [code example] ## max_fail_percentage Allow some failures before stopping: [code example] ### Setting to 0 [code example] ### Setting to 100 [code example] ## Comparison | Feature | Default | `any_errors_fatal: true` | `max_fail_percentage: 20` | |---------|---------|--------------------------|---------------------------| | 1 of 10 fails | Continue 9 | **Stop all** | Continue | | 3 of 10 fail | Continue 7 | **Stop all** | **Stop all** | | 10 of 10 fail | All fail | **Stop all** | **Stop all** | | Use case | Independent servers | Critical operations | Rolling updates | | Scope | Per-play or task | Per-play or task | Per-play only | ## Practical Examples ### Database Cluster [code example] ### Load-Balanced Web Tier [code example] ### Mixed Criticality [code example] ## Combining with block/rescue [code example] ## Troubleshoot... --- ## Ansible Apache HTTPD — Deploy and Configure Web Servers URL: https://www.ansiblebyexample.com/articles/ansible-apache-httpd-web-server-configuration Description: Deploy Apache HTTPD with Ansible. Installation, virtual host configuration, SSL/TLS, mod_rewrite, mod_security, reverse proxy, performance tuning. ## Introduction Apache HTTP Server (httpd) remains the world's most deployed web server. Ansible automates every aspect — installation, virtual host management, SSL certificates, module configuration, reverse proxy setup, and performance tuning. Template your entire Apache configuration from variables so adding a site is just adding an item to a YAML list. ## Install Apache [code example] ## Virtual Hosts [code example] [code example] ### Variables [code example] ## Enable Modules [code example] ## Reverse Proxy [code example] ## Performance Tuning [code example] [code example] [code example] ## Security Hardening [code example] ## Troubleshooting ### Validate Config [code example] ### Check Virtual Hosts [code example] ## Related Articles - Ansible Nginx Automation - Ansible Let's Encrypt SSL - Ansible HAProxy - Ansible Firewall Module ## Conclusion Ansible templates Apache virtual hosts from YAML variables — adding a site is adding an item to a list. Use `community.general.apache2_module` to manage modules, template-based configs for SSL, reverse proxy, and performance tuning, and `configtest` validation before applying changes. Apache + Ansible gives you declarative multi-site web server management across your fleet. --- ## Ansible Apache Vhost — RedHat Config URL: https://www.ansiblebyexample.com/articles/deploy-a-web-server-apache-httpd-virtualhost-on-redhat-like-systems-ansible-modules-yum-file-copy-template-service-and-firewalld Description: Automate Apache virtual host setup on RedHat systems with Ansible. Learn to manage web server installation, configuration, and firewall settings. ## How to deploy a webserver apache httpd virtual host on RedHat-like systems with Ansible? This Playbook is quick and dirty but shows you the basics of Ansible automation technology that you could use in your System Administrator every day. ## Deploy a web server apache httpd virtualhost on RedHat-like systems - install packages => `ansible.builtin.yum` - document root => `ansible.builtin.file` - custom index.html => `ansible.builtin.copy` - Apache virtualhost => `ansible.builtin.template` - start service => `ansible.builtin.service` - open firewall => `ansible.posix.firewalld` Today we're talking about how to Deploy a web server apache httpd on RedHat-like Linux systems. The full process requires six steps that you could automate with different Ansible modules. Firstly you need to install the `httpd` package and dependency using the `ansible.builtin.yum` Ansible module. Secondly, you need to create the document root with the right permission with the `ansible.builtin.file` module. Thirsty, you need to create the custom index.html with `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Fourthly, you need to set up Apache configuration for the specific virtual host using the `ansible.builtin.template` module. Fifthly, you need to start the `httpd` service and enable it on boot and all the dependant using the `ansible.builtin.service` Ansible module. Sixthly you need to open the relevant firewall service-related ports using the `... --- ## Ansible AppArmor — Manage Linux Security Profiles URL: https://www.ansiblebyexample.com/articles/ansible-apparmor-linux-security-profiles Description: Manage AppArmor security profiles with Ansible. Deploy custom profiles, switch enforcement modes, audit application access, troubleshoot denials. ## Introduction AppArmor is a Linux mandatory access control (MAC) system that confines programs to a limited set of resources — file access, network capabilities, and system calls. Ansible automates AppArmor profile management: deploy custom profiles, switch between enforce/complain modes, audit application behavior, and harden services across your fleet. ## Install and Enable AppArmor [code example] ## Deploy Custom Profiles [code example] ## Manage Profile Modes [code example] ## Nginx AppArmor Profile [code example] ## Docker Container Profiles [code example] ## Audit and Troubleshoot [code example] ## Fleet Status Report [code example] ## Handlers [code example] ## Troubleshooting ### Profile Not Loading [code example] ### Application Blocked Start in complain mode, run the app, then review logs: [code example] ## Related Articles - Ansible SELinux Module - Ansible Auditd - Ansible Compliance Guide - Ansible Docker Compose ## Conclusion AppArmor confines applications to only the resources they need — Ansible deploys and manages profiles at scale. Use complain mode for profiling new applications, enforce mode for production, and `aa-logprof` to iteratively refine profiles from real access logs. Deploy profiles for Nginx, Docker containers, and custom applications. Security hardening as code, applied consistently across every server. --- ## Ansible apt Module — Manage Packages on Debian and Ubuntu URL: https://www.ansiblebyexample.com/articles/ansible-apt-module-manage-packages-debian-ubuntu Description: Install, update, and remove packages on Debian/Ubuntu with the Ansible apt module. Upgrade all, pin versions, add repositories, and autoremove with. ## Introduction `ansible.builtin.apt` manages packages on Debian-based systems (Debian, Ubuntu, Linux Mint). Install, remove, update, and upgrade packages idempotently — Ansible only makes changes when needed. ## Install Packages [code example] ## Update Package Cache [code example] ## Upgrade Packages [code example] ## Remove Packages [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | — | Package name(s) | | `state` | `present` | `present`, `latest`, `absent`, `fixed` | | `update_cache` | `false` | Run `apt update` before install | | `cache_valid_time` | — | Skip update if cache is newer (seconds) | | `upgrade` | — | `safe`, `full`, `dist` | | `purge` | `false` | Remove config files with `state: absent` | | `autoremove` | `false` | Remove unused dependencies | | `autoclean` | `false` | Clean local package cache | | `deb` | — | Install from `.deb` file path/URL | | `force_apt_get` | `false` | Use apt-get instead of aptitude | | `install_recommends` | `true` | Install recommended packages | | `allow_downgrade` | `false` | Allow package downgrade | | `dpkg_options` | — | Extra dpkg options | ## Install from .deb File [code example] ## Add APT Repository [code example] ## Practical Patterns ### Full Server Setup [code example] ### Conditional Package Installation [code example] ### Pin Package Version [code example] ### Unattended Upgrades [code example] ## Troubleshooting ### "Could not g... --- ## Ansible apt vs yum vs package — Cross-Platform Package Management URL: https://www.ansiblebyexample.com/articles/ansible-apt-vs-yum-vs-package Description: Compare Ansible apt, yum, dnf, and package modules. Learn cross-platform package management patterns and when to use each module. ## Introduction Ansible has platform-specific package modules (`apt`, `yum`, `dnf`) and a generic `package` module. Choosing the right one depends on whether your playbooks target a single OS family or multiple distributions. This guide compares all four with cross-platform patterns. ## Quick Comparison | Module | OS Family | Package Manager | Specific Features | |--------|-----------|----------------|------------------| | `apt` | Debian/Ubuntu | apt/dpkg | `update_cache`, `deb`, `dpkg_options`, PPA | | `yum` | RHEL/CentOS 7 | yum | `enablerepo`, `disablerepo`, `security` | | `dnf` | RHEL 8+/Fedora | dnf | `allowerasing`, `nobest`, modules | | `package` | Any | Auto-detect | Only `name` + `state` (lowest common denominator) | ## apt — Debian/Ubuntu [code example] ## yum / dnf — RHEL/CentOS/Fedora [code example] ## package — Generic Cross-Platform [code example] ### package Limitations [code example] ## Cross-Platform Patterns ### Pattern 1: OS-Specific Variables [code example] ### Pattern 2: Conditional Tasks [code example] ### Pattern 3: Role with OS Support [code example] ## Performance Tips [code example] ## Common Mistakes [code example] ## Related Articles - Ansible apt Module - Ansible Roles Guide - Ansible Inventory Guide - Ansible check mode vs diff mode ## Conclusion **apt** for Debian/Ubuntu (richest feature set: cache control, PPA, purge). **dnf** for RHEL 8+/Fedora (module streams, repo control). **yum** for RHEL 7 only. **package** for t... --- ## Ansible apt_key and apt_repository — Manage APT Sources URL: https://www.ansiblebyexample.com/articles/ansible-apt-key-and-apt-repository-manage-apt-sources Description: Ansible apt_key and apt_repository guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible apt_key and apt_repository — Manage APT Sources ## Introduction Manage APT Sources. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible apt_key and apt_repository requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ta... --- ## Ansible ARA Records Ansible — Install, Configure, Browse Playbook History URL: https://www.ansiblebyexample.com/articles/ansible-ara-records-ansible-playbook-history Description: Set up ARA Records Ansible to record and browse playbook execution history. Install ARA, configure the callback plugin, and use the web UI and CLI. ## Introduction ARA Records Ansible (ARA) is an open-source tool that records Ansible playbook execution data and makes it available through a web interface, CLI, and REST API. Every time you run a playbook, ARA captures tasks, results, hosts, files, and timing — giving you a searchable history of what ran, when, where, and what changed. This guide covers installation, configuration, and practical usage. ## What ARA Records [code example] ## Installation ### Install ARA with pip [code example] ### Install with Ansible [code example] ## Configuration ### Method 1: ansible.cfg (Recommended) [code example] ### Method 2: Environment Variables [code example] ### Method 3: Ansible Configuration with Environment [code example] ## Using the Web UI [code example] ### Deploy ARA Server with Ansible [code example] ## Using the CLI [code example] ## ARA with CI/CD [code example] ## ARA with Centralized Server [code example] [code example] ## Common Mistakes [code example] ## ARA vs Other Tools [code example] ## Related Articles - Ansible Callback Plugins - Ansible Troubleshooting - Ansible CI/CD Pipelines - Ansible AAP Enterprise - Ansible Playbook Best Practices ## Conclusion ARA Records Ansible turns ephemeral playbook output into searchable, browsable history. Install it with `pip install "ara[server]"`, enable the callback plugin, and every playbook run is automatically recorded. Use the web UI for browsing, the CLI for scripting, and the REST API fo... --- ## Ansible archive — Create zip tar.gz URL: https://www.ansiblebyexample.com/articles/ansible-archive-module-create-tar-gz-zip-archives Description: Ansible archive Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible archive Module — Create tar gz zip Archives ## Introduction Create tar gz zip Archives. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible archive Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible assemble Module — Combine File Fragments into Single File URL: https://www.ansiblebyexample.com/articles/ansible-assemble-module-combine-file-fragments-into-single-file Description: Merge multiple file fragments into a single configuration file on remote hosts. With clear, copy-paste, step-by-step examples. # Ansible assemble Module — Combine File Fragments into Single File ## Introduction The `ansible.builtin.assemble` module merge multiple file fragments into a single configuration file on remote hosts. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.assemble` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mod... --- ## Ansible assert Module — Validate Conditions and Fail Fast URL: https://www.ansiblebyexample.com/articles/ansible-assert-validate-conditions-fail-fast Description: Use the Ansible assert module to validate conditions before proceeding. Check variables, facts, and system requirements with custom error messages. ## Introduction `ansible.builtin.assert` validates conditions and stops the playbook with a clear message if they fail. Use it for pre-flight checks — verify system requirements, variable values, and dependencies before making changes. ## Basic Syntax [code example] ## Multiple Conditions [code example] ## Validate Variables [code example] ## Check Registered Results [code example] ## Practical Patterns ### Pre-Deployment Validation [code example] ### OS Compatibility Check [code example] ### Loop Validation [code example] ## assert vs fail [code example] ## quiet Mode [code example] ## Troubleshooting ### Complex Conditions For multi-line conditions, use `>` YAML folding: [code example] ### "Conditional check failed" The expression in `that` must be valid Jinja2. Don't use `{{ }}`: [code example] ## Related Articles - Ansible when Conditional - Ansible debug Module - Ansible Facts Guide - Ansible register Variables - Ansible Playbook Guide ## Conclusion `assert` is your pre-flight checklist. Validate system requirements, variable values, service availability, and dependencies before making changes. It fails fast with clear messages, saving time on debugging half-completed deployments. Use `that` for conditions (list = AND logic), `fail_msg` for clear error messages, and `quiet: true` for clean output. For simple single-condition checks, `fail` + `when` works too, but `assert` is cleaner for multiple validations. --- ## Ansible assert Module — Validate Variables & Fail Early URL: https://www.ansiblebyexample.com/articles/ansible-assert-module-validate-variables-and-conditions Description: Use Ansible assert to validate variables, check conditions, and fail playbooks early with clear error messages. Examples with that, fail_msg. # Ansible assert Module — Validate Variables and Conditions The `ansible.builtin.assert` module lets you validate conditions during playbook execution and fail immediately with a clear message if something is wrong. ## Basic Syntax [code example] ## Common Use Cases ### Check Variable is Defined [code example] ### Validate Numeric Ranges [code example] ### Check File Exists [code example] ### Validate OS Version [code example] ### Multiple Conditions with quiet Mode [code example] The `quiet: true` parameter suppresses the verbose output of each condition, showing only the fail message if something fails. ## Parameters Reference | Parameter | Required | Description | |-----------|----------|-------------| | `that` | yes | List of conditions to evaluate (all must be true) | | `fail_msg` | no | Custom message shown when assertion fails | | `success_msg` | no | Custom message shown when all assertions pass | | `quiet` | no | Suppress individual condition output (default: false) | ## Tips and Best Practices 1. **Use assert at the start of playbooks** — Fail fast before making changes 2. **Always include `fail_msg`** — Generic "Assertion failed" messages waste debugging time 3. **Combine with `stat` module** — Check file existence before operations 4. **Use `quiet: true`** for large condition lists — Reduces output noise 5. **Group related assertions** — One assert task per logical check ## Related Articles - Ansible Error Handling — rescue, always, ignore_err... --- ## Ansible assert Module — Validate Variables and Conditions URL: https://www.ansiblebyexample.com/articles/ansible-assert-validate-variables-conditions Description: Use the Ansible assert module to validate variables, check conditions, and fail early with clear error messages. Guard clauses for reliable automation. ## Introduction `ansible.builtin.assert` validates conditions before proceeding. If any condition is false, the task fails with a clear message. Use it to catch misconfigurations early — before they cause cryptic errors downstream. ## Basic Usage [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `that` | List of conditions (all must be true) | | `fail_msg` | Message on failure | | `success_msg` | Message on success | | `quiet` | Suppress success output (`true`/`false`) | ## Validate Variables [code example] ## Pre-Flight Checks [code example] ## Validate After Commands [code example] ## Loop Validation [code example] ## Role Validation Pattern [code example] ## Deployment Verification [code example] ## Troubleshooting ### Complex Conditions Use parentheses and Jinja2 filters: [code example] ### Undefined Variable Errors Check `is defined` first: [code example] ## Related Articles - Ansible Error Handling - Ansible Variables Guide - Ansible Playbook Guide - Ansible debug Module ## Conclusion `ansible.builtin.assert` is your guard clause. Validate required variables at the start of playbooks and roles. Check system requirements (RAM, disk, OS). Verify deployments after they complete. Use `fail_msg` for clear error messages. The pattern: validate early, fail fast, fix before damage is done. --- ## Ansible assert Module: Validate Conditions in Playbooks URL: https://www.ansiblebyexample.com/articles/assert-module-in-ansible Description: Ansible assert module: validate conditions to stop playbook execution on failure. Use for guard clauses, custom error messages, and controlled output. ## Introduction The `assert` module in Ansible is a powerful tool for validating conditions and ensuring the correctness of your automation workflows. By halting execution when a condition isn't met, it prevents cascading failures and provides valuable feedback to the user. In this article, we'll explore the `quiet`, `fail_msg`, and `success_msg` parameters, which enhance the flexibility and usability of assertions in playbooks. Use `ansible.builtin.assert` for guard clauses in playbooks: check that variables, facts, ports, files, or other expressions match your expectations before running the tasks that depend on them. ## What is the `assert` Module? The `assert` module evaluates one or more conditions and ensures they are true. If any condition fails, the module raises an error and stops execution. It's particularly useful for debugging, validation, and ensuring preconditions in complex playbooks. ### Basic Syntax [code example] If `some_variable` doesn't equal `expected_value`, the playbook will fail at this step. ## Enhancing Assertions with `quiet`, `fail_msg`, and `success_msg` ### 1. `quiet`: Suppress Output for Passed Assertions By default, the `assert` module outputs all evaluated conditions. However, in scenarios where you only want feedback on failures, `quiet: true` suppresses success messages. #### Example: [code example] ### Use Case: - Keeps playbook output clean and focused, especially when numerous assertions are involved. --- ### 2. `fail_msg`... --- ## Ansible async and poll — Background URL: https://www.ansiblebyexample.com/articles/ansible-async-poll-long-running-tasks Description: Use Ansible async and poll to run long-running tasks in the background. Fire-and-forget, check status later, and parallelize slow operations. ## Introduction By default, Ansible waits for each task to complete before moving to the next. For long-running tasks (builds, backups, large downloads), `async` and `poll` let you run tasks in the background and check on them later. ## How It Works [code example] ## Check Status Later [code example] ## Parallel Long Tasks [code example] ## Practical Patterns ### Package Updates [code example] ### Software Build [code example] ### Download Large Files [code example] ### Rolling Restart with Warmup [code example] ### Reboot and Reconnect [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `async` | Maximum runtime in seconds | | `poll` | Check interval (0 = fire-and-forget) | | `async_status` | Module to check job status | | `jid` | Job ID (from registered variable) | ## async_status Return Values [code example] ## Limitations - **Cannot use with `loop`** on the `async_status` check — use `loop` on the original task - **Task must complete within `async` seconds** or it's killed - **Not all modules support async** — works best with `command`, `shell`, `raw` - **Async tasks survive connection loss** — they keep running on the remote host - **Results stored in `~/.ansible_async/`** on the remote host ## Troubleshooting ### Job Timed Out Increase `async` value: [code example] ### Can't Find Job Job IDs are host-specific. Don't mix up jobs across hosts: [code example] ### Cleanup Old Jobs [code example] ## Related... --- ## Ansible Async Task Failure — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-async-task-failure-fix-and-solutions Description: Troubleshoot async task failures from timeouts, status checks, and cleanup. Hands-on, tested examples and best practices for Ansible Async Task Failure. # Ansible Async Task Failure — Fix and Solutions ## Introduction Troubleshoot async task failures from timeouts, status checks, and cleanup. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Troubleshoot async task failures from timeouts, status checks, and cleanup. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible async_status Module — Check Async Task Status URL: https://www.ansiblebyexample.com/articles/ansible-async-status-module-check-async-task-status Description: Monitor and check the status of asynchronous tasks in Ansible playbooks. Hands-on, tested examples and best practices for Ansible async_status Module. # Ansible async_status Module — Check Async Task Status ## Introduction The `ansible.builtin.async_status` module monitor and check the status of asynchronous tasks in Ansible playbooks. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.async_status` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run w... --- ## Ansible at Module — Schedule One-Time Tasks URL: https://www.ansiblebyexample.com/articles/ansible-at-module-schedule-one-time-tasks Description: Ansible at Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible at Module — Schedule One-Time Tasks ## Introduction Schedule One-Time Tasks. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible at Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective task ... --- ## Ansible at Scale — Manage 1,000+ Nodes with Performance Tuning URL: https://www.ansiblebyexample.com/articles/ansible-at-scale-manage-1000-nodes-performance-tuning Description: Scale Ansible to manage thousands of nodes. Optimize forks, pipelining, fact caching, callback plugins, pull mode, and execution environments for large. ## Introduction Running Ansible against 10 hosts is easy. Running it against 1,000+ hosts requires deliberate performance tuning. This guide covers every lever: connection optimization, parallelism, fact caching, pull mode, execution environments, and architecture patterns that let Ansible scale to enterprise fleet sizes. ## Baseline Performance Settings [code example] ### Key Settings Explained | Setting | Default | Recommended | Impact | |---------|---------|-------------|--------| | `forks` | 5 | 50-100 | Parallel host connections | | `pipelining` | False | True | Reduces SSH operations by ~2x | | `gathering` | implicit | smart | Cache facts, skip if cached | | `fact_caching` | memory | jsonfile/redis | Persist facts across runs | | `ControlPersist` | 60s | 60s-300s | Reuse SSH connections | ## Optimize Parallelism ### Forks Tuning [code example] [code example] [code example] ### Strategy Plugins [code example] [code example] ## Fact Caching with Redis [code example] [code example] ## Reduce Gather Facts Overhead [code example] [code example] ## SSH Connection Optimization [code example] ### Mitogen (Alternative SSH Transport) [code example] ## Pull Mode for Massive Scale [code example] ### When to Use Pull vs Push | Criteria | Push (default) | Pull (ansible-pull) | |----------|---------------|-------------------| | Hosts | < 500 | 500+ | | Network | Good connectivity | Intermittent/NAT | | Control | Centralized | Distributed | | Latency | Low | ... --- ## Ansible at Scale — Patterns for 1,000+ Host Fleets URL: https://www.ansiblebyexample.com/articles/ansible-large-scale-patterns-performance Description: Scale Ansible to manage thousands of hosts. Forks, strategy plugins, fact caching, pull mode, execution environments, AWX, and architecture patterns for. # Ansible at Scale — Patterns for 1,000+ Host Fleets ## Introduction Ansible works great for 10 hosts. At 100 hosts, you need tuning. At 1,000+, you need architecture. This guide covers the patterns, configuration, and tools that make Ansible work reliably across thousands of hosts in enterprise environments. ## Performance Configuration ### ansible.cfg Baseline for Large Fleets [code example] ## Strategy Comparison | Strategy | Behavior | Best For | |----------|----------|----------| | `linear` | All hosts run task 1, then task 2 (default) | Ordered deployments | | `free` | Each host runs independently | Independent servers | | `host_pinned` | Like free, but keeps host order per batch | Mixed workloads | | `mitogen_linear` | Accelerated linear (3-7x faster) | Everything | [code example] ## Inventory Patterns ### Split Inventory by Region [code example] [code example] ### Dynamic Inventory for Cloud [code example] ## Serial Execution for Safety [code example] ## Pull Mode with ansible-pull For very large fleets (10,000+ hosts), push mode hits limits. Pull mode flips the model — each host runs ansible-pull on a schedule: [code example] ## AWX / Automation Controller For enterprise scale, AWX (or Red Hat AAP) provides: [code example] Key features for scale: - **Automation Mesh**: Distribute execution across regions - **Instance Groups**: Dedicate capacity to teams - **Job Slicing**: Split one job across multiple nodes - **Smart Inventories**: Dynamic host... --- ## Ansible Auditd — Configure Linux Audit Framework URL: https://www.ansiblebyexample.com/articles/ansible-auditd-linux-audit-framework Description: Configure the Linux audit framework (auditd) with Ansible. Deploy audit rules for file access, system calls, authentication, privilege escalation,. ## Introduction The Linux Audit Framework (auditd) tracks security-relevant events — file access, system calls, authentication, privilege escalation, and configuration changes. It's required by CIS benchmarks, STIG, PCI-DSS, and HIPAA compliance. Ansible automates auditd deployment, rule management, and log configuration across your fleet. ## Install and Configure [code example] ### auditd.conf Template [code example] ## Audit Rules — CIS Benchmark [code example] ## Custom Application Rules [code example] ## Search and Report [code example] ## Forward Logs to Central Server [code example] [code example] ## Troubleshooting ### Check Rule Status [code example] ### Rules Not Loading [code example] ## Related Articles - Ansible Compliance Guide - Ansible Fail2Ban - Ansible Firewall Module - Ansible Logrotate ## Conclusion Ansible deploys auditd rules as code — CIS benchmark compliance, STIG requirements, and custom application monitoring all defined in templates. Use `augenrules --load` to apply changes without restarting, `ausearch` and `aureport` for investigation, and audisp-remote for centralized log collection. Immutable rules (`-e 2`) prevent tampering in high-security environments. --- ## Ansible Authentication Failure — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-authentication-failure-fix-and-solutions Description: Resolve authentication errors from wrong credentials, keys, and sudo config. Tested on real machines with clear, copy-paste examples. # Ansible Authentication Failure — Fix and Solutions ## Introduction Resolve authentication errors from wrong credentials, keys, and sudo config. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve authentication errors from wrong credentials, keys, and sudo config. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible authorized_key Module — Deploy SSH Public Keys URL: https://www.ansiblebyexample.com/articles/ansible-authorized-key-module-deploy-ssh-public-keys Description: Ansible authorized_key Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible authorized_key Module — Deploy SSH Public Keys ## Introduction Deploy SSH Public Keys. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible authorized_key Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible Automate Database Migrations — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-automate-database-migrations-complete-guide Description: Run database migrations as part of Ansible deployments. Hands-on, tested examples and best practices for Ansible Automate Database Migrations. # Ansible Automate Database Migrations — Complete Guide ## Introduction Run database migrations as part of Ansible deployments. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Run database migrations as part of Ansible deployments. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Automate Windows Updates — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-automate-windows-updates-complete-guide Description: Deploy Windows patches and manage update schedules with Ansible. Hands-on, tested examples and best practices for Ansible Automate Windows Updates. # Ansible Automate Windows Updates — Complete Guide ## Introduction Deploy Windows patches and manage update schedules with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy Windows patches and manage update schedules with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Automates London 2023: Your Guide to Enterprise Automation URL: https://www.ansiblebyexample.com/articles/ansible-automates-london-2023 Description: Join Ansible Automates London 2023 on July 13 to discover automation strategies, outcomes, and platform features. Ideal for IT professionals seeking to. Save the date: Ansible Automates London 2023 in London, UK, July 13, 2023 Ansible Automates is an event offering multiple tracks focused on Enterprise Automation using Ansible. Here is a summary of each track and the target audience: **Track 1: Enterprise Automation Strategy** — Why Automate? This track emphasizes the importance of enterprise automation, providing insights into its significance and value for all organizations. It is ideal for Enterprise Architects and business stakeholders seeking to understand the rationale behind automation initiatives. **Track 2: The Outcome of Automation** — What to Automate? In this track, delivery teams share their experiences, highlighting challenges and successes in implementing automation. It suits anyone interested in learning about automation possibilities with Ansible and how to execute it effectively. **Track 3: Ansible Automation Platform** — How to Automate This track focuses on extracting value from the Ansible Automation Platform. Attendees can explore the latest features and upcoming developments. This track is designed for individuals who are already utilizing the platform. ## Why Attend? Ansible Automates aims to redefine business practices through automation. It offers opportunities to create, scale, and implement automation across the enterprise. Participants can gain insights from local automation experts, and industry thought leaders, learning how to enhance team effectiveness using Ansible Automation. The event ... --- ## Ansible Automation AI URL: https://www.ansiblebyexample.com/articles/ansible-automation-ai Description: Explore Ansible Automation AI, your versatile resource for mastering Ansible, from basics to advanced Kubernetes and VMware integrations, simplifying IT. ## Introduction In today's fast-paced IT environment, automation has become a cornerstone for efficiency and innovation. Ansible Automation AI emerges as a beacon of guidance for IT professionals navigating through the realms of automation and infrastructure-as-code. This comprehensive guide is a must-have for Linux and Windows Systems Administrators, DevOps professionals, and those passionate about infrastructure-as-code, offering a rich blend of foundational knowledge and advanced insights. **Discover More**: For further insights and detailed discussions, visit Ansible Automation AI. ### Introducing Ansible Automation AI Ansible Automation AI stands out with its approachable yet professional tone, making it a versatile resource for beginners and seasoned developers alike. The guide embarks on a journey from the basics of Ansible, smoothly transitioning into more complex territories. It serves as an invaluable assistant in automating IT infrastructure, with a keen focus on VMware, Kubernetes-based containerized microservices, and the reduction of human interaction and errors. ## Key Features and Benefits 1. **Jargon-Free Understanding**: Tailored to demystify Ansible technology, the guide ensures concepts are easily graspable, breaking down complex topics into digestible segments. 2. **Practical Applications**: From managing Kubernetes clusters and cloud services to orchestrating pods and storage, the guide offers hands-on guidance every step of the way. 3. **Comp... --- ## Ansible Automation Orchestrator — AI-Driven IT Operations Preview URL: https://www.ansiblebyexample.com/articles/ansible-automation-orchestrator-ai-driven-it-operations-preview Description: Red Hat's Automation Orchestrator combines event detection, AI reasoning, and deterministic execution with human approval gates for autonomous operations. # Ansible Automation Orchestrator — AI-Driven IT Operations Preview ## Introduction Coming in Q3 2026, Red Hat's **Automation Orchestrator** combines three pillars into one governed pipeline: event detection (EDA), AI reasoning (AIA), and deterministic execution (AAP). The result: autonomous IT operations with human approval gates built in. ## Architecture: The Three Pillars [code example] ## How It Works ### Step 1: Event Detection (EDA) [code example] ### Step 2: AI Reasoning (AIA) The AI layer: 1. Correlates the event with recent changes 2. Assesses impact and blast radius 3. Selects appropriate remediation playbook 4. Determines if human approval is needed ### Step 3: Deterministic Execution (AAP) [code example] ## Human Approval Gates | Risk Level | Approval Required | Timeout | |-----------|-------------------|---------| | Low (diagnostic) | None | — | | Medium (restart) | Team lead | 15 min | | High (scale/failover) | Platform owner | 30 min | | Critical (data ops) | Change board | 1 hour | ## Event Sources (12 New Collections) EDA 2026 adds 12 new event source collections: | Collection | Events | |-----------|--------| | `ansible.eda.kafka` | Message queue events | | `ansible.eda.aws_eventbridge` | AWS service events | | `ansible.eda.azure_event_hub` | Azure platform events | | `ansible.eda.prometheus` | Alert manager webhooks | | `ansible.eda.servicenow` | ITSM ticket events | | `ansible.eda.pagerduty` | Incident triggers | | `ansible.eda.github` | Re... --- ## Ansible Automation Platform — Complete Guide to AAP URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-download Description: Complete guide to Red Hat Ansible Automation Platform (AAP). Learn the architecture, key components (Controller, Hub, EDA), installation methods, and how. ## Introduction Red Hat Ansible Automation Platform (AAP) is the enterprise version of Ansible — adding a web UI, role-based access control, centralized content management, and event-driven automation on top of the open-source Ansible engine. It's designed for teams that need governance, scalability, and support for their automation at scale. ## AAP vs Open-Source Ansible | Feature | Open-Source Ansible | Ansible Automation Platform | |---------|--------------------|-----------------------------| | Engine | ansible-core | ansible-core (certified) | | Web UI | No (use AWX) | Automation Controller | | Content Hub | Ansible Galaxy | Automation Hub (certified) | | RBAC | No | Yes | | Event-Driven | No | Event-Driven Ansible | | Support | Community | Red Hat subscription | | Execution Environments | Manual build | Included + custom | | Analytics | No | Automation Analytics | | Cost | Free | Subscription required | ## Core Components ### 1. Automation Controller (formerly Ansible Tower) The web UI and API for running automation: - **Job Templates** — define what playbook runs on which inventory - **Workflows** — chain multiple job templates with conditional logic - **Schedules** — cron-like scheduling for automated runs - **RBAC** — teams, users, and permissions - **Credentials** — securely store SSH keys, cloud tokens, vault passwords - **Notifications** — Slack, email, webhook on job success/failure - **API** — REST API for integration with CI/CD tools ### 2. Automation H... --- ## Ansible Automation Platform 2.1 Released: Key Updates and New Features URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-automation-platform-2-1-general-available Description: Discover the latest updates in Ansible Automation Platform 2.1, including new automation mesh technology, container-native design, and enhanced. Hello everyone and welcome to the latest Ansible Automation news from Ansible Pilot. On December 2nd the Engineer Team give as a gift before Christmas, they just announced their Ansible Automation Platform 2.1 General Available. Let me quickly remind you that the Ansible Automation Platform is the enterprise-grade release of Ansible with the Customer Support provided directly by the RedHat corporation. The Early Access 2.0 release was presented this summer but this new version was announced in September 2021. This is a major upgrade from the previous Platform 1.2. Let me share four highlights of this release: - The major news is automation mesh technology that enables dynamic cluster capacity, global scalability, and Secure automation with end-to-end encryption. - All the platform was designed with the container in mind. The automaton execution environment allows you to rely on pre-build containers to run our Ansible code. - The Automation Platform Operator run now natively on OpenShift, the Red Hat implementation of Kubernetes. - The central authentication is available for Controller and Automation Hub single sign-on (SSO) The platform now includes all the following 11 products: - Execution environment builder to create your customized execution environment. - Ansible content tools to simplify the development of your Ansible code in Visual Studio. - Ansible Content Collections for better code reuse mixing Enterprise, Partner, and Community grade - Automation content naviga... --- ## Ansible Automation Platform 2.2 Released: Key Updates and New Features URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-automation-platform-2-2-general-available Description: Explore the latest updates in Ansible Automation Platform 2.2, including new automation mesh technology, enhanced support for containers, and integration. Hello everyone and welcome to the latest Ansible Automation news from Ansible Pilot. On May 25th the Ansible Engineer Team announced the Ansible Automation Platform 2.2 General Available. Let me quickly remind you that the Ansible Automation Platform is the enterprise-grade release of Ansible with the Customer Support provided directly by the RedHat corporation. This is the latest release of the 2.0 series after the 2.1 released in December 2021 anticipated by the Early Access program. Meanwhile, the Platform 1.2 support period was extended to give time to upgrade to the 2.0 major upgrade. Let me share four highlights of this release: - The major news is automation mesh technology that enables dynamic cluster capacity, global scalability, and Secure automation with end-to-end encryption. - All the platform was designed with the container in mind. The automaton execution environment allows you to rely on pre-build containers to run our Ansible code. - The Automation Platform Operator runs now natively on OpenShift, the Red Hat implementation of Kubernetes. - The central authentication SSO is available for Controller and Automation Hub single sign-on (SSO) - The Automation Hub supports High Availability - On-Premise Automation Catalog - RHEL9 support (few days after RHEL9's GA) The platform now includes all the following 11 products: - Execution environment builder to create your customized execution environment. - Ansible content tools to simplify the development of your Ans... --- ## Ansible Automation Platform 2.3 Released: Key Features and Enhancements URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-automation-platform-2-3-general-available Description: Discover the latest updates in Ansible Automation Platform 2.3, including enhanced security with trusted content signing, new Event-Driven Architecture,. Hello everyone and welcome to the latest Ansible Automation news from Ansible Pilot. Today, we’re diving into the exciting updates of Ansible Automation Platform 2.3, released on November 29, 2022. For those new to the Ansible world, Ansible Automation Platform (AAP) is the enterprise-grade version of Ansible, offering premium support and additional features from Red Hat. This release continues Red Hat’s commitment to enhancing automation capabilities, following the AAP 2.2 release in May 2022. ## Key Highlights of Ansible Automation Platform 2.3 1. **Enhanced Security with Trusted Automation Supply Chain:** - **Ansible Trusted Collections:** Now available from the trusted registry, ensuring downloaded content is validated with a GPG key to prevent tampering. - **ansible-sign Utility:** A new open-source tool for signing and verifying your code, enhancing security and integrity. 2. **New Event-Driven Architecture:** - This innovative feature allows automation to be triggered by events rather than on-demand or scheduled runs. The new "RuleBook" system opens up exciting possibilities for Infrastructure as Code (IaC) automation. 3. **Enterprise Features:** - **Enterprise LDAP Integration:** Now supports role-based access control, a much-requested feature for enterprise environments. - **Automation Hub Improvements:** Includes support for high availability and on-premise automation catalog, as well as RHEL9 support. 4. **Container-Based Architecture Refinemen... --- ## Ansible Automation Platform 2.6 — What's New & Changes URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-6 Description: Explore AAP 2.6 features: Platform Gateway, unified auth, Event-Driven Ansible, Automation Mesh, enhanced Execution Environments, and more. ## Red Hat Ansible Automation Platform 2.6 Overview **Red Hat Ansible Automation Platform (AAP) 2.6** is now generally available, introducing new capabilities that blend **AI-powered assistance**, **scalability**, and **real-time analytics**. This release focuses on helping IT operations teams automate more effectively, measure impact, and scale across hybrid environments. Red Hat describes this release as a step toward “automating for the future,” emphasizing trusted automation foundations for modern enterprise IT. --- ## Key Highlights With the 2.6 release, Red Hat delivers three major feature areas designed to drive measurable value: 1. **Unlock more value** – Track and visualize automation ROI with the new automation dashboard. 2. **Operate more efficiently** – Harness generative AI through the Ansible Lightspeed Intelligent Assistant. 3. **Achieve new levels of scale** – Expand automation access with the new self-service automation portal. --- ## Unlock More Value: Automation Dashboard The **automation dashboard** provides an on-premise, secure utility for visualizing and reporting the business impact of automation initiatives. ### Benefits - **Monitor performance:** Track job success rates, time savings, and ROI in real-time. - **Optimize efficiency:** Identify underutilized or overextended nodes to rebalance workloads. - **Secure insights:** The dashboard runs entirely on-premise, ensuring sensitive data stays protected. - **Flexible reporting:** E... --- ## Ansible Automation Platform 2.7 — Automation Portal and EE Builder URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-7-automation-portal-and-ee-builder Description: AAP 2.7 introduces a visual Execution Environment Builder, self-service template gallery, and guided workflows for platform engineers. # Ansible Automation Platform 2.7 — Automation Portal and EE Builder ## Introduction Red Hat's Ansible Automation Platform 2.7 introduces the **Automation Portal** — a visual self-service interface that transforms Execution Environment (EE) creation from a CLI-only task into a platform engineering experience. No more YAML syntax errors, no more memorizing `ansible-builder` flags. ## What's New in AAP 2.7 ### Automation Portal The Automation Portal provides: - **Visual EE Builder** — drag-and-drop interface for building Execution Environments - **Template Gallery** — pre-built EE templates for common use cases - **Guided Workflows** — step-by-step wizards eliminating YAML errors - **Self-Service** — developers build EEs without platform team bottleneck ### Visual Execution Environment Builder [code example] With the visual builder: 1. Select base image from dropdown 2. Search and add collections visually 3. Python deps auto-resolved from collection metadata 4. One-click build and push to Private Automation Hub ### Template Gallery Pre-built templates for: | Template | Use Case | Collections Included | |----------|----------|---------------------| | Network Automation | Cisco/Arista/Juniper | cisco.ios, arista.eos, junipernetworks.junos | | Cloud Operations | AWS/Azure/GCP | amazon.aws, azure.azcollection, google.cloud | | Security & Compliance | STIG/CIS hardening | ansible.posix, community.general | | Windows Management | AD/GPO/Updates | ansible.windows, community... --- ## Ansible Automation Platform 2.7 Changelog: A Field Guide URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-7-changelog-a-field-guide Description: AAP 2.7 changelog covering Automation Portal, MCP Server, gateway-only architecture, 12 new collections, and the managed rollout timeline. Red Hat Tech Day Netherlands 2026 (3 June 2026, Bunnik) doubled as the General Availability launch for Ansible Automation Platform 2.7. This is a field guide to what actually shipped, plus one playbook that exercises a few of the new pieces end to end. ## Example: touching the new surfaces [code example] Run it against a real 2.7 control plane and it does two small but representative things: it drafts an Execution Environment definition pulling in one of the twelve new content collections announced at Tech Day (Splunk, HashiCorp Vault, Cisco Intersight, plus Microsoft MECM/SCOM, Google Cloud, and Azure round out the list), and it hits the gateway API directly — the only path into AAP 2.7 now that inter-component traffic is gateway-only. ## What's actually new in 2.7 - **Automation Portal** — a self-service front end for launching templates and a visual Execution Environment Builder, so EE definitions like the one above can be assembled in a UI instead of hand-written YAML. - **Automation Intelligent Assistant (BYOK RAG)** — bring-your-own-key retrieval-augmented generation baked into the platform for in-context automation help. - **Hosted MCP Server (Tech Preview)** — exposes 107 tools across 6 tool sets, letting MCP-compatible AI clients drive AAP operations directly. - **Automation Orchestrator (preview, Q3 2026)** — built on Temporal, for durable, long-running workflow orchestration beyond what job templates and workflows handle today. - **12 new content collections**... --- ## Ansible Automation Platform on ARM: Enhance Scalability & Efficiency URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-4-single-node-installation-arm-based-infrastructure-automation Description: Discover how Ansible Automation Platform supports ARM processors, offering flexibility, seamless integration, and increased automation efficiency across. ## Ansible Automation Platform for ARM processors The Ansible Automation Platform offers several benefits for ARM architectures: 1. Flexibility and Portability: Ansible Automation Platform’s support for ARM architectures provides organizations with the flexibility to choose their infrastructure based on their specific needs. It enables the deployment of Ansible Automation Platform on ARM-based systems, allowing users to leverage the benefits of ARM processors, such as power efficiency and scalability. This flexibility and portability make it easier for organizations to adopt Ansible Automation Platform in a wide range of environments, including data centers, edge locations, and IoT devices. 2. Seamless Integration: Ansible Automation Platform integrates seamlessly with ARM-based systems, ensuring smooth automation workflows and processes. The platform supports Ansible modules and playbooks that can be executed on ARM architectures, allowing users to manage and configure ARM-based devices and systems efficiently. This integration simplifies the automation of ARM infrastructure and enables organizations to achieve consistent management across heterogeneous environments. 3. Increased Automation Efficiency: By leveraging Ansible Automation Platform on ARM architectures, organizations can automate their IT infrastructure and operations effectively. Ansible’s declarative language and agentless architecture make it well-suited for managing ARM-based systems. Users can define inf... --- ## Ansible Automation: Transform IT Operations with Ease URL: https://www.ansiblebyexample.com/articles/ansible-automation Description: Discover the power of Ansible Automation for IT operations. Explore key features, benefits, and practical applications to streamline tasks, enhance. ## Ansible Automation: Streamlining IT Operations Ansible Automation is revolutionizing IT operations by providing a simple, agentless, and powerful platform for automating tasks across a wide range of environments. This article explores the fundamentals of Ansible Automation, its key features, benefits, and practical applications in modern IT infrastructures. ## What is Ansible Automation? Ansible Automation is an open-source IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and many other IT needs. Developed by Red Hat, Ansible allows IT administrators and developers to write simple yet powerful automation scripts called playbooks, which are written in YAML, a human-readable data serialization language. ## Key Features of Ansible Automation 1. **Agentless Architecture**: Ansible operates without the need for agent software on remote systems. It leverages existing SSH and WinRM protocols to communicate with nodes, simplifying the setup and reducing the overhead associated with managing agents. 2. **Human-Readable YAML Playbooks**: Ansible playbooks are written in YAML, making them easy to read, write, and understand. This human-readable format ensures that even those with minimal programming experience can create and manage automation tasks. 3. **Idempotency**: Ansible ensures that the system state is consistent regardless of how many times an automation task is run. This ide... --- ## Ansible autoscaling_group Module — Manage AWS Auto Scaling Groups URL: https://www.ansiblebyexample.com/articles/ansible-autoscaling-group-module-manage-aws-auto-scaling-groups Description: Create and configure EC2 Auto Scaling groups for elastic workloads. Hands-on, tested examples and best practices for Ansible autoscaling_group Module. # Ansible autoscaling_group Module — Manage AWS Auto Scaling Groups ## Introduction The `amazon.aws.autoscaling_group` module create and configure EC2 Auto Scaling groups for elastic workloads. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.autoscaling_group` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run... --- ## Ansible AWS Automation — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-amazon-web-services-aws-by-examples Description: Learn how to automate AWS infrastructure using Ansible. This guide covers everything from setup to advanced strategies, enabling efficient cloud. ## How to Configure Ansible Dynamic Inventory for VMware Automating your Amazon Web Services (AWS) Infrastructure with Ansible enables you to achieve Infrastructure as Code (IaC). Using IaC, you can automate your workflows and CI/CD pipelines, helping you meet critical business demands faster. ☁️ Elevate your cloud automation game with "Ansible for AWS"! 🌐 Whether you're a cloud architect, DevOps engineer, or IT professional navigating the AWS landscape, this curated collection of tutorials and guides will help you master Ansible for seamless automation within Amazon Web Services environments. ## AWS Automation with Ansible ### Introduction to Ansible for AWS: Kickstart your journey with a comprehensive overview of Ansible's role in orchestrating AWS resources. Delve into the foundational concepts that make Ansible a powerful tool for AWS automation. ### Setting Up Ansible for AWS: Follow step-by-step guides on configuring Ansible for optimal AWS integration. Learn best practices for setting up your environment and managing AWS infrastructure as code. ### AWS Resource Provisioning: Unleash the power of Ansible for automating the provisioning of AWS resources. Explore how to dynamically create and manage EC2 instances, S3 buckets, and more. ### Configuring AWS Environments: Explore Ansible Playbooks for efficiently configuring and maintaining AWS environments. Master the art of managing AWS settings, networking, and security configurations. ### Securing AWS Deployment... --- ## Ansible AWS EC2 — Launch and Manage Instances URL: https://www.ansiblebyexample.com/articles/ansible-aws-ec2-launch-and-manage-instances Description: Ansible AWS EC2 guide with practical Ansible examples, parameters, and troubleshooting tips. Hands-on, tested examples and best practices for Ansible AWS EC2. # Ansible AWS EC2 — Launch and Manage Instances ## Introduction Launch and Manage Instances. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/pro... --- ## Ansible AWS IAM — Users Roles and Policies URL: https://www.ansiblebyexample.com/articles/ansible-aws-iam-users-roles-and-policies Description: Ansible AWS IAM guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible AWS IAM — Users Roles and Policies ## Introduction Users Roles and Policies. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/productio... --- ## Ansible AWS RDS — Manage Database Instances URL: https://www.ansiblebyexample.com/articles/ansible-aws-rds-manage-database-instances Description: Ansible AWS RDS guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible AWS RDS — Manage Database Instances ## Introduction Manage Database Instances. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/product... --- ## Ansible AWS S3 — Upload Download and Manage Buckets URL: https://www.ansiblebyexample.com/articles/ansible-aws-s3-upload-download-and-manage-buckets Description: Ansible AWS S3 guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible AWS S3 — Upload Download and Manage Buckets ## Introduction Upload Download and Manage Buckets. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for de... --- ## Ansible AWS S3 Bucket — Create URL: https://www.ansiblebyexample.com/articles/create-an-aws-s3-bucket-using-ansible Description: Discover how to automate the creation of AWS S3 buckets using Ansible. Our detailed guide covers the prerequisites, step-by-step playbook creation. ## S3 Bucket AWS S3 bucket is a popular object storage service that offers a cost-effective and scalable solution to store and retrieve large amounts of data. In this article, we will discuss how to create an S3 bucket using Ansible, an open-source automation platform. Ansible is a powerful tool for infrastructure automation, configuration management, and application deployment. It uses YAML-based playbooks to define the desired state of the infrastructure and executes tasks on the target hosts using SSH or other remote protocols. Ansible provides a rich set of modules that can be used to automate various AWS services, including S3. To create an S3 bucket in AWS, DigitalOcean, Ceph, Walrus, FakeS3 and StorageGRID using Ansible, we need to define a playbook that includes the required tasks. The playbook consists of three main sections: - Variables: This section defines the variables that will be used in the playbook. In our example, we define four variables: `bucket_name`, `encryption_type`, `bucket_policy`, and `s3_acl`. We set the default value for encryption_type to an empty string as we are not using encryption in this example. The bucket_policy variable specifies the name of the JSON policy file that will be used to set the bucket policy. We use a generic policy by default. Finally, we set the canned ACL for the bucket to public-read. - Tasks: This section defines the tasks that will be executed on the target hosts. In our example, we define four tasks. The first task... --- ## Ansible AWS VPC — Virtual Private Cloud Networking URL: https://www.ansiblebyexample.com/articles/ansible-aws-vpc-virtual-private-cloud-networking Description: Ansible AWS VPC guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible AWS VPC — Virtual Private Cloud Networking ## Introduction Virtual Private Cloud Networking. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/s... --- ## Ansible AWX — Complete Guide with Tutorials and Examples URL: https://www.ansiblebyexample.com/articles/ansible-for-awx-by-examples Description: Install and configure Ansible AWX with Docker or Kubernetes. Job templates, inventories, credentials, RBAC, REST API, and workflow automation examples. ## Introduction AWX is the open-source web UI and REST API for managing Ansible automation at scale. It provides job scheduling, role-based access control, credential management, and real-time job monitoring — everything a team needs to run Ansible playbooks reliably across their infrastructure. This page collects all AWX tutorials on AnsibleByExample, organized by topic. ## AWX Architecture [code example] ## Key Components | Component | Purpose | |-----------|---------| | **Projects** | Git repos containing playbooks | | **Inventories** | Target hosts (static, dynamic, or smart) | | **Credentials** | SSH keys, cloud tokens, vault passwords | | **Job Templates** | Playbook + inventory + credentials = runnable job | | **Workflows** | Chain job templates with conditional logic | | **Schedules** | Cron-like recurring job execution | | **RBAC** | Teams, users, and granular permissions | | **Notifications** | Slack, email, webhook on job events | ## Tutorials ### Getting Started - What is Ansible AWX? - AWX: Open Source Automation Platform ### Installation - Build AWX in Docker Containers - Install AWX Operator for Kubernetes and OpenShift ### Day-to-Day Usage - Run and Stop AWX in Docker - Run the Latest AWX in Docker - Create AWX Superuser in Docker ### Enterprise Alternative - Ansible Automation Platform Guide - Install AAP on OpenShift ## Quick Start Workflow ### 1. Install AWX [code example] ### 2. Create a Project Link your Git repository containing Ansib... --- ## Ansible AWX — Free Open-Source Tower Alternative URL: https://www.ansiblebyexample.com/articles/awx Description: AWX is the free, open-source Ansible Tower alternative. Install with Docker or Kubernetes, configure job templates, inventories, and credentials. ## Introduction AWX is the open-source upstream project for Red Hat Ansible Automation Platform's Controller component (formerly Ansible Tower). It provides a web UI, REST API, role-based access control, and job scheduling for Ansible playbooks — all free and open source. ## AWX vs Ansible Tower vs AAP | Feature | AWX | Ansible Tower (legacy) | AAP Controller | |---------|-----|----------------------|----------------| | Cost | Free | Subscription | Subscription | | Support | Community | Red Hat | Red Hat | | Release cycle | Frequent | Stable | Stable | | Certified content | No | Yes | Yes | | Analytics | Basic | Yes | Advanced | | EDA | No | No | Yes | | Upgrade path | Manual | Supported | Supported | **Key takeaway:** AWX is ideal for learning, development, and small teams. AAP is for production environments that need support and certified content. ## Key Features ### Web-Based Dashboard AWX provides a complete web UI for: - Launching and monitoring jobs in real time - Managing inventories, credentials, and projects - Viewing job history and output logs - Scheduling recurring automation tasks ### Role-Based Access Control (RBAC) [code example] Permission levels: - **Admin** — full control over the resource - **Execute** — can launch jobs - **Read** — view-only access - **Use** — can use in job templates (for credentials, inventories) ### Job Templates Define reusable automation jobs: | Field | Description | |-------|-------------| | Name | Job template name | | ... --- ## Ansible AWX — Open Source Tower URL: https://www.ansiblebyexample.com/articles/ansible-awx-open-source-tower-alternative Description: AWX is the free, open-source upstream of Ansible Tower. Deploy Ansible automation with web UI, scheduling, RBAC, REST API, and credential management. ## What Is Ansible AWX? Ansible AWX (or simply AWX) is the open-source upstream project for Red Hat Ansible Automation Platform (AAP) Controller (formerly Ansible Tower). It provides a web-based UI, REST API, role-based access control (RBAC), job scheduling, credential management, and inventory syncing — all free. AWX is ideal for teams that need centralized Ansible automation management without the cost of AAP licensing. ## AWX vs Ansible Tower vs AAP [code example] ## Install AWX on Kubernetes (Recommended) The AWX Operator is the recommended deployment method. ### Prerequisites [code example] ### Deploy AWX Operator [code example] ### Deploy AWX Instance [code example] [code example] ## Install AWX with Docker Compose (Development) [code example] ## AWX Core Concepts [code example] ## Configure AWX ### Add a Project (Git Repository) [code example] ### Add an Inventory [code example] ### Dynamic Inventory Sources [code example] ### Create a Job Template [code example] ### Create a Workflow [code example] ## AWX REST API Usage [code example] ## Using awxkit (Python SDK) [code example] ## AWX with ansible-playbook (CLI Alternative) [code example] ## Troubleshooting [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Automation Platform 2.5 Features - Ansible Beginners Guide - Ansible Vault Encrypt Secrets - Ansible CI/CD Pipelines - Ansible Kubernetes Operations ## Conclusion AWX gives you enterprise Ansible ... --- ## Ansible AWX Alternative — Open Source Options Compared URL: https://www.ansiblebyexample.com/articles/ansible-awx-alternative-open-source-options-compared Description: Compare AWX alternatives for Ansible automation: Semaphore, Rundeck, Jenkins, Ansible Navigator, and AAP. Features, pricing, and when to use each. # Ansible AWX Alternative — Open Source Options Compared ## Introduction AWX is the open-source upstream of Red Hat Ansible Automation Platform (AAP). It provides a web UI, REST API, RBAC, and job scheduling for Ansible playbooks. But AWX can be complex to maintain — if you need something simpler, more lightweight, or with different strengths, several alternatives exist. ## Comparison Table | Tool | License | UI | API | RBAC | Scheduling | Complexity | |------|---------|-----|-----|------|-----------|------------| | AWX | Apache 2.0 | Full web UI | REST | Full | Yes | High | | Semaphore | MIT | Clean web UI | REST | Basic | Yes | Low | | Rundeck | Apache 2.0 | Web UI | REST | Full | Yes | Medium | | Jenkins + Ansible | MIT | Web UI | REST | Plugin | Yes | High | | Ansible Navigator | Apache 2.0 | TUI | No | No | No | Low | | AAP (Red Hat) | Commercial | Full web UI | REST | Full | Yes | Medium | | Zuul | Apache 2.0 | Web UI | REST | Yes | Yes | High | ## Ansible Semaphore **Best for:** Small teams wanting a simple AWX alternative [code example] ### Pros - **Lightweight** — single binary, minimal resources - **Simple UI** — clean and intuitive - **Easy install** — no Kubernetes required - **Active development** — frequent releases ### Cons - Limited RBAC (no fine-grained permissions) - No survey/prompt equivalent - Smaller community than AWX - No execution environments support ### When to Choose Semaphore - Small team (< 10 users) - Don't need complex RBAC - Want fas... --- ## Ansible AWX API — Automate Jobs Templates and Inventories URL: https://www.ansiblebyexample.com/articles/ansible-awx-api-automate-jobs-templates-and-inventories Description: Use the AWX REST API with Ansible uri module and awx.awx collection. Launch jobs, manage templates, inventories, credentials, and workflows. # Ansible AWX API — Automate Jobs Templates and Inventories ## Introduction AWX (the upstream of Ansible Automation Platform Controller) provides a REST API for programmatic control of your automation. With the `awx.awx` collection or direct API calls via the `uri` module, you can launch jobs, manage inventories, sync projects, and orchestrate workflows — all from Ansible playbooks or CI/CD pipelines. ## Prerequisites [code example] [code example] ## Authentication [code example] ## Launch a Job Template [code example] ### Via REST API Directly [code example] ## Manage Inventories [code example] ## Manage Credentials [code example] ## Manage Job Templates [code example] ## Workflows [code example] ## CI/CD Integration [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | 401 Unauthorized | Check token validity; regenerate at `/api/v2/tokens/` | | 403 Forbidden | User lacks permission on the resource | | Job stays pending | Check available execution instances; scale AWX | | Inventory sync fails | Verify credentials and source configuration | | Workflow node fails | Check individual job template runs independently first | ## Best Practices 1. **Use OAuth2 tokens** over basic auth — tokens can be scoped and revoked 2. **Use `awx.awx` collection** over raw API — handles pagination and errors 3. **Store credentials in AWX** — not in playbooks or CI/CD variables 4. **Use workflows** for multi-step deployments — built-in success/failu... --- ## Ansible AWX Backup and Restore — Protect Your Automation Data URL: https://www.ansiblebyexample.com/articles/ansible-awx-backup-and-restore-protect-your-automation-data Description: Back up and restore Ansible AWX including PostgreSQL database, secrets, and configuration. Disaster recovery procedures for AWX on Kubernetes and Docker. # Ansible AWX Backup and Restore — Protect Your Automation Data ## Introduction Ansible AWX stores job templates, inventories, credentials, schedules, and execution history in a PostgreSQL database. Losing this data means rebuilding your entire automation platform from scratch. This guide covers backup and restore procedures for both Kubernetes (AWX Operator) and Docker Compose deployments. ## What Gets Backed Up | Component | Contains | Critical? | |-----------|----------|-----------| | PostgreSQL database | All AWX data (jobs, templates, inventories, users) | ✅ Essential | | Secret key | Encryption key for credentials | ✅ Essential | | `/var/lib/awx/projects/` | Manual project files | If not in SCM | | Custom EE images | Execution environment definitions | Rebuild from Containerfile | | `settings.py` overrides | Custom configuration | ✅ Important | ## Kubernetes (AWX Operator) Backup ### Create a Backup [code example] [code example] ### Automated Backup CronJob [code example] ### Restore from Backup [code example] [code example] ## Docker Compose Backup ### Manual Database Backup [code example] ### Automated Backup Script [code example] [code example] ### Restore (Docker Compose) [code example] ## Ansible Playbook for AWX Backup [code example] ## Verify Backup Integrity [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Backup PVC full | Increase storage or reduce retention | | Restore fails with version mismatch | AWX v... --- ## Ansible AWX Custom Credentials — Create and Use Custom Types URL: https://www.ansiblebyexample.com/articles/ansible-awx-custom-credentials-create-and-use-custom-types Description: Create custom credential types in AWX for APIs, cloud providers, and internal services. Injector configuration, input fields, and playbook integration. # Ansible AWX Custom Credentials — Create and Use Custom Types ## Introduction AWX includes built-in credential types for SSH, AWS, Azure, and other common services. But when you need to authenticate against internal APIs, custom cloud endpoints, or third-party services, you create custom credential types. This guide covers the full workflow: defining input fields, configuring injectors, and using custom credentials in playbooks. ## Built-in vs Custom Credential Types | Built-in | Custom | |----------|--------| | Machine (SSH) | Internal REST APIs | | AWS, Azure, GCP | Custom cloud providers | | Vault (HashiCorp) | Database admin credentials | | SCM (Git) | LDAP bind credentials | | Container Registry | Monitoring systems (Datadog, Splunk) | ## Create a Custom Credential Type ### Via AWX UI 1. Navigate to **Administration → Credential Types** 2. Click **Add** 3. Define **Input Configuration** (what users fill in) 4. Define **Injector Configuration** (how it's exposed to playbooks) ### Input Configuration [code example] ### Injector Configuration [code example] ## Common Custom Credential Examples ### REST API Service [code example] ### Kubernetes Kubeconfig [code example] ### Database Admin [code example] ### HashiCorp Consul [code example] ## Use Custom Credentials in Playbooks [code example] [code example] ## AWX API: Create Credential Types Programmatically [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Credential f... --- ## Ansible AWX Survey — Prompt Users for Input at Launch URL: https://www.ansiblebyexample.com/articles/ansible-awx-survey-prompt-users-for-input-at-launch Description: Create AWX job template surveys to prompt users for variables at launch time. Text fields, dropdowns, passwords, and validation for self-service automation. # Ansible AWX Survey — Prompt Users for Input at Launch ## Introduction AWX surveys let you add a form to job templates — users fill in variables (environment, server name, version) before launch without editing playbooks or inventory. Surveys turn complex automation into self-service buttons that anyone on the team can use safely. ## Create a Survey 1. Navigate to **Templates → Your Job Template** 2. Click the **Survey** tab 3. Click **Add** 4. Define questions (fields) ## Field Types | Type | Use Case | Example | |------|----------|---------| | Text | Free-form input | Server hostname | | Textarea | Multi-line input | SSH public key | | Password | Hidden input | Database password | | Integer | Numeric input | Port number | | Float | Decimal input | CPU threshold | | Multiple Choice (single) | Dropdown select | Environment: dev/staging/prod | | Multiple Choice (multiple) | Multi-select | Services to restart | ## Survey Configuration Example ### Environment Selection [code example] ### Server Name [code example] ### Version to Deploy [code example] ### Database Password [code example] ## Use Survey Variables in Playbooks [code example] ## Survey API ### Get Survey Spec [code example] ### Set Survey Spec Programmatically [code example] ### Launch with Survey Answers [code example] ## Variable Precedence Survey variables are injected as **extra vars** — highest precedence: [code example] > ⚠️ Survey variables **override** anything set in the playbook... --- ## Ansible Azure Resource Manager — VMs and Resources URL: https://www.ansiblebyexample.com/articles/ansible-azure-resource-manager-vms-and-resources Description: Ansible Azure Resource Manager guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Azure Resource Manager — VMs and Resources ## Introduction VMs and Resources. Automate Azure infrastructure with Ansible using the `azure.azcollection` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches Azure naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/stag... --- ## Ansible azure_rm_networkinterface Module — Manage Azure Network Interfaces URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-networkinterface-module-manage-azure-network-interfaces Description: Create and configure Azure VM network interfaces and IP configurations. Tested on real machines with clear, copy-paste examples. # Ansible azure_rm_networkinterface Module — Manage Azure Network Interfaces ## Introduction The `azure.azcollection.azure_rm_networkinterface` module create and configure Azure VM network interfaces and IP configurations. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_networkinterface` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for grac... --- ## Ansible azure_rm_resourcegroup Module — Manage Azure Resource Groups URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-resourcegroup-module-manage-azure-resource-groups Description: Create and manage Azure resource groups for organizing cloud resources. Tested on real machines with clear, copy-paste examples. # Ansible azure_rm_resourcegroup Module — Manage Azure Resource Groups ## Introduction The `azure.azcollection.azure_rm_resourcegroup` module create and manage Azure resource groups for organizing cloud resources. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_resourcegroup` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure... --- ## Ansible azure_rm_securitygroup Module — Manage Azure Network Security Groups URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-securitygroup-module-manage-azure-network-security-groups Description: Create NSG rules for Azure network traffic filtering with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible azure_rm_securitygroup Module — Manage Azure Network Security Groups ## Introduction The `azure.azcollection.azure_rm_securitygroup` module create NSG rules for Azure network traffic filtering with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_securitygroup` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful fail... --- ## Ansible azure_rm_storageaccount Module — Manage Azure Storage Accounts URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-storageaccount-module-manage-azure-storage-accounts Description: Create and configure Azure Storage accounts for blob, file, and table storage. With clear, copy-paste, step-by-step examples. # Ansible azure_rm_storageaccount Module — Manage Azure Storage Accounts ## Introduction The `azure.azcollection.azure_rm_storageaccount` module create and configure Azure Storage accounts for blob, file, and table storage. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_storageaccount` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for grace... --- ## Ansible azure_rm_virtualmachine Module — Manage Azure Virtual Machines URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-virtualmachine-module-manage-azure-virtual-machines Description: Create, configure, and manage Azure VMs with Ansible automation. Tested on real machines with clear, copy-paste examples. # Ansible azure_rm_virtualmachine Module — Manage Azure Virtual Machines ## Introduction The `azure.azcollection.azure_rm_virtualmachine` module create, configure, and manage Azure VMs with Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_virtualmachine` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure ha... --- ## Ansible azure_rm_webapp Module — Manage Azure Web Apps URL: https://www.ansiblebyexample.com/articles/ansible-azure-rm-webapp-module-manage-azure-web-apps Description: Deploy and configure Azure App Service web applications with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible azure_rm_webapp Module — Manage Azure Web Apps ## Introduction The `azure.azcollection.azure_rm_webapp` module deploy and configure Azure App Service web applications with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install azure.azcollection` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `azure.azcollection.azure_rm_webapp` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check m... --- ## Ansible azure.azcollection Example: Provision Azure ML and Storage Resources URL: https://www.ansiblebyexample.com/articles/ansible-azure-azcollection-example-provision-azure-ml-and-storage-resources Description: Runnable Ansible playbook example using azure.azcollection to provision Azure ML workspaces and Storage accounts on AAP 2.7. At Red Hat Tech Day Netherlands 2026 (3 June 2026, Bunnik), Red Hat announced 12 new content collections for AAP 2.7, including an expanded `azure.azcollection` covering Azure ML, App Configuration, Front Door, Storage, and Arc/HCI. Below is a runnable playbook that provisions a resource group, a Storage account, and an Azure ML workspace with Ansible. ## Example Playbook [code example] ## What This Does The play runs locally and calls three `azure.azcollection` modules in sequence. First, `azure_rm_resourcegroup` creates the container resource group in `westeurope`. Second, `azure_rm_storageaccount` provisions a `StorageV2` account that the ML workspace uses for artifacts, datasets, and logs. Third, `azure_rm_mlworkspace` creates the Azure ML workspace itself, wiring in the storage account created in the previous task. Each module is idempotent — re-running the playbook against existing resources reports no change instead of failing or duplicating infrastructure. This mirrors the kind of Efficiency and Scale gains Red Hat highlighted for the expanded collection: a single playbook stitches together Storage and ML provisioning that would otherwise require separate ARM templates, Bicep files, or manual portal clicks. ## Notes / Gotchas - **Authentication**: set `AZURE_SUBSCRIPTION_ID`, `AZURE_CLIENT_ID`, `AZURE_SECRET`, and `AZURE_TENANT` as environment variables, or pass them as module parameters. On AAP 2.7, use a Microsoft Azure Resource Manager credential type instea... --- ## Ansible Backup and Restore — Files Databases and Configs URL: https://www.ansiblebyexample.com/articles/ansible-backup-and-restore-files-databases-and-configs Description: Ansible Backup and Restore guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Backup and Restore — Files Databases and Configs ## Introduction Files Databases and Configs. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Backup and Restore requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ... --- ## Ansible Backup and Restore Files — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-backup-and-restore-files-complete-guide Description: Automate file backups with timestamps and rotation using Ansible. Tested on real machines with clear, copy-paste examples. # Ansible Backup and Restore Files — Complete Guide ## Introduction Automate file backups with timestamps and rotation using Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Automate file backups with timestamps and rotation using Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Backup Windows — win_robocopy Playbook URL: https://www.ansiblebyexample.com/articles/backup-with-robocopy-on-windows-ansible-module-win-robocopy Description: Backup Windows 10, 11, Server 2019/2022 files with Ansible win_robocopy and win_copy. Complete playbook with scheduling, exclusions, and verification. ## How to Backup With Robocopy on Windows with Ansible? ## Ansible backing up with RoboCopy > `community.windows.win_robocopy`: Synchronizes the contents of two directories using Robocopy Today we're talking about the Ansible module `win_robocopy`. The full name is `community.windows.win_robocopy`, which means that is part of the collection targeting Windows platforms. Synchronizes the contents of two directories using Robocopy. Under the hood, it uses the RoboCopy utility, since that should be available on most modern Windows systems. ## Parameters - `src` _string_ - source path - absolute or relative - `dest` _string_ - destination path - absolute or relative - `recurse` _string_ - no/yes - Includes all subdirectories - `purge` _string_ - no/yes - Deletes any files/directories found in the destination that do not exist in the source. - `flags` _string_ - Additional flags Let's see the parameter of the `win_robocopy` module. The only mandatory parameters are "src" and "dest" parameters. The "src" parameter is mandatory and specifies the path on the source host that will be synchronized to the destination. The path can be absolute or relative. Same story for the `dest` parameter that specifies the path on the destination host that will be synchronized from the source. Paths could be Local or Remote according to your needs. The "recurse" parameter is default as disabled but you should consider enabling it when you want to synchronize all the subdirectories. If you need t... --- ## Ansible become — Fix sudo Password URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-missing-sudo-password Description: Fix 'Missing sudo password' and 'Incorrect sudo password' Ansible errors. Configure become, NOPASSWD sudoers, and ansible_become_pass securely. ## Introduction Today we're going to talk about Ansible troubleshooting, specifically about missing sudo password and incorrect sudo password. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the missing sudo password and incorrect sudo password and how to solve it! ## error code - missingsudopassword_error.yml [code example] ## error execution [code example] ## troubleshoot [code example] ## verification [code example] ## fix - /etc/sudoers.d/devops [code example] ## fix execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to troubleshoot the`missing sudo password` and `incorrect sudo password` fatal errors. --- ## Ansible become — Privilege Escalation Guide URL: https://www.ansiblebyexample.com/articles/mastering-ansible-become-feature Description: Master Ansible become for privilege escalation — sudo, su, doas, become_user, become_method, become_flags, passwords, and network enable mode. Complete. ## Introduction Ansible's `become` feature handles privilege escalation — running tasks as `root` or another user when your connection user lacks the required permissions. It replaces the deprecated `sudo:` directive with a flexible, pluggable system supporting `sudo`, `su`, `doas`, `pfexec`, `runas` (Windows), and network `enable` mode. This article covers every `become` directive, practical examples, password handling, security best practices, and troubleshooting. ## Quick Start [code example] Run with: [code example] ## Become Directives Reference | Directive | Default | Scope | Description | |---|---|---|---| | `become` | `false` | play, task, block | Enable privilege escalation | | `become_user` | `root` | play, task, block | User to escalate to | | `become_method` | `sudo` | play, task, block | Escalation method | | `become_flags` | — | play, task, block | Extra flags for the method | | `become_exe` | — | play, task, block | Path to the escalation binary | ### Command-Line Equivalents | CLI Flag | Directive | Description | |---|---|---| | `-b` / `--become` | `become: true` | Enable become | | `-K` / `--ask-become-pass` | — | Prompt for become password | | `--become-user USER` | `become_user` | Set become user | | `--become-method METHOD` | `become_method` | Set become method | ### Connection Variables [code example] | Variable | Description | |---|---| | `ansible_become` | Enable become for host | | `ansible_become_user` | Become user | | `ansible_become_met... --- ## Ansible become — Privilege Escalation Guide (sudo, su) URL: https://www.ansiblebyexample.com/articles/ansible-become-privilege-escalation-sudo Description: How to escalate privileges in Ansible with become. Run tasks as root or other users with sudo, su, doas. Configure passwordless sudo and become_user. ## What Is become in Ansible? `become` is how Ansible escalates privileges — run tasks as `root` or any other user. By default, it uses `sudo`, but also supports `su`, `pbrun`, `pfexec`, `doas`, and others. You can set it at play level, task level, or in configuration. ## Basic Usage [code example] [code example] ## become Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `become` | `false` | Enable privilege escalation | | `become_user` | `root` | User to become | | `become_method` | `sudo` | Method: `sudo`, `su`, `doas`, `pbrun`, etc. | | `become_flags` | — | Extra flags for the become method | ## Run as a Specific User [code example] ## become_method [code example] ## Configuration ### ansible.cfg [code example] ### Command Line [code example] ### Inventory Variables [code example] ## Passwordless sudo The most common setup — configure sudoers so Ansible doesn't need a password: [code example] ## With sudo Password [code example] [code example] ## Practical Patterns ### Switch Between Users in One Play [code example] ### Block with become [code example] ## Troubleshooting ### "Missing sudo password" [code example] ### "sudo: a password is required" but NOPASSWD is set Check sudoers file syntax and permissions: [code example] ### "Failed to set permissions on the temporary files" When becoming an unprivileged user, Ansible needs to set permissions on temp files: [code example] ### become_user Doesn... --- ## Ansible become sudo Password Required — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-become-sudo-password-required-fix-and-solutions Description: Fix missing sudo password prompts in automated Ansible runs. Hands-on, tested examples and best practices for Ansible become sudo Password Required. # Ansible become sudo Password Required — Fix and Solutions ## Introduction Fix missing sudo password prompts in automated Ansible runs. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix missing sudo password prompts in automated Ansible runs. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible become vs sudo vs su — Privilege Escalation Methods URL: https://www.ansiblebyexample.com/articles/ansible-become-vs-sudo-vs-su Description: Compare Ansible become, sudo, and su for privilege escalation. Learn when to use each method with practical examples for Linux, mixed environments. ## Introduction Most Ansible tasks need root privileges. The `become` system is Ansible's unified way to handle privilege escalation, replacing the older `sudo:` and `su:` directives. This guide covers all escalation methods, when to use each, and security best practices. ## Quick Comparison | Directive | Status | Method | Use Case | |-----------|--------|--------|----------| | `become: true` | ✅ Current | Configurable (default: sudo) | Standard privilege escalation | | `become_method: sudo` | ✅ Current | sudo | Most Linux systems (default) | | `become_method: su` | ✅ Current | su | Switch to specific user | | `become_method: doas` | ✅ Current | doas | OpenBSD, security-focused | | `become_method: runas` | ✅ Current | runas | Windows | | `sudo: true` | ❌ Removed | sudo | Legacy (Ansible < 2.0) | ## become — Standard Usage [code example] ## become_user — Run as Specific User [code example] ## become_method — Escalation Backend [code example] ## Configuration ### ansible.cfg [code example] ### Command Line [code example] ### Per-Host in Inventory [code example] ## Passwordless sudo Setup [code example] ## Security Best Practices [code example] ## Common Mistakes [code example] ## Related Articles - Ansible become Privilege Escalation - Ansible SSH Key Management - Ansible Vault Guide - Ansible Vault encrypt_string vs vault file ## Conclusion **become: true** is the standard way to escalate privileges in Ansible. Default method is **sudo** (works on mos... --- ## Ansible become_method — sudo, su, doas, runas Privilege Escalation URL: https://www.ansiblebyexample.com/articles/ansible-become-method-sudo-su-doas-runas-privilege-escalation Description: Configure Ansible become_method for privilege escalation. Use sudo, su, doas, pfexec, runas for Linux, BSD, and Windows with practical examples. # Ansible become_method — sudo, su, doas, runas Privilege Escalation ## Introduction Ansible's `become` system handles privilege escalation — running tasks as root or another user. While most people use `sudo` (the default), Ansible supports multiple escalation methods: `su`, `doas` (OpenBSD), `pfexec` (Solaris), `runas` (Windows), and more. This guide covers when and how to use each method. ## Available Methods | Method | Platform | Use Case | |--------|----------|----------| | `sudo` | Linux, macOS | Default; most common | | `su` | Linux, Unix | Switch user with password | | `doas` | OpenBSD, Linux | Minimal sudo alternative | | `pfexec` | Solaris/Illumos | RBAC-based privilege | | `runas` | Windows | Run as different Windows user | | `machinectl` | Linux (systemd) | Escalation in containers | | `dzdo` | Linux (Centrify) | Centrify DirectAuthorize | | `pmrun` | Linux (Privilege Manager) | BeyondTrust escalation | ## Configuration Levels ### ansible.cfg (Global) [code example] ### Inventory (Per Host/Group) [code example] ### Play Level [code example] ### Task Level [code example] ## sudo (Default) [code example] ### sudoers Configuration [code example] ## su [code example] ## doas (OpenBSD) [code example] [code example] ## runas (Windows) [code example] ## Mixed Environments [code example] ## Passing Become Passwords [code example] [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "sudo: a password is required" | Ad... --- ## Ansible Best Practices — Write Clean, Maintainable Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-best-practices-clean-maintainable-playbooks Description: Essential Ansible best practices: directory structure, naming conventions, idempotency, vault secrets, roles, linting, and CI/CD integration. Proven. # Ansible Best Practices — Write Clean, Maintainable Playbooks These practices come from real-world production experience managing hundreds of servers with Ansible. Follow them to build automation that scales. ## Directory Structure [code example] ## 1. Use FQCN for All Modules Always use Fully Qualified Collection Names: [code example] ## 2. Name Every Task [code example] ## 3. Use Roles for Reusable Logic [code example] ## 4. Keep Secrets in Vault [code example] Prefix vault variables with `vault_` to make them easy to identify. ## 5. Write Idempotent Tasks [code example] ## 6. Use Handlers for Service Restarts [code example] ## 7. Lint Your Playbooks [code example] ## 8. Use Tags for Selective Execution [code example] [code example] ## 9. Test with Check Mode [code example] ## 10. Use group_vars and host_vars [code example] ## Quick Reference | Practice | Why | |----------|-----| | FQCN modules | Avoids name conflicts | | Name every task | Readable output | | Use roles | Reusability | | Vault for secrets | Security | | Idempotent tasks | Safe to re-run | | Handlers for restarts | Restart only when needed | | Lint playbooks | Catch issues early | | Tags | Selective execution | | Check mode | Safe testing | | group_vars/host_vars | Clean variable management | ## Related Articles - FQCN in Ansible — Fully Qualified Collection Names - Ansible Vault — Encrypt secrets - Ansible Dry Run — Check and diff mode - Ansible Error Handling — Rescue and igno... --- ## Ansible Best Practices 2026 — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-best-practices-2026-complete-guide Description: Updated Ansible best practices for 2026: project structure, naming, security, performance, and team workflows. With clear, copy-paste, step-by-step examples. # Ansible Best Practices 2026 — Complete Guide ## Introduction Updated Ansible best practices for 2026: project structure, naming, security, performance, and team workflows. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Updated Ansible best practices for 2026: project structure, naming, security, performance, and team workflows. Start with t... --- ## Ansible BIND DNS — Automate DNS Server Deployment URL: https://www.ansiblebyexample.com/articles/ansible-bind-dns-deploy-and-manage-dns-servers Description: Automate BIND9 DNS server deployment with Ansible. Configure zones, records, forwarders, DNSSEC, and primary/secondary replication. # Ansible BIND DNS — Deploy and Manage DNS Servers ## Introduction BIND (Berkeley Internet Name Domain) is the most widely used DNS server software. Automating DNS with Ansible ensures consistent zone configurations, proper replication between primary and secondary servers, and reliable record management across your infrastructure. ## Install BIND9 [code example] ## Named Options Template [code example] ## Forward Zone Template [code example] ## Reverse Zone Template [code example] ## Primary/Secondary Replication [code example] ## Dynamic DNS Updates [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Zone not loading | `named-checkzone example.com /etc/bind/zones/db.example.com` | | Config syntax error | `named-checkconf` — shows line numbers | | SERVFAIL responses | Check forwarders are reachable | | Zone transfer failed | Verify `allow-transfer` includes secondary IP | | Serial not incrementing | Ensure serial increases on every zone change | ## Best Practices 1. **Increment serial on every change** — use epoch or YYYYMMDDNN format 2. **Validate before reload** — `named-checkconf` and `named-checkzone` 3. **Restrict zone transfers** — `allow-transfer { secondary_ip; };` 4. **Use TSIG keys** for secure dynamic updates 5. **Monitor with `dig`** — `dig @localhost example.com` after changes 6. **Log queries selectively** — enable only for troubleshooting ## Conclusion Ansible makes BIND DNS management repeatable and version-contro... --- ## Ansible BIND DNS — Deploy and Manage DNS Servers URL: https://www.ansiblebyexample.com/articles/ansible-bind-dns-server-zones-records Description: Deploy BIND9 DNS servers with Ansible. Primary and secondary zones, A/AAAA/CNAME/MX/TXT records, reverse DNS, DNSSEC signing, split-horizon DNS. ## Introduction BIND (Berkeley Internet Name Domain) is the most widely deployed DNS server software. Ansible automates DNS infrastructure — install BIND, template zone files from variables, manage A/AAAA/CNAME/MX/TXT/SRV records, configure primary-secondary replication, enable DNSSEC, and set up split-horizon DNS. All DNS records become code. ## Install BIND [code example] ### named.conf.options [code example] ## Forward Zone [code example] [code example] ### Zone File Template [code example] ### Zone Variables [code example] ## Reverse DNS Zone [code example] ## Validate and Test [code example] ## Primary-Secondary Replication [code example] ## Troubleshooting ### Zone Transfer Failing [code example] ### Serial Number Issues The template uses `ansible_date_time.epoch` as serial. If deploying multiple times per second, use a counter or date-based serial: [code example] ## Related Articles - Ansible Firewall Module - Ansible Let's Encrypt SSL - Ansible Chrony NTP - Ansible Template Module ## Conclusion Ansible turns DNS records into YAML variables — adding a record is adding a line to a list, and `named-checkzone` validates before applying. Template zone files from inventory, configure primary-secondary replication, and manage all record types (A, AAAA, CNAME, MX, TXT, SRV, PTR). DNS as code means every change is versioned, reviewed, and reproducible. --- ## Ansible block vs rescue vs always — Error Handling Patterns URL: https://www.ansiblebyexample.com/articles/ansible-block-vs-rescue-vs-always Description: Master Ansible block, rescue, and always for error handling. Learn try-catch patterns, cleanup tasks, and real-world examples for robust playbooks. ## Introduction Ansible's `block`/`rescue`/`always` is the equivalent of try/catch/finally in programming languages. `block` groups tasks that might fail, `rescue` handles failures, and `always` runs cleanup regardless of success or failure. This pattern replaces fragile `ignore_errors` with structured error handling. ## Basic Structure [code example] ## block — Group Tasks [code example] ## rescue — Handle Failures [code example] ### rescue Variables [code example] ## always — Guaranteed Cleanup [code example] ## Real-World Patterns ### Rolling Deploy with Rollback [code example] ### Database Migration with Savepoint [code example] ## block vs ignore_errors [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Error Handling - Ansible changed_when / failed_when - Ansible Troubleshooting - Ansible Handlers Guide ## Conclusion `block` groups related tasks and applies shared attributes. `rescue` catches failures and runs recovery logic (rollback, notification). `always` guarantees cleanup runs regardless of outcome (release locks, re-enable monitoring, restore LB). This pattern replaces `ignore_errors` with intentional, structured error handling. The most common real-world use: deploy in `block`, rollback in `rescue`, re-enable load balancer in `always`. --- ## Ansible blockinfile Module — Edit Multi-Line Text in Files URL: https://www.ansiblebyexample.com/articles/edit-multi-line-text-ansible-module-blockinfile Description: Master the Ansible blockinfile module — insert, update, and remove multi-line text blocks in files. Complete guide with markers, validation, templates,. ## Introduction The `ansible.builtin.blockinfile` module inserts, updates, or removes blocks of multi-line text in files. Unlike `lineinfile` (which handles single lines), `blockinfile` manages entire text blocks surrounded by customizable marker lines — making it easy to identify and update Ansible-managed sections. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | File path to edit | | `block` | string | No | Multi-line text to insert | | `state` | string | No | `present` (default) or `absent` | | `insertafter` | string | No | Insert after this regex (or `EOF`) | | `insertbefore` | string | No | Insert before this regex (or `BOF`) | | `marker` | string | No | Marker template (default: `# {mark} ANSIBLE MANAGED BLOCK`) | | `marker_begin` | string | No | Begin marker text (default: `BEGIN`) | | `marker_end` | string | No | End marker text (default: `END`) | | `create` | bool | No | Create file if missing | | `backup` | bool | No | Create backup before editing | | `validate` | string | No | Validation command | | `owner` | string | No | File owner | | `group` | string | No | File group | | `mode` | string | No | File permissions | ## Basic Usage ### Insert a Block [code example] Result in `/etc/hosts`: [code example] ### Remove a Block [code example] ### Update a Block Simply run the task again with new content — the block between the markers is replaced entirely: [code exampl... --- ## Ansible blockinfile Module: Manage Text Blocks URL: https://www.ansiblebyexample.com/articles/ansible-blockinfile-module-manage-text-blocks Description: Ansible blockinfile inserts, updates, or removes multi-line text blocks using marker comments — ideal for config sections, SSH keys, and structured content. ## Introduction `ansible.builtin.blockinfile` inserts, updates, or removes a block of text in a file. Unlike `lineinfile` (single lines), `blockinfile` manages multi-line content — configuration blocks, script sections, and structured entries. It uses marker comments to track its blocks. ## Basic Usage [code example] This produces: [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `path` | (required) | File to modify | | `block` | `""` | Text block to insert (empty = remove block) | | `marker` | `"# {mark} ANSIBLE MANAGED BLOCK"` | Marker template (`{mark}` → BEGIN/END) | | `marker_begin` | `BEGIN` | Text for `{mark}` in opening marker | | `marker_end` | `END` | Text for `{mark}` in closing marker | | `insertafter` | `EOF` | Insert after this regex | | `insertbefore` | — | Insert before this regex | | `create` | `false` | Create file if it doesn't exist | | `state` | `present` | `present` or `absent` | | `backup` | `false` | Create backup before modifying | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions | ## Custom Markers Use custom markers to manage multiple blocks in the same file: [code example] Result: [code example] ## Insert Position [code example] ## Remove a Block [code example] ## Practical Patterns ### /etc/hosts Management [code example] ### Nginx Server Block [code example] ### SSH Authorized Keys [code example] ### Sudoers Configuration [cod... --- ## Ansible Blue-Green Deployment — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-blue-green-deployment-complete-guide Description: Implement zero-downtime blue-green deployments with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Blue-Green Deployment. # Ansible Blue-Green Deployment — Complete Guide ## Introduction Implement zero-downtime blue-green deployments with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Implement zero-downtime blue-green deployments with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible bower Module — Manage Frontend Packages with Bower URL: https://www.ansiblebyexample.com/articles/ansible-bower-module-manage-frontend-packages-with-bower Description: Install and manage frontend JavaScript packages using Bower package manager. Hands-on, tested examples and best practices for Ansible bower Module. # Ansible bower Module — Manage Frontend Packages with Bower ## Introduction The `community.general.bower` module install and manage frontend JavaScript packages using Bower package manager. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.bower` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run ... --- ## Ansible Builder — Build Custom Execution Environments URL: https://www.ansiblebyexample.com/articles/ansible-builder-build-custom-execution-environments Description: Build custom Ansible Execution Environments with ansible-builder. Create EE images with collections, Python packages, and system dependencies for. # Ansible Builder — Build Custom Execution Environments ## Introduction Ansible Builder (`ansible-builder`) is a command-line tool that creates container images called Execution Environments (EEs). EEs package ansible-core, collections, Python libraries, and system dependencies into a single container — ensuring consistent playbook execution across development, CI/CD, and production. ## Install ansible-builder [code example] ## Execution Environment Definition The `execution-environment.yml` file defines what goes into your EE: [code example] ## Build the EE Image [code example] ## EE Definition File Versions [code example] ## Use Separate Requirements Files [code example] [code example] [code example] [code example] ## Run Playbooks with Custom EE [code example] ## Multi-Stage Build Example [code example] ## Inspect an EE [code example] ## CI/CD Pipeline [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Execution Environments vs virtualenv vs Docker - Ansible at Scale — Patterns for Large Fleets - Ansible Navigator — Modern CLI Interface - Ansible Automation Platform Architecture ## Conclusion `ansible-builder build -t` is the core command for creating Execution Environments. Define your dependencies in `execution-environment.yml`, build with a single command, and push to a container registry. EEs eliminate "works on my machine" problems and ensure every playbook run uses identical dependencies. --- ## Ansible bundler Module — Manage Ruby Gems with Bundler URL: https://www.ansiblebyexample.com/articles/ansible-bundler-module-manage-ruby-gems-with-bundler Description: Install Ruby gem dependencies using Bundler in Ansible automation. Hands-on, tested examples and best practices for Ansible bundler Module. # Ansible bundler Module — Manage Ruby Gems with Bundler ## Introduction The `community.general.bundler` module install Ruby gem dependencies using Bundler in Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.bundler` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--ch... --- ## Ansible by Example books by Apress URL: https://www.ansiblebyexample.com/articles/ansible-by-example-books-by-apress Description: Learn how to automate VMware infrastructure and Kubernetes clusters with Ansible. The books “Ansible for VMware by Examples” and “Ansible for. Buy on Apress Buy on Amazon The books "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example" provides a comprehensive guide on how to automate various tasks in VMware and Kubernetes using Ansible, an open-source IT automation tool. Here are some key points about the book and its value: 1. Automation of Kubernetes Infrastructure: The book focuses on using Ansible to automate different aspects of Kubernetes infrastructure, including pods, services, storage, and cluster management. By automating these tasks, IT professionals can save time, reduce human errors, and create more robust cloud-native applications. 2. Infrastructure as Code (IaC): The book emphasizes the concept of Infrastructure as Code, which involves managing infrastructure resources through machine-readable code. Ansible allows you to define and deploy your Kubernetes infrastructure using human-readable YAML files, making it easier to understand and maintain your infrastructure configuration. 3. Real-Life Use Cases: Each chapter of the book explores a specific use case for automating Kubernetes with Ansible. It provides code Playbooknstrations and real-life examples to illustrate how Ansible can be applied in practical scenarios. This hands-on approach helps readers understand the concepts better and apply them to their own environments. 4. Ansible Troubleshooting: The book covers Ansible troubleshooting techniques, helping readers identify and resolve common issues that may arise during au... --- ## Ansible BYOK Example: Add Company Runbooks to the Intelligent Assistant RAG URL: https://www.ansiblebyexample.com/articles/ansible-byok-example-add-company-runbooks-to-the-intelligent-assistant-rag Description: Configure AAP 2.7 BYOK Tech Preview to ingest a company runbook into the Intelligent Assistant RAG pipeline with a working Ansible playbook example. Red Hat AAP 2.7 introduces BYOK ("Bring Your Own Knowledge") as a Tech Preview feature, announced at Red Hat Tech Day Netherlands 2026 in Bunnik. BYOK lets you inject internal documents — runbooks, change-management procedures, network naming conventions, compliance policies — into the Intelligent Assistant's RAG pipeline, so chatbot answers reflect your organization's own standards instead of generic Ansible documentation. Below is an example playbook that uploads a runbook document into the BYOK knowledge source. [code example] ## What it does and why The play targets two Tech Preview BYOK endpoints exposed by AAP 2.7's gateway API. The first task creates (or confirms) a named knowledge source — a logical bucket for related documents, such as `network-ops-runbooks` or `pci-dss-controls`. The second task uploads a Markdown runbook (`incident-response-vlan-outage.md`) into that source as a multipart file; AAP queues it for chunking, embedding, and indexing into the Intelligent Assistant's vector store. Once ingestion completes, the chatbot embedded in the AAP UI can cite that runbook when a user asks about the specific incident procedure, instead of falling back to generic upstream Ansible guidance. BYOK targets the Intelligent Assistant only — it does not extend to the Coding Assistant (the VS Code extension), which has a separate BYOM provider matrix. ## Notes / Gotchas - BYOK is Tech Preview in AAP 2.7 as of Red Hat Tech Day Netherlands 2026 — the API paths above are... --- ## Ansible BYOM Providers Compared: Choosing a Backend for AAP AI Features URL: https://www.ansiblebyexample.com/articles/ansible-byom-providers-compared-choosing-a-backend-for-aap-ai-features Description: Compare Red Hat AI, OpenAI, Azure OpenAI, watsonx, and Gemini/Vertex as BYOM backends for AAP 2.7's Intelligent Assistant and Coding Assistant. AAP 2.7 lets you Bring Your Own Model (BYOM) to power its AI features, but not every provider is wired up to both the Intelligent Assistant and the Coding Assistant yet. Red Hat laid out the full compatibility matrix at Red Hat Tech Day Netherlands 2026 in Bunnik — here it is, plus how to point each feature at a provider once it's supported. [code example] ## What this does The play POSTs a BYOM provider definition to the AAP Gateway API, telling the Intelligent Assistant which external model to use and where to reach it. The `provider_type` and `feature` fields are the two values you check against the compatibility matrix below before running this against a real environment — pointing an unsupported provider/feature pair at the API will simply be rejected by the Gateway. ## The compatibility matrix As of AAP 2.7, per Red Hat Tech Day Netherlands 2026: | Provider | Intelligent Assistant (chatbot in AAP UI) | Coding Assistant (Ansible VS Code extension) | |---|---|---| | Red Hat AI | Supported (AAP 2.6+) | Supported (AAP 2.6+) | | OpenAI | Supported (AAP 2.6+) | Coming Soon | | Azure OpenAI | Supported (AAP 2.6+) | Coming Soon | | IBM watsonx | Not supported | Supported (AAP 2.5+) | | Google Gemini / Vertex AI | Coming Soon | Supported (AAP 2.6+) | Two things stand out. First, Red Hat AI is the only provider that already covers both features end to end — it's the safest default if you want one backend for everything. Second, watsonx and OpenAI/Azure OpenAI are currently... --- ## Ansible Cache Plugins — Fact Caching for Performance URL: https://www.ansiblebyexample.com/articles/ansible-cache-plugins-fact-caching-performance Description: Speed up Ansible with cache plugins for fact caching. Configure Redis, JSON file, memcached, and MongoDB backends. Reduce gather_facts overhead across. # Ansible Cache Plugins — Fact Caching for Performance ## Introduction Every time Ansible runs a playbook, it gathers facts from every host — hardware info, network configuration, OS details. For large inventories (hundreds or thousands of hosts), this adds minutes to every run. Cache plugins solve this by storing gathered facts between playbook runs. The next run reads cached facts instead of re-gathering them, dramatically reducing execution time. ## How Fact Caching Works \`\`\` Without caching: Run 1: gather_facts (60s) → tasks (30s) = 90s Run 2: gather_facts (60s) → tasks (30s) = 90s With caching: Run 1: gather_facts (60s) → cache facts → tasks (30s) = 90s Run 2: read cache (1s) → tasks (30s) = 31s ← 66% faster \`\`\` ## Available Cache Plugins | Plugin | Backend | Shared | Persistent | Best For | |--------|---------|--------|------------|----------| | \`memory\` | RAM | No | No | Default (single run) | | \`jsonfile\` | JSON files | Yes* | Yes | Simple setups | | \`yaml\` | YAML files | Yes* | Yes | Human-readable cache | | \`redis\` | Redis server | Yes | Yes | Teams, CI/CD, Tower | | \`memcached\` | Memcached | Yes | No | High-speed, ephemeral | | \`mongodb\` | MongoDB | Yes | Yes | Large inventories | | \`pickle\` | Pickle files | Yes* | Yes | Fast serialization | \* File-based plugins are shared if the cache directory is on shared storage. ## JSON File Cache (Simplest) \`\`\`ini # ansible.cfg [defaults] gathering = smart fact_caching = jsonfile fa... --- ## Ansible Callback Plugin Development — Custom Output URL: https://www.ansiblebyexample.com/articles/ansible-callback-plugin-development-custom-output Description: Ansible Callback Plugin Development guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Callback Plugin Development — Custom Output ## Introduction Custom Output. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Callback Plugin Development requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible Callback Plugins — Customize Output and Notifications URL: https://www.ansiblebyexample.com/articles/ansible-callback-plugins-customize-output-notifications Description: Use Ansible callback plugins to customize output format, send notifications, profile task performance, and integrate with monitoring tools. ## Introduction Callback plugins customize what Ansible does during execution — change output format, profile task timing, send notifications on failure, or integrate with monitoring. They hook into events like task start, task completion, play end, and runner failure. ## Built-in Callbacks ### Change Output Format [code example] | Callback | Description | |----------|-------------| | `default` | Standard output | | `yaml` | YAML-formatted (most readable) | | `json` | JSON output | | `dense` | Minimal one-line per task | | `debug` | Verbose debug output | | `minimal` | Bare minimum | | `null` | No output | | `tree` | Save output per host to files | | `unixy` | Unix-style condensed | ### Enable Additional Callbacks [code example] ## Profile Tasks (Performance) [code example] Output shows timing for every task: [code example] ### profile_roles [code example] Shows total time per role: [code example] ## Notification Callbacks ### Slack Notification [code example] ### Email on Failure [code example] ### Log to Syslog [code example] ### Log to File (JSON) [code example] ## Custom Callback Plugin [code example] [code example] ## Event Hooks | Hook | Fires When | |------|-----------| | `v2_playbook_on_start` | Playbook begins | | `v2_playbook_on_play_start` | Play begins | | `v2_playbook_on_task_start` | Task begins | | `v2_runner_on_ok` | Task succeeds | | `v2_runner_on_failed` | Task fails | | `v2_runner_on_skipped` | Task skipped | | `v2_runner_on_unr... --- ## Ansible Callback Plugins — Profiling URL: https://www.ansiblebyexample.com/articles/profiling-troubleshooting-and-optimizing-resources-ansible-automation-platform Description: Use Ansible callback plugins to profile task execution time, identify slow tasks, and customize output. Configure timer, profile_tasks, and profile_roles. ## Introduction Ansible callback plugins customize playbook output and provide additional functionality during execution. The three most useful built-in callbacks — `timer`, `profile_tasks`, and `profile_roles` — help you identify performance bottlenecks by measuring execution time at the playbook, task, and role level. This article covers configuration, all major callback plugins, writing custom callbacks, and using profiling data to optimize playbooks. ## Quick Start Add to your `ansible.cfg`: [code example] Install the collection: [code example] Run any playbook — you'll see timing data automatically: [code example] ## The Three Profiling Callbacks ### ansible.posix.timer Shows total playbook execution time: [code example] ### ansible.posix.profile_tasks Shows execution time for every task, sorted by duration: [code example] ### ansible.posix.profile_roles Shows aggregated execution time per role: [code example] ## Configuration Options ### ansible.cfg [code example] ### Environment Variables [code example] ### Per-Playbook Override [code example] ## All Built-in Callback Plugins | Plugin | Type | Description | |---|---|---| | `ansible.posix.timer` | aggregate | Total playbook execution time | | `ansible.posix.profile_tasks` | aggregate | Per-task execution time | | `ansible.posix.profile_roles` | aggregate | Per-role execution time | | `ansible.builtin.default` | stdout | Default human-readable output | | `ansible.builtin.minimal` | stdout | Min... --- ## Ansible Canary Deployment — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-canary-deployment-complete-guide Description: Roll out changes to a subset of servers first with Ansible serial, batch_size, and health verification. Tested on real machines with clear, copy-paste examples. # Ansible Canary Deployment — Complete Guide ## Introduction Roll out changes to a subset of servers first with Ansible serial, batch_size, and health verification. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use `block/rescue/always` for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked before action | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Roll out changes to a subset of servers first with Ansible serial, batch_size, and health verification. Use check mode for validation, handle errors gracefully, and always test in a non-production environment first. --- ## Ansible Canary Deployment Strategy — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-canary-deployment-strategy-complete-guide Description: Roll out changes to a subset of servers first with Ansible serial. Tested on real machines with clear, copy-paste examples. # Ansible Canary Deployment Strategy — Complete Guide ## Introduction Roll out changes to a subset of servers first with Ansible serial. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Roll out changes to a subset of servers first with Ansible serial. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Cannot Find Role Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-cannot-find-role-error-fix-and-solutions Description: Fix role not found errors from wrong paths, Galaxy installs, and requirements. Tested on real machines with clear, copy-paste examples. # Ansible Cannot Find Role Error — Fix and Solutions ## Introduction Fix role not found errors from wrong paths, Galaxy installs, and requirements. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix role not found errors from wrong paths, Galaxy installs, and requirements. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible capabilities Module — Manage Linux File Capabilities URL: https://www.ansiblebyexample.com/articles/ansible-capabilities-module-manage-linux-file-capabilities Description: Set and manage Linux file capabilities (cap_net_bind, cap_sys_admin) on executables. With clear, copy-paste, step-by-step examples. # Ansible capabilities Module — Manage Linux File Capabilities ## Introduction The `community.general.capabilities` module set and manage Linux file capabilities (cap_net_bind, cap_sys_admin) on executables. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.capabilities` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Tes... --- ## Ansible cargo Module — Install Rust Packages with Cargo URL: https://www.ansiblebyexample.com/articles/ansible-cargo-module-install-rust-packages-with-cargo Description: Build and install Rust crates using Cargo package manager with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible cargo Module — Install Rust Packages with Cargo ## Introduction The `community.general.cargo` module build and install Rust crates using Cargo package manager with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.cargo` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--... --- ## Ansible Ceph — Deploy Distributed Storage Clusters URL: https://www.ansiblebyexample.com/articles/ansible-ceph-distributed-storage-cluster Description: Deploy Ceph distributed storage with Ansible using cephadm. Monitor, OSD, and MDS deployment, CephFS, RBD block storage, S3 with RGW, pool management. ## Introduction Ceph is a unified distributed storage system providing block (RBD), file (CephFS), and object (RGW/S3) storage from a single cluster. Ansible automates Ceph deployment using `cephadm` — bootstrap the cluster, add monitors and OSDs, create pools, configure CephFS, and manage the cluster lifecycle. ## Architecture [code example] ## Bootstrap Ceph Cluster [code example] ## Add Hosts to Cluster [code example] ## Deploy OSDs [code example] ## Create Pools [code example] ## CephFS Filesystem [code example] ### Mount CephFS on Clients [code example] ## RGW (S3 Gateway) [code example] ## Health Monitoring [code example] ## Troubleshooting ### OSD Not Starting [code example] ### Slow Requests [code example] ## Related Articles - Ansible MinIO S3 Storage - Ansible Kubernetes - Ansible Docker Compose - Ansible Prometheus Grafana ## Conclusion Ceph provides unified block, file, and object storage from a single cluster — Ansible automates the entire lifecycle with `cephadm`: bootstrap, add hosts and OSDs, create pools, deploy CephFS and RGW, and monitor health. Use Ceph for persistent volumes in Kubernetes, shared filesystems, S3-compatible object storage, and disaster recovery. Ansible makes scaling from 3 to 300 nodes the same playbook with different inventory. --- ## Ansible Certification EX294 Study Guide — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-certification-ex294-study-guide-complete-guide Description: Study guide for Red Hat EX294 RHCE Ansible exam covering all exam objectives with examples. Tested on real machines with clear, copy-paste examples. # Ansible Certification EX294 Study Guide — Complete Guide ## Introduction Study guide for Red Hat EX294 RHCE Ansible exam covering all exam objectives with examples. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Study guide for Red Hat EX294 RHCE Ansible exam covering all exam objectives with examples. Start with the fundamentals, implement... --- ## Ansible Certification EX374 Study Guide — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-certification-ex374-study-guide-complete-guide Description: Complete study guide for Red Hat EX374 Ansible Automation Platform exam with practice exercises. With clear, copy-paste, step-by-step examples. # Ansible Certification EX374 Study Guide — Complete Guide ## Introduction Complete study guide for Red Hat EX374 Ansible Automation Platform exam with practice exercises. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Complete study guide for Red Hat EX374 Ansible Automation Platform exam with practice exercises. Start with the fundamentals,... --- ## Ansible Certified Collections Update May 2026 — MCP, NetCommon, VMware URL: https://www.ansiblebyexample.com/articles/ansible-certified-collections-update-may-2026-mcp-netcommon-vmware Description: May 2026 certified collection updates: ansible.mcp 1.1.0, ansible.netcommon 8.5.2, hpe.oneview 11.2.0, vmware.vmware 2.8.0, and more. What's new. # Ansible Certified Collections Update May 2026 — MCP, NetCommon, VMware ## Introduction Red Hat certifies collections that meet quality, security, and support standards for use with Ansible Automation Platform. The May 8, 2026 Bullhorn newsletter announced seven certified collection updates. Here's what changed and whether you should upgrade. ## Updated Collections ### ansible.mcp 1.1.0 The Model Context Protocol (MCP) collection enables Ansible to interact with AI/ML model serving infrastructure. [code example] ### ansible.netcommon 8.5.2 Core networking collection — provides shared plugins for all network modules. This update is especially important given the Paramiko deprecation timeline (removal after 2028-02-01). [code example] ### hpe.oneview 11.2.0 HPE OneView server management — profile templates, server hardware, firmware baselines. [code example] ### juniper.apstra 1.0.8 Juniper Apstra intent-based networking — data center fabric management. ### onepassword.connect 2.4.0 1Password Connect — secrets management integration for Ansible. [code example] ### redhat.eap 1.5.11 Red Hat JBoss Enterprise Application Platform — Java application server management. ### vmware.vmware 2.8.0 VMware vSphere automation — VM lifecycle, networking, storage management. [code example] ## Quick Upgrade [code example] [code example] ## Priority Guide | Collection | Priority | Why | |-----------|----------|-----| | ansible.netcommon 8.5.2 | **High** | Paramiko mi... --- ## Ansible cfg — Configuration File Guide URL: https://www.ansiblebyexample.com/articles/ansible-cfg-configuration-file-guide Description: Configure Ansible behavior with ansible.cfg. Connection settings, privilege escalation, performance tuning, SSH options, and project-level configuration. ## Introduction `ansible.cfg` controls Ansible's behavior — inventory location, SSH settings, privilege escalation, performance tuning, and more. Place it in your project directory for per-project configuration. ## Configuration Precedence Ansible checks these locations (first match wins): 1. `ANSIBLE_CONFIG` environment variable 2. `./ansible.cfg` (current directory) 3. `~/.ansible.cfg` (home directory) 4. `/etc/ansible/ansible.cfg` (global) **Best practice**: Put `ansible.cfg` in your project root. ## Essential Configuration [code example] ## Performance Tuning [code example] ### Impact of Settings | Setting | Impact | |---------|--------| | `forks = 20` | Run on 20 hosts simultaneously (vs 5 default) | | `pipelining = True` | ~2x speed (fewer SSH round-trips) | | `gathering = smart` | Only gather facts once (cached) | | `ControlPersist=600s` | Keep SSH connections open 10 min | ## Security Settings [code example] ## Inventory Configuration [code example] ## Logging [code example] ## Per-Environment Config [code example] [code example] ## Common Patterns ### Development Config [code example] ### Production Config [code example] ### CI/CD Config [code example] ## Environment Variables Override any setting with `ANSIBLE_` prefix: [code example] ## View Current Config [code example] ## Troubleshooting ### Config Not Being Read [code example] ### Pipelining Fails Pipelining requires `requiretty` to be disabled in sudoers: [code example] ##... --- ## Ansible cfg Precedence — Configuration File Load Order URL: https://www.ansiblebyexample.com/articles/ansible-cfg-precedence-configuration-file-load-order Description: Understand ansible.cfg precedence rules: environment variable, current directory, home directory, and system-wide. Override settings per-project safely. # Ansible cfg Precedence — Configuration File Load Order ## Introduction Ansible loads configuration from multiple locations with a strict precedence order. Understanding this hierarchy prevents unexpected behavior when ansible.cfg settings seem to be ignored. This guide covers the full load order, common pitfalls, and how to debug configuration issues. ## Precedence Order (Highest to Lowest) [code example] **First match wins** — Ansible uses the FIRST config file found in this order and ignores all others. It does NOT merge settings from multiple files. ## Detailed Load Order [code example] ## Security: World-Writable Directory Check [code example] ## Environment Variables Override Everything [code example] ## Common ansible.cfg Sections [code example] ## Per-Project Configuration Pattern [code example] [code example] ## Debug: Which Config Is Active? [code example] ## Common Pitfalls | Problem | Cause | Fix | |---------|-------|-----| | Settings ignored | Wrong directory or world-writable | Check `ansible --version` for active config path | | Different behavior in CI vs local | CI uses different working directory | Set `ANSIBLE_CONFIG` explicitly | | Home config pollutes projects | `~/.ansible.cfg` applies globally | Use per-project `./ansible.cfg` instead | | Vault password not found | Relative path in wrong context | Use absolute path or `ANSIBLE_VAULT_PASSWORD_FILE` | | SSH timeout in containers | System `/etc/ansible/ansible.cfg` not present | Includ... --- ## Ansible changed_when — Control Task Change Reporting URL: https://www.ansiblebyexample.com/articles/ansible-changed-when-control-task-change-reporting Description: Use changed_when to override Ansible's change detection. Prevent false changes, ensure idempotent playbooks, and create accurate change reports. # Ansible changed_when — Control Task Change Reporting ## Introduction By default, Ansible marks tasks as "changed" based on the module's return status. But some modules — especially `command`, `shell`, and `raw` — always report changed, even when nothing actually changed. `changed_when` lets you define custom conditions for what constitutes a real change, enabling accurate reporting and proper handler notification. ## Basic Usage [code example] ## Never Changed (Read-Only Tasks) [code example] ## Conditional Change Detection [code example] ## Multiple Conditions [code example] ## With Handlers [code example] ## changed_when vs check_mode [code example] ## Common Patterns [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Command always shows "changed" | Add `changed_when: false` for read-only commands | | Handler fires when nothing changed | Add proper `changed_when` condition | | "changed" count wrong in summary | Review all command/shell tasks for `changed_when` | | Can't determine if changed | Have the command output a known string to match | | Check mode skips tasks | Use `check_mode: false` for safe info-gathering | ## Best Practices 1. **Every `command`/`shell` task needs `changed_when`** — modules handle it; raw commands don't 2. **`changed_when: false` for all read-only commands** — `grep`, `cat`, `ls`, `systemctl status` 3. **Match output text for change detection** — have scripts echo "CHANGED" or "NO_CHANGE" 4. **Use ... --- ## Ansible changed_when and failed_when — Control Task Reporting URL: https://www.ansiblebyexample.com/articles/ansible-changed-when-failed-when-task-reporting Description: Control task status in Ansible with changed_when and failed_when. Practical examples for shell commands, APIs, and custom success conditions. ## Introduction By default, Ansible marks `command`, `shell`, and `raw` tasks as "changed" every run — even when nothing actually changed. `changed_when` and `failed_when` give you precise control over when tasks report as changed or failed. This is essential for idempotent playbooks. ## changed_when — Control "Changed" Status ### Suppress False "Changed" [code example] ### Change Based on Output [code example] ### Change Based on Return Code [code example] ### Multiple Conditions [code example] ## failed_when — Control Failure Status ### Ignore Specific Errors [code example] ### Fail on Specific Output [code example] ### Never Fail (Investigate Later) [code example] ## Combining Both [code example] ## Common Patterns ### Idempotent Shell Commands [code example] ### Check Mode Support [code example] ### API Calls [code example] ### Git Operations [code example] ## Ansible 13 Note In ansible-core 2.20, when using `failed_when` to suppress an error, the `exception` key is renamed to `failed_when_suppressed_exception`. Update any playbooks that check `result.exception`: [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Error Handling - Ansible shell Module - Ansible debug Module - Ansible Troubleshooting ## Conclusion `changed_when: false` on every read-only command. `changed_when: "'keyword' in result.stdout"` for commands that might or might not make changes. `failed_when` to distinguish between expected non-zer... --- ## Ansible Check .NET Framework Version URL: https://www.ansiblebyexample.com/articles/check-registry-net-framework-version-on-windows-like-systems-ansible-module-win-reg-stat Description: Learn how to check the .NET Framework version on Windows systems with Ansible using the win_reg_stat module. Includes a practical Playbook example. ## How to Check the .NET Framework version on Windows-like systems with Ansible? The principle is to read the right Windows Registry key, store in a variable, and display it on the screen. ## Ansible read Windows Registry - `ansible.windows.win_reg_stat` - Get information about Windows registry keys Today we're talking about the Ansible module `win_reg_stat`. The full name is `ansible.windows.win_reg_stat`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It gets information about Windows registry keys. ## Parameters & Return Values ### Parameters - path string - The full registry key path including the hive to search for - name string - key path including the hive to search for ### Main Return Values - exists, value, raw_value, type, sub_keys The only mandatory parameter is "path" which is the full registry key path including the hive to search for. You probably would like to specify also the "name" of the key path including the hive to search for. The module returns multiple properties. The most useful are "exists" if the key/property exist in the registry, The value of the key is accessible via the "value" and "raw_value" attributes. Other useful attributes are "type" for the property type and "sub_key" for a list of all the subkeys of the key specified. ## Links - ansible.windows.win_reg_stat - How to: D... --- ## Ansible Check if File Exists — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-check-if-file-exists-complete-guide Description: Test file existence with stat module and conditional task execution. Hands-on, tested examples and best practices for Ansible Check if File Exists. # Ansible Check if File Exists — Complete Guide ## Introduction Test file existence with stat module and conditional task execution. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Test file existence with stat module and conditional task execution. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Check Mode — Dry Run Playbooks Safely URL: https://www.ansiblebyexample.com/articles/ansible-check-mode-dry-run-playbooks-safely Description: Use ansible --check and --diff to preview changes without modifying systems. Dry run playbooks, validate configurations, and audit infrastructure safely. # Ansible Check Mode — Dry Run Playbooks Safely ## Introduction Check mode (`--check`) runs your playbook without making any changes — it predicts what *would* happen. Combined with `--diff`, it shows exactly what lines in files would change. This is essential for auditing, change management, and building confidence before applying changes to production. ## Basic Usage [code example] ## How Check Mode Works In check mode, Ansible: 1. Connects to hosts normally 2. Gathers facts normally 3. Evaluates conditions normally 4. **Simulates** each task — reports `changed` or `ok` without executing 5. Returns what **would** change [code example] ## Force Check Mode Per Task [code example] ## Skip Check Mode Per Task [code example] ## Diff Mode Diff mode shows line-by-line changes for file-modifying modules: [code example] Output example: [code example] ## Diff with Sensitive Data [code example] ## Check Mode in CI/CD [code example] ## Handling Check Mode Limitations Some modules don't support check mode — they skip entirely: [code example] ## The ansible_check_mode Variable [code example] ## Compliance Auditing Pattern [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Task skipped in check mode | Module doesn't support check; use `check_mode: false` | | False "changed" in check | Module is check-mode aware but state differs | | Dependent tasks fail | Earlier task didn't run; use `check_mode: false` for data-gathering | | No diff ... --- ## Ansible Check Mode (Dry Run) — Test Playbooks Without Making Changes URL: https://www.ansiblebyexample.com/articles/ansible-check-mode-dry-run-test-playbooks Description: Master Ansible check mode for safe dry runs. Use --check, --diff, check_mode per task, and handle modules that don't support check mode. # Ansible Check Mode (Dry Run) ## Basic Usage [code example] ## Per-Task Check Mode [code example] ## Diff Mode [code example] [code example] ## Handle Modules That Don't Support Check Mode [code example] ## Check Mode in Conditionals [code example] ## Best Practice: CI/CD Pipeline [code example] ## Conclusion Always `--check --diff` before applying changes in production. Use `check_mode: false` for tasks that must run even during dry runs (like gathering state). Build check mode into your CI/CD pipeline. --- ## Ansible check mode vs diff mode — Test Playbooks Safely URL: https://www.ansiblebyexample.com/articles/ansible-check-mode-vs-diff-mode Description: Use Ansible check mode and diff mode to test playbooks before applying changes. Learn dry-run workflows, check_mode in tasks, and combining both for safe. ## Introduction Running a playbook against production without testing is asking for trouble. Ansible's check mode (`--check`) and diff mode (`--diff`) let you preview what would change without actually changing anything. This guide covers both modes, how to combine them, and how to handle tasks that don't support check mode. ## Check Mode (Dry Run) [code example] Check mode simulates the playbook: each task reports what it **would** do without making changes. [code example] ### Limitations [code example] ### Force Task to Run in Check Mode [code example] ### Skip Task in Check Mode [code example] ### Detect Check Mode in Tasks [code example] ## Diff Mode (Show Changes) [code example] Diff mode shows exactly what changed in files: [code example] ### Control Diff Per Task [code example] ## Combining Check + Diff [code example] ### Deployment Workflow [code example] ## Per-Task Check Mode Support [code example] ## ansible.cfg Settings [code example] ## Common Mistakes [code example] ## Related Articles - Ansible changed_when / failed_when - Ansible Troubleshooting - Ansible Best Practices - Ansible Strategies Guide ## Conclusion `--check` shows what **would** change. `--diff` shows **how** files would change. Together (`--check --diff`) they give you a complete dry-run preview. Always preview before applying to production. Use `check_mode: false` on tasks that gather data needed by later tasks. Use `diff: false` on sensitive files. The workflow: ... --- ## Ansible Chocolatey — Windows Software URL: https://www.ansiblebyexample.com/articles/install-windows-software-ansible-module-win-chocolatey Description: Automate Windows software installation with Ansible and Chocolatey. Complete guide to win_chocolatey module with package install, upgrade, pin, sources,. ## Introduction Chocolatey is the package manager for Windows — like `apt` for Ubuntu or `dnf` for RHEL. Combined with Ansible's `win_chocolatey` module, you can automate software installation, updates, and management across your entire Windows fleet from a single playbook. ## Module Reference **Full name:** `chocolatey.chocolatey.win_chocolatey` **Collection:** `chocolatey.chocolatey` Install the collection: [code example] ### Key Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | list/string | Yes | Package name(s) to manage | | `state` | string | No | `present`, `latest`, `absent`, `downgrade`, `reinstalled` | | `version` | string | No | Specific version to install | | `pinned` | bool | No | Pin package to prevent upgrades | | `source` | string | No | Custom package source URL | | `install_args` | string | No | Arguments passed to the native installer | | `package_params` | string | No | Parameters passed to the Chocolatey package | | `allow_prerelease` | bool | No | Allow prerelease versions | | `force` | bool | No | Force reinstall even if already installed | | `timeout` | int | No | Timeout in seconds (default: 2700) | ### State Values | State | Behavior | |-------|----------| | `present` | Install if not present (default) | | `latest` | Install or upgrade to latest version | | `absent` | Uninstall the package | | `downgrade` | Downgrade to specified version | | `reinstalled` | Force reinstall | ##... --- ## Ansible Chrony NTP — Configure Time Synchronization URL: https://www.ansiblebyexample.com/articles/ansible-chrony-ntp-time-synchronization Description: Configure time synchronization with Ansible using Chrony and NTP. Set up NTP servers, clients, stratum hierarchy, hardware timestamping, and time drift. # Ansible Chrony NTP — Configure Time Synchronization ## Introduction Accurate time synchronization is critical for distributed systems — log correlation, TLS certificate validation, database replication, and Kerberos authentication all depend on it. Chrony is the default NTP implementation on modern Linux distributions (RHEL 8+, Ubuntu 20.04+), replacing the legacy ntpd. Ansible makes it easy to configure Chrony consistently across your entire fleet. ## Basic Chrony Deployment [code example] ## Configuration Template [code example] ## NTP Server + Client Hierarchy [code example] [code example] ## Firewall Configuration [code example] ## Monitoring and Validation [code example] ## Troubleshooting [code example] ## Related Articles - Ansible systemd Service Management - Ansible Configuration Drift Detection - Ansible Firewalld UFW Module - Ansible assert Module - Ansible Compliance as Code ## Conclusion Chrony is the modern standard for NTP on Linux. With Ansible, you can deploy a consistent time synchronization hierarchy — dedicated NTP servers syncing to public pools, with all other hosts pointing to your internal servers. Add monitoring assertions to catch clock drift before it causes authentication failures or log correlation issues. --- ## Ansible CI CD Pipeline — Jenkins GitLab GitHub Actions URL: https://www.ansiblebyexample.com/articles/ansible-ci-cd-pipeline-jenkins-gitlab-github-actions Description: Ansible CI CD Pipeline guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible CI CD Pipeline — Jenkins GitLab GitHub Actions ## Introduction Jenkins GitLab GitHub Actions. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible CI CD Pipeline requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible CI/CD Integration — GitLab, GitHub Actions, and Jenkins Pipeline Automation URL: https://www.ansiblebyexample.com/articles/ansible-cicd-integration-gitlab-github-actions-jenkins-pipeline Description: Integrate Ansible into CI/CD pipelines with GitLab CI, GitHub Actions, and Jenkins. Automate testing, deployment, and infrastructure changes with approval. ## Introduction Running playbooks manually doesn't scale. CI/CD pipelines turn Ansible automation into a controlled, auditable, and repeatable process: every infrastructure change goes through linting, testing, approval, deployment, and verification. Whether you use GitLab CI, GitHub Actions, or Jenkins, the pattern is the same — lint → test → plan → approve → deploy → verify → rollback if needed. ## Pipeline Stages [code example] ## GitHub Actions ### Basic Pipeline [code example] ## GitLab CI [code example] ## Jenkins ### Jenkinsfile [code example] ## Molecule Testing in CI [code example] [code example] ## Rollback Strategy [code example] ## Related Articles - Ansible Best Practices Guide - Ansible-Lint Guide - Ansible + Terraform Pipeline - Ansible Automation Platform Guide - Ansible Roles for Reusable Automation ## Conclusion Every CI/CD platform follows the same Ansible pattern: lint (yamllint + ansible-lint) → test (Molecule) → dry-run (`--check --diff`) → staging deploy → approval gate → production deploy → verify → notify. GitHub Actions uses `environment:` protection rules for approval gates, GitLab CI uses `when: manual`, and Jenkins uses `input`. Store vault passwords and cloud credentials as CI secrets, never in the repo. The key enterprise requirement is the approval gate between staging and production — manual confirmation that gives teams confidence to automate everything else. --- ## Ansible CIS Hardening — RHEL 9 URL: https://www.ansiblebyexample.com/articles/automating-audit-cis-benchmark-hardening-for-red-hat-enterprise-linux-9-with-ansible Description: Discover how to automate CIS Benchmark hardening for RHEL 9 systems using Ansible. Simplify security compliance with the "ansible-lockdown" project for. ## Introduction As organizations increasingly prioritize cybersecurity and compliance, the need for robust security measures has become paramount. The Center for Internet Security (CIS) Benchmarks provides guidelines and best practices for securing various operating systems. Adhering to these benchmarks for Red Hat Enterprise Linux (RHEL) 9 can be time-consuming and complex. However, this process becomes streamlined and efficient with the power of automation through Ansible. This article explores how using Ansible's automation capabilities with the "ansible-lockdown" project can help organizations automatically implement CIS Benchmark hardening for RHEL 9 systems, ensuring a more secure and compliant environment. - Ansible Lockdown GitHub - Lockdown Enterprise Organization ## What is the CIS Benchmark? The CIS Benchmarks are consensus-based configuration guidelines developed by experts to help organizations safeguard their systems against security threats. These benchmarks cover a wide range of platforms and applications, offering specific recommendations on security settings, configurations, and policies. By adhering to the CIS Benchmark, organizations can reduce the risk of cyberattacks and enhance their overall security posture. ## Introducing Ansible Ansible is an open-source automation tool that simplifies IT infrastructure deployment, configuration, and management. It employs declarative language to describe the desired state of a system, allowing users to automate r... --- ## Ansible cisco.intersight Module Example: Firmware and Port Configuration URL: https://www.ansiblebyexample.com/articles/ansible-cisco-intersight-module-example-firmware-and-port-configuration Description: Runnable Ansible playbook example using cisco.intersight modules for Day-2 firmware upgrades and port configuration on Cisco UCS gear. At Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026), the Ansible team announced 12 new content collections landing in AAP 2.7. Among them, `cisco.intersight` ships 100+ modules aimed squarely at Day-2 network operations: firmware lifecycle and port configuration on Cisco UCS infrastructure managed through Intersight. ## Example playbook [code example] ## What this does and why The playbook targets `localhost` because `cisco.intersight` modules talk to the Intersight cloud/on-prem API rather than SSHing into devices directly — the API key ID and private key are the credential pair Intersight issues for API-driven automation, kept out of the playbook via environment lookups. The first task checks the current firmware version on a server profile. The upgrade task is conditional: it only fires when the installed version doesn't already match the target, which keeps the playbook idempotent and safe to run on every AAP job template execution. The port policy task assigns an uplink role and speed to a specific port on a fabric interconnect, the kind of Day-2 change that used to require a manual click-through in the Intersight GUI. The final task polls until the new firmware version is confirmed, since firmware upgrades trigger a reboot and the API won't reflect the new state instantly. ## Notes and gotchas - **Credentials**: Intersight API keys are organization-scoped. In AAP 2.7, store them as a custom credential type rather than raw environment variables in productio... --- ## Ansible cli_command Module — Run CLI Commands on Network Devices URL: https://www.ansiblebyexample.com/articles/ansible-cli-command-module-run-cli-commands-on-network-devices Description: Execute platform-agnostic CLI commands across network devices with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible cli_command Module — Run CLI Commands on Network Devices ## Introduction The `ansible.netcommon.cli_command` module execute platform-agnostic CLI commands across network devices with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.netcommon` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.netcommon.cli_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in ch... --- ## Ansible cli_config Module — Push CLI Config to Network Devices URL: https://www.ansiblebyexample.com/articles/ansible-cli-config-module-push-cli-config-to-network-devices Description: Deploy configuration to any network device supporting CLI with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible cli_config Module — Push CLI Config to Network Devices ## Introduction The `ansible.netcommon.cli_config` module deploy configuration to any network device supporting CLI with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.netcommon` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.netcommon.cli_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode... --- ## Ansible cloudformation Module — Deploy AWS CloudFormation Stacks URL: https://www.ansiblebyexample.com/articles/ansible-cloudformation-module-deploy-aws-cloudformation-stacks Description: Create, update, and delete AWS CloudFormation stacks with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible cloudformation Module — Deploy AWS CloudFormation Stacks ## Introduction The `amazon.aws.cloudformation` module create, update, and delete AWS CloudFormation stacks with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.cloudformation` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `-... --- ## Ansible cloudwatch_metric_alarm Module — Manage AWS CloudWatch Alarms URL: https://www.ansiblebyexample.com/articles/ansible-cloudwatch-metric-alarm-module-manage-aws-cloudwatch-alarms Description: Create metric alarms for monitoring AWS resources with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible cloudwatch_metric_alarm Module — Manage AWS CloudWatch Alarms ## Introduction The `amazon.aws.cloudwatch_metric_alarm` module create metric alarms for monitoring AWS resources with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.cloudwatch_metric_alarm` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check ... --- ## Ansible CMDB — Generate Host Inventory Reports URL: https://www.ansiblebyexample.com/articles/ansible-cmdb-generate-host-inventory-reports Description: Use ansible-cmdb to generate HTML inventory reports from Ansible facts. Visualize your infrastructure with searchable host databases and CSV exports. # Ansible CMDB — Generate Host Inventory Reports ## Introduction `ansible-cmdb` transforms Ansible fact-gathering output into browsable HTML reports, CSV files, and SQL databases. Instead of running ad-hoc commands to check what's running where, generate a complete inventory report: OS versions, IP addresses, memory, disk, installed packages — all in a searchable web page. It's infrastructure documentation that builds itself. ## Installation [code example] ## Quick Start [code example] That's it — two commands to a complete infrastructure report. ## Gather Facts [code example] Each host produces a JSON file in the output directory: [code example] ## Output Formats ### HTML (Default) [code example] ### CSV [code example] ### Markdown [code example] ### SQL [code example] ### JSON [code example] ## Custom Columns [code example] ## Enrich with Inventory Data [code example] ## Automate with Playbook [code example] ## Schedule Regular Reports [code example] ## Custom Templates [code example] ## What the Report Shows | Section | Data | |---------|------| | Hostname | FQDN, short name | | OS | Distribution, version, kernel | | Hardware | CPUs, memory, architecture | | Network | IP addresses, MAC, interfaces | | Storage | Disk sizes, mount points | | Groups | Ansible inventory groups | | Virtualization | Type (kvm, docker, physical) | | Python | Version installed | | Timestamp | When facts were gathered | ## Troubleshooting | Issue | Solution | |--... --- ## Ansible Code Freeze Schedule June 2026 — Release Process Guide URL: https://www.ansiblebyexample.com/articles/ansible-code-freeze-schedule-june-2026-release-process-guide Description: Ansible community code freeze starts June 2, 2026. Learn the release process, freeze schedule, what's blocked during freeze, and how to prepare your. # Ansible Code Freeze Schedule June 2026 — Release Process Guide ## Introduction The Ansible community announced an official code freeze starting June 2, 2026. During code freeze, only critical bugfixes and security patches are accepted — no new features, no breaking changes. This guide explains the schedule, what it means for collection maintainers and users, and how to prepare. ## Code Freeze Timeline | Date | Event | |------|-------| | **Now – Jun 1** | Feature development open — merge new features, deprecations | | **Jun 2, 2026** | 🧊 **Code freeze begins** — feature PRs blocked | | Jun 2 – release | Bugfixes and security patches only | | TBD | Release candidate (RC) | | TBD | Final release | ## What's Allowed During Freeze | Action | Allowed? | |--------|----------| | Critical bugfixes | ✅ | | Security patches | ✅ | | Documentation updates | ✅ | | Test improvements | ✅ | | New features | ❌ Blocked | | Breaking changes | ❌ Blocked | | New deprecation warnings | ❌ Blocked | | New module/plugin additions | ❌ Blocked | ## For Collection Maintainers ### Before Code Freeze (Do Now) [code example] ### During Code Freeze [code example] ### Prepare for Release [code example] ## For Users ### What to Do Now 1. **Test current playbooks** against latest collection versions 2. **Pin collection versions** in `requirements.yml` before freeze 3. **Report bugs early** — bugs found after freeze get prioritized 4. **Review deprecation warnings** — deprecated features may b... --- ## Ansible code in RHSB-2021-009 Log4Shell — Remote Code Execution — log4j (CVE-2021-44228) URL: https://www.ansiblebyexample.com/articles/ansible-code-in-rhsb-2021-009-log4shell-remote-code-execution-log4j-cve-2021-44228 Description: Learn how my Ansible Playbook was featured in Red Hat Security Bulletin RHSB-2021-009 to address the Log4Shell vulnerability (CVE-2021-44228). Discover. My Ansible Playbook code was officially included in the Red Hat Security Bulletin RHSB-2021-009 Log4Shell - Remote Code Execution - log4j (CVE-2021-44228). ## RHSB-2021-009 - Red Hat Security Bulletin RHSB-2021-009 - Ansible Playbook - Ansible variable file ## Ansible Playbook Read about the line-by-line video of the Vulnerability Scanner/Detector Log4Shell Remote Code Execution Log4j (CVE-2021–44228) — Ansible log4j-cve-2021–44228. code with ❤️ in GitHub ## Ansible Galaxy Role Read about the line-by-line video of the Download and Use Ansible Galaxy Role - ansible-galaxy and requirements.yml. Ansible Galaxy lucab85/ansible_role_log4shell role. ## Conclusion My Ansible Playbook code was officially included in the Red Hat Security Bulletin RHSB-2021-009 Log4Shell. --- ## Ansible Coding Assistant Example: Configure Google Gemini as the Backend URL: https://www.ansiblebyexample.com/articles/ansible-coding-assistant-example-configure-google-gemini-as-the-backend Description: Configure the Ansible VS Code Coding Assistant to use Google Gemini/Vertex as its BYOM backend on AAP 2.6+, with a working settings example. The Ansible Coding Assistant (the Ansible VS Code extension's AI completion feature) supports Bring Your Own Model (BYOM), and Google Gemini/Vertex is a supported backend as of AAP 2.6+. Below is a minimal, working configuration for pointing the Coding Assistant at a Gemini endpoint. ## Example: VS Code `settings.json` [code example] ## Example: Ansible playbook to provision the API credential Teams typically manage the Gemini API key as a secret consumed by the AAP controller/gateway rather than hardcoding it in VS Code. A simple playbook to push that credential into AAP via the `ansible.controller` collection looks like this: [code example] ## What this does The `settings.json` block tells the Ansible VS Code extension to skip the default Red Hat AI-hosted backend and route Coding Assistant inline suggestions (task name completions, module argument scaffolding, playbook boilerplate) to a Gemini model instead. The `byom.type` field selects the Google Gemini/Vertex provider; `projectId` and `region` are required because Gemini access on Vertex AI is scoped to a GCP project and region, not just an API key. The playbook stores the actual Gemini API key as an AAP credential rather than in plaintext in the editor config. The Coding Assistant then references that credential by name (`credentialsSecretName`) when the extension authenticates through the AAP gateway, keeping the key out of version-controlled workspace settings. ## Notes / Gotchas - Per the BYOM provider mat... --- ## Ansible Coding Assistant Example: Configure IBM watsonx as the Backend URL: https://www.ansiblebyexample.com/articles/ansible-coding-assistant-example-configure-ibm-watsonx-as-the-backend Description: Configure IBM watsonx as the model backend for the Ansible VS Code Coding Assistant on AAP 2.5+, the first external BYOM provider it supports. The Ansible VS Code extension's Coding Assistant supports Bring Your Own Model (BYOM), and IBM watsonx was the first external provider it supported, available since AAP 2.5. This is separate from the Intelligent Assistant chatbot in the AAP UI, which does not support watsonx. Below is a reference `settings.json` snippet for wiring the extension to a watsonx deployment. [code example] The corresponding controller-side model configuration, set by an AAP admin under **Automation Decisions > AI Model Configurations**: [code example] ## What this does The `settings.json` block points the VS Code extension at your AAP controller and tells it to route inference requests for the Coding Assistant feature to watsonx, using the project and deployment IDs from your IBM Cloud or watsonx.ai instance. The playbook automates the admin-side setup: it stores the watsonx API key as a credential in AAP, then creates a model configuration record that maps the `coding_assistant` feature to that credential and a chosen model (here, `granite-20b-code-instruct`). Once both pieces are in place, inline task suggestions, playbook completions, and explanation requests in VS Code are served by watsonx instead of the default Red Hat AI model. ## Notes / Gotchas - watsonx support is scoped to the **Coding Assistant** only. If you try to point the **Intelligent Assistant** chatbot at watsonx, it will not work — that surface only accepts Red Hat AI, OpenAI, and Azure OpenAI today, with Google Gemini/Ve... --- ## Ansible Collection Role Testing with Molecule URL: https://www.ansiblebyexample.com/articles/ansible-collection-role-testing-with-molecule Description: Complete guide to testing Ansible roles with Molecule. Docker and Podman drivers, converge/verify/idempotence, Testinfra verification, CI/CD integration,. ## Introduction Molecule is the standard testing framework for Ansible roles and collections. It creates ephemeral instances (Docker containers, Podman, VMs), runs your role against them, verifies the result, and destroys the instances — all in one command. This ensures your roles work correctly before they reach production. This guide covers everything from basic setup to multi-platform testing and CI/CD integration. ## Install Molecule [code example] ## Quick Start ### Initialize a New Role with Molecule [code example] ### Directory Structure [code example] ## Configuration: molecule.yml ### Docker Driver (Default) [code example] ### Podman Driver [code example] ## Test Lifecycle Molecule runs tests in this order: [code example] ### Key Commands [code example] ## The Converge Playbook [code example] ### With Pre/Post Tasks [code example] ## Verification ### Ansible Verifier (Default) [code example] ### Testinfra Verifier (Python Tests) [code example] [code example] ## Prepare Playbook (Pre-test Setup) [code example] ## Multiple Scenarios [code example] [code example] ## Testing Collections ### Collection Structure [code example] ### Collection molecule.yml [code example] ### Collection converge.yml [code example] [code example] ## CI/CD Integration ### GitHub Actions [code example] ### GitLab CI [code example] ## Idempotence Testing Molecule's `idempotence` step runs the converge playbook twice and fails if any task reports `c... --- ## Ansible Collection Version Conflict — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-collection-version-conflict-fix-and-solutions Description: Resolve collection version conflicts and dependency resolution failures. Hands-on, tested examples and best practices for Ansible Collection Version Conflict. # Ansible Collection Version Conflict — Fix and Solutions ## Introduction Resolve collection version conflicts and dependency resolution failures. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve collection version conflicts and dependency resolution failures. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Collections — Create Package and Distribute URL: https://www.ansiblebyexample.com/articles/ansible-collections-create-package-and-distribute Description: Ansible Collections guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Collections — Create Package and Distribute ## Introduction Create Package and Distribute. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Collections requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible Collections Path — Install Location and Configuration URL: https://www.ansiblebyexample.com/articles/ansible-collections-path-install-location-and-configuration Description: Configure Ansible collections paths to control where collections are installed and found. Multiple paths, per-project isolation, and troubleshooting import. # Ansible Collections Path — Install Location and Configuration ## Introduction The `collections_paths` setting in ansible.cfg controls where Ansible looks for and installs collections. Misconfiguring this path is the #1 reason for "collection not found" errors. This guide covers default locations, per-project isolation, and common path issues. ## Default Collection Locations Ansible searches for collections in this order: [code example] [code example] ## Configure in ansible.cfg [code example] [code example] ## Per-Project Collection Isolation [code example] [code example] [code example] ## requirements.yml [code example] [code example] ## Collection Directory Structure [code example] ## Find Where a Collection Is Installed [code example] ## Common Errors and Fixes | Error | Cause | Fix | |-------|-------|-----| | `ERROR! couldn't resolve module/action` | Collection not in search path | Check `collections_paths` includes install location | | `ModuleNotFoundError` | Collection installed in wrong path | Install with `-p` matching your config | | `ERROR! the role was not found in` | Role in collection, path mismatch | Ensure `collections_paths` is correct | | Multiple versions conflict | Different paths have different versions | Use project-local path only | | `ansible-galaxy: error: unrecognized arguments` | Old ansible version | Upgrade to ansible-core 2.15+ | ## CI/CD Pattern [code example] ## Python Virtual Environment Pattern [code example] ## Ex... --- ## Ansible Collections Requirements — Install and Manage Dependencies URL: https://www.ansiblebyexample.com/articles/ansible-collections-requirements-install-and-manage-dependencies Description: Manage Ansible collection dependencies with requirements.yml. Install, pin versions, use private registries, and automate dependency resolution for. # Ansible Collections Requirements — Install and Manage Dependencies ## Introduction Modern Ansible uses collections for modules, plugins, and roles. A `requirements.yml` file pins the exact collections your project needs — ensuring consistent behavior across teams, CI/CD pipelines, and production environments. Without it, `ansible-galaxy` installs whatever version is latest, leading to breaking changes and unreproducible builds. ## Basic requirements.yml [code example] ## Install Collections [code example] ## Version Pinning Strategies [code example] ### When to Use Which | Strategy | When | Risk | |----------|------|------| | Exact `"9.5.0"` | Production, CI/CD | Misses security updates | | Range `">=9.0,=9.0"` | Development | May break on major updates | | No version | Quick testing only | Unpredictable behavior | ## Mixed Roles and Collections [code example] [code example] ## Private Automation Hub / Galaxy Server [code example] ### Configure servers in ansible.cfg [code example] ## Install from Git [code example] ## Install from Tarball [code example] ## Project Setup [code example] [code example] ## CI/CD Integration [code example] [code example] ## List and Verify [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "Collection not found" | Check `collections_path` in ansible.cfg | | Version conflict | Pin exact versions; check dependency chains | | "ERROR! Unexpected Exception" | Upgrade ansible-core; collection ... --- ## Ansible COLLECTIONS_PATH — Configure URL: https://www.ansiblebyexample.com/articles/ansible-collections-path-configure-and-manage-collection-locations Description: Learn how to configure Ansible collections paths — set ANSIBLE_COLLECTIONS_PATHS environment variable or collections_paths in ansible.cfg. Fix 'collection. ## Default Collections Paths Ansible looks for collections in these locations (in order): 1. `./collections/ansible_collections/` (project-local) 2. `~/.ansible/collections/ansible_collections/` (user-local) 3. `/usr/share/ansible/collections/ansible_collections/` (system-wide) ## Configure in ansible.cfg [code example] Multiple paths are separated by colons (`:`) on Linux/macOS or semicolons (`;`) on Windows. ## Configure with Environment Variable [code example] ## Install Collections to a Specific Path [code example] ### requirements.yml [code example] ## Show Installed Collections [code example] Output: [code example] ## Verify Collection Installation [code example] ## Project Structure with Local Collections [code example] [code example] ## Fix "Collection Not Found" Errors ### Error: "couldn't resolve module/action" [code example] **Fix:** [code example] ### Error: "collection not found in configured paths" Your `collections_paths` doesn't include where the collection is installed: [code example] ## ANSIBLE_COLLECTIONS_PATH vs ANSIBLE_COLLECTIONS_PATHS Both work — `ANSIBLE_COLLECTIONS_PATHS` (plural) is the standard. The singular form is also accepted as an alias for backward compatibility. [code example] In `ansible.cfg`, use `collections_paths` (plural): [code example] --- *Browse 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible Command vs Shell Modules: Key Differences Explained URL: https://www.ansiblebyexample.com/articles/ansible-modules-command-vs-shell Description: Explore the differences between Ansible's command and shell modules. Learn when to use each, with practical examples and code Playbooknstrations. Ready to advance your Ansible expertise? Explore Linux Administrator Job openings today! ## What is the difference between `command` vs `shell` Ansible modules? These two Ansible modules are confused one for another but they're fundamentally different. Both modules allow you to execute command on a target host but in a slightly different way. ## command vs shell command - execute commands against the target Unix-based hosts - it bypasses the shell - always set changed to True shell - execute shell commands against the target Unix-based hosts - redirections and shell's inbuilt functionality - always set changed to True The `command` and `shell` Ansible modules execute commands on the target node. Generally speaking, is always better to use a specialized Ansible module to execute a task. However, sometimes the only way is to execute a Linux `command` via command or `shell` module. Let me reinforce again, you should avoid as much as possible the usage of command/shell instead of a better module. Both modules execute commands on target nodes but in a sensible different way. The `command` modules execute commands on the target machine without using the target shell, it simply executes the command. The target shell is for example the popular `bash`, `zsh`, or `sh`. As a side effect user environment, variable expansions, output redirections, stringing two commands together, and other shell features are not available. On the other side, every command executed using `shell` mo... --- ## Ansible Community Day Berlin 2023: Highlights and Key Takeaways URL: https://www.ansiblebyexample.com/articles/ansible-community-day-berlin-2023-recap Description: Discover the highlights from Ansible Community Day Berlin 2023. Learn about key presentations, interviews, and community experiences from this vibrant. ## Introduction Yesterday (20th September 2023), I attended and presented the highly anticipated Ansible Community Day in Berlin, and it did not disappoint. The event was a delightful blend of tech talks, networking, and community bonding, making it a memorable experience for attendees. In this article, we’ll take a closer look at the highlights and experiences of this event. ## The Perfect Venue The Ansible Community Day took place at the C-base, one of the oldest hackerspaces in Berlin, nestled along the picturesque Spree River. The event’s location provided a unique and relaxed atmosphere, complete with a garden where attendees could unwind and connect with fellow enthusiasts. The C-base team’s warm hospitality added to the overall positive experience, making everyone feel welcome. ## Impressions As any tech-savvy individual knows, documenting experiences through photos is a must. The event offered plenty of photo-worthy moments, and attendees, including myself, captured some of the event’s highlights to share with the broader community. ## Insightful Talks A community day is only as good as its content, and this year’s Ansible Community Day delivered on that front. The agenda, available on the newly established Ansible forums, was packed with insightful talks delivered by industry experts. Here’s a glimpse of some of the standout presentations: - ***Welcome to Ansible Community Day*** by Carol Chen - ***Ansible Community Strategy 2023: The Half-Year Update*** by Greg ... --- ## Ansible Community Forum: Your Hub for Automation Discussions and Collaboration URL: https://www.ansiblebyexample.com/articles/ansible-community-forum-a-hub-for-ansible-enthusiasts Description: Explore the newly launched Ansible Community Forum, designed for automation professionals to discuss, collaborate, and stay updated. Discover its features. ## Introduction Are you an Ansible enthusiast, developer, or someone looking to dive into the world of automation? If so, you’re in for a treat! The Ansible Community Forum has arrived, poised to become your go-to destination for all things Ansible. In this article, we’ll explore the exciting launch of this forum, its features, and why it’s already making waves in the Ansible community. ## Link - https://forum.ansible.com - https://discourse.org ## A Community Dream Come True The Ansible community has been buzzing with anticipation for over six months, and now, the moment has arrived. The Ansible Community Forum is live and here to unite the ecosystem. This forum aims to gather where Ansible users, experts, and beginners can discuss, seek assistance, learn about events, and actively participate in the Ansible community. It is based on the Discourse software used by Python, Fedora, Mozilla, Ubuntu, Nextcloud, Pulp, LetsEncypt, Sailfish , etc. One of the standout features of the Ansible Community Forum is its user-friendly design, which allows for efficient navigation and interaction. Here are some key features that make this forum a powerful tool for the Ansible community: ### Tagging and Filtering With robust tagging and filtering options, users can easily locate and follow discussions relevant to their interests. Whether you are interested in networking, automation playbooks, or Ansible modules, you can find and participate in discussions that matter to you. ### Notific... --- ## Ansible Community General Collection 7.0.0 Released: Key Changes and Enhancements URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-community-general-collection-7-0-0 Description: Check out the key updates in Ansible Community General Collection 7.0.0, including breaking changes, module improvements, new features, bug fixes. Hello Ansible Enthusiasts! We’re pleased to announce the release of Ansible Community General Collection 7.0.0, which became available on May 9, 2023. This update introduces a variety of new features, improvements, and important changes across numerous modules. Here’s a summary of what’s new in this release: **1. Breaking Changes / Porting Guide:** - **Dependency Updates:** If you manually installed or upgraded `community.general`, make sure to also install `community.sap_libs` if using `sapcar_extract`, `sap_task_list_execute`, or `hana_query` modules to ensure proper functionality. - **Module Output Changes:** The `ModuleHelper` utility now prefixes certain output variables with an underscore when they clash with internal variables, addressing a previous bug (#5765). - **gconftool2:** Adjustments have been made for handling non-existent keys, which now return `null` instead of an empty string (#6028). - **gitlab_runner:** The default for `access_level_on_creation` has been updated from `false` to `true` (#6428). - **nmcli:** The default for the `hairpin` option has changed from `true` to `false` (#6428). - **proxmox:** The default for the `unprivileged` option has been updated from `false` to `true` (#6428). **2. Module Improvements:** - **apache2_module:** Added `warn_mpm_absent` to control warnings in edge cases (#5793). - **apt_rpm:** New parameters like `clean`, `dist_upgrade`, and `update_kernel` for system upgrades (#5867). - **bitwarden ... --- ## Ansible community.crypto — X509 Certificates and Keys URL: https://www.ansiblebyexample.com/articles/ansible-community-crypto-x509-certificates-and-keys Description: Ansible community.crypto guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible community.crypto — X509 Certificates and Keys ## Introduction X509 Certificates and Keys. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible community.crypto requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible community.vmware Collection Setup URL: https://www.ansiblebyexample.com/articles/configure-ansible-for-vmware-ansible-collection-community-vmware Description: Configure Ansible for VMware vSphere with community.vmware collection. Install pyVmomi, set credentials, and manage VMs with complete playbook examples. ## How to configure Ansible for VMware? Ansible provides various modules to manage VMware infrastructure, which includes data center, cluster, host system, and virtual machine. I'll show you step by step how to prepare your Ansible controller to interact with the VMware infrastructure. This initial configuration sometimes is a roadblock for some VMware users to start using Ansible. ## Configure Ansible for VMware - vSphere 6.0, 5.5, 5.1 and 5.0 - Python pyVmomi supports 2.7.x and 3.4+ - Ansible collection `community.vmware` The supported nodes include all the modern releases of VMware vSphere. The full list includes vSphere 6.0, 5.5, 5.1, and 5.0. Ansible VMware modules are written on top of pyVmomi. pyVmomi is the Python SDK for the VMware vSphere API that allows users to manage ESX, ESXi, and vCenter infrastructure. This library interacts with the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter in order to execute some Ansible code. The `pyVmomi` Python library supports Python 2.7.x and 3.4+. The Ansible collection `community.vmware` of modules and plugins manages various operations related to virtual machines in the given ESXi or vCenter server. As the name suggests, this resource is provided with only Community Support so it's not maintained directly by the Ansible Engineer Team. ## Links - Introduction to Ansible for VMware - community.vmware.vmware_guest_info ## Playbook How to configure Ansible for VMware: 1. Install pyVmomi First of all, ... --- ## Ansible Compare Lists — Data Check URL: https://www.ansiblebyexample.com/articles/compare-two-lists-in-ansible Description: Learn how to compare two lists in Ansible playbooks, verify their lengths, and ensure matching elements using robust filters and syntax. ## Introduction When working with Ansible playbooks, comparing two lists is a common task, especially for validating data consistency in automation workflows. However, users often encounter issues with filters like `length`, particularly in older Ansible versions or due to syntax ambiguities. This guide demonstrates how to effectively compare lists, ensuring they match in both size and content. --- ## The Scenario: Comparing Two Lists Consider the following two lists: [code example] The goal is to: 1. Verify that both lists are of equal length. 2. Check that all elements in `list_one` are present in `list_two`, and vice versa. 3. Fail gracefully if there are mismatches. --- ## Playbook: Comparing Two Lists Here’s the complete playbook to achieve this: ### Example Playbook [code example] --- ## Key Features of the Playbook ### Length Comparison - Ensures both lists are of the same size using the `length` filter. ### Element Comparison - Extracts `name` attributes with `map(attribute='name')`. - Uses the `difference` filter to identify mismatched elements between the lists. ### Fail Gracefully - The `fail` module provides clear error feedback when the lists differ in length or content. --- ## Why It Works 1. **Explicit Template Syntax**: - Wrapping conditions in `{{ ... }}` ensures clear, unambiguous Jinja2 evaluation. 2. **Robust Filters**: - Filters like `length`, `map`, and `difference` are reliable tools for list manipulation. 3. **Error Handling*... --- ## Ansible Compliance — CIS STIG Hardening URL: https://www.ansiblebyexample.com/articles/ansible-compliance-as-code-cis-benchmarks-stig-hardening Description: Implement compliance as code with Ansible. Automate CIS benchmark enforcement, DISA STIG hardening, PCI-DSS controls, and continuous compliance auditing. ## Introduction Enterprise compliance isn't optional — it's audited, regulated, and fined. CIS Benchmarks, DISA STIGs, PCI-DSS, SOC 2, and HIPAA all require specific system configurations that need to be enforced consistently across hundreds or thousands of servers. Manual compliance checks don't scale; spreadsheet tracking doesn't prevent drift. Ansible turns compliance requirements into executable code: playbooks that both enforce and verify security baselines. ## Compliance Frameworks | Framework | Full Name | Focus | Common Industries | |-----------|-----------|-------|-------------------| | CIS | Center for Internet Security Benchmarks | OS/application hardening | All | | STIG | Security Technical Implementation Guide | DoD security requirements | Government, defense | | PCI-DSS | Payment Card Industry Data Security Standard | Cardholder data protection | Finance, retail | | SOC 2 | Service Organization Control 2 | Data security controls | SaaS, tech | | HIPAA | Health Insurance Portability Act | Protected health information | Healthcare | | NIST 800-53 | Security and Privacy Controls | Federal information systems | Government | ## Using Community Hardening Roles ### CIS Benchmark Role [code example] [code example] ### DISA STIG Role [code example] [code example] ## Custom Compliance Playbooks ### SSH Hardening (CIS 5.2) [code example] ### Password Policy (CIS 5.4) [code example] ### Filesystem Hardening (CIS 1.1) [code example] ## Compliance Audit Play... --- ## Ansible Compliance Drift — Config URL: https://www.ansiblebyexample.com/articles/managing-compliance-drift-with-ansible Description: Detect and remediate configuration drift with Ansible. CIS benchmark checks, automated remediation playbooks, and scheduled compliance scans. ## Managing Compliance Drift with Ansible In the fast-paced world of IT operations, maintaining configuration compliance is essential for securing systems and ensuring operational efficiency. Yet, over time, configurations often deviate from intended baselines—a phenomenon known as **compliance drift**. This article explores how Ansible, a leading automation tool, addresses compliance drift effectively and efficiently. --- ### What is Compliance Drift? Compliance drift occurs when system configurations diverge from predefined baselines due to: - Manual changes or errors - Software patches or updates - Unmonitored ad-hoc modifications - Neglect in applying updated policies These deviations can lead to vulnerabilities, inefficiencies, and non-compliance with organizational or regulatory standards. --- ### Ansible: Your Partner in Preventing Compliance Drift Ansible's architecture and capabilities make it ideal for managing compliance drift. Its strengths include: 1. **Declarative Playbooks**: Define desired states in human-readable YAML files. 2. **Idempotency**: Ensure repeated tasks do not produce inconsistent results. 3. **Integration with CMDBs**: Fetch and enforce compliance policies across infrastructure. 4. **Automated Remediation**: Fix deviations with minimal manual intervention. --- ### Practical Use Cases with Ansible #### **1. Configuration Enforcement** Ansible playbooks maintain system consistency. Example: [code example] #### **2. Compliance Auditi... --- ## Ansible composer Module — Manage PHP Dependencies with Composer URL: https://www.ansiblebyexample.com/articles/ansible-composer-module-manage-php-dependencies-with-composer Description: Install and update PHP project dependencies using Composer with Ansible. Hands-on, tested examples and best practices for Ansible composer Module. # Ansible composer Module — Manage PHP Dependencies with Composer ## Introduction The `community.general.composer` module install and update PHP project dependencies using Composer with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.composer` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode**... --- ## Ansible Conditional Role Execution URL: https://www.ansiblebyexample.com/articles/conditional-ansible-role-execution-in-playbooks Description: Discover how to use conditional logic in Ansible playbooks to execute roles like Datadog only when specific variables are set, optimizing deployments. ## Conditional Role Execution in Ansible: A Guide to Running the Datadog Role Based on Variables In complex infrastructure environments, there are often scenarios where you need to run specific tasks or roles conditionally. Ansible, being a powerful automation tool, offers various mechanisms to handle such conditional executions. One common use case is the need to execute a specific role only if a particular variable is set. In this article, we'll discuss how to execute the Datadog role conditionally based on a variable passed at runtime. ## The Problem Statement You want to run the Datadog Ansible role to install and configure the Datadog agent on your servers, but only if a specific variable, say `datadog`, is set to `1`. This ensures that the role is executed only when required, avoiding unnecessary installations and configurations during other deployments. The initial approach might look like this: [code example] However, this configuration leads to an error because the `when` statement is not supported at the play level in Ansible. It can only be used with tasks. So, how do we achieve this conditional execution? ## The Solution: Using `include_role` with Conditions To address this issue, we need to move the conditional logic into the tasks section of the playbook. We can use the `include_role` directive, which allows us to include a role dynamically based on certain conditions. Here’s how we can rewrite the playbook: [code example] ## How It Works 1. **`includ... --- ## Ansible Configuration Drift Detection and Remediation URL: https://www.ansiblebyexample.com/articles/ansible-configuration-drift-detection-remediation Description: How to detect and fix configuration drift with Ansible using check mode, assert, and idempotent playbooks. Prevent server sprawl and compliance issues. # Ansible Configuration Drift Detection and Remediation Configuration drift occurs when servers gradually deviate from their intended state — manual changes, ad-hoc fixes, and untracked modifications accumulate until systems become unpredictable. Ansible is one of the best tools to detect and fix this. ## What is Configuration Drift? [code example] Common causes: - Manual SSH changes bypassing automation - Emergency fixes applied inconsistently - Partial playbook runs that failed midway - Different team members making ad-hoc changes ## Detect Drift with Check Mode Ansible's `--check` (dry run) mode shows what **would** change without making modifications: [code example] If the output shows changes, those servers have drifted from the desired state. [code example] Run with `--check --diff` to see drift without fixing it. ## Automated Drift Detection Playbook [code example] ## Remediation Strategies ### 1. Idempotent Playbooks (Recommended) Write playbooks that describe the **desired state**, not steps. Run them regularly: [code example] ### 2. Scheduled Runs Run playbooks on a schedule via cron or Ansible Automation Platform: [code example] ### 3. Compliance Reporting with Tags [code example] Run compliance checks only: [code example] ## Tools for Drift Detection | Tool | Description | |------|-------------| | `ansible-playbook --check --diff` | Built-in dry run with diff output | | ARA Records Ansible | Web dashboard for playbook history | | Ansible Au... --- ## Ansible Configure Centralized Logging — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-centralized-logging-complete-guide Description: Set up ELK Stack or Loki centralized logging with Ansible. Hands-on, tested examples and best practices for Ansible Configure Centralized Logging. # Ansible Configure Centralized Logging — Complete Guide ## Introduction Set up ELK Stack or Loki centralized logging with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up ELK Stack or Loki centralized logging with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure DNS Servers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-dns-servers-complete-guide Description: Set up BIND, Unbound, and CoreDNS servers with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Configure DNS Servers. # Ansible Configure DNS Servers — Complete Guide ## Introduction Set up BIND, Unbound, and CoreDNS servers with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up BIND, Unbound, and CoreDNS servers with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure Firewall Rules — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-firewall-rules-complete-guide Description: Manage iptables, firewalld, and ufw rules with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Configure Firewall Rules. # Ansible Configure Firewall Rules — Complete Guide ## Introduction Manage iptables, firewalld, and ufw rules with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Manage iptables, firewalld, and ufw rules with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure LDAP Authentication — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-ldap-authentication-complete-guide Description: Set up LDAP and Active Directory authentication with Ansible. Hands-on, tested examples and best practices for Ansible Configure LDAP Authentication. # Ansible Configure LDAP Authentication — Complete Guide ## Introduction Set up LDAP and Active Directory authentication with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up LDAP and Active Directory authentication with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure Log Rotation — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-log-rotation-complete-guide Description: Set up logrotate with size limits and compression using Ansible. Tested on real machines with clear, copy-paste examples. # Ansible Configure Log Rotation — Complete Guide ## Introduction Set up logrotate with size limits and compression using Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up logrotate with size limits and compression using Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure Nginx Reverse Proxy — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-nginx-reverse-proxy-complete-guide Description: Set up Nginx as reverse proxy with SSL and load balancing. Hands-on, tested examples and best practices for Ansible Configure Nginx Reverse Proxy. # Ansible Configure Nginx Reverse Proxy — Complete Guide ## Introduction Set up Nginx as reverse proxy with SSL and load balancing. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up Nginx as reverse proxy with SSL and load balancing. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure NTP Time Sync — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-ntp-time-sync-complete-guide Description: Set up NTP or chrony time synchronization with Ansible. Hands-on, tested examples and best practices for Ansible Configure NTP Time Sync. # Ansible Configure NTP Time Sync — Complete Guide ## Introduction Set up NTP or chrony time synchronization with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set up NTP or chrony time synchronization with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure Prometheus Monitoring — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-prometheus-monitoring-complete-guide Description: Deploy Prometheus and node exporters with Ansible automation. Hands-on, tested examples and best practices for Ansible Configure Prometheus Monitoring. # Ansible Configure Prometheus Monitoring — Complete Guide ## Introduction Deploy Prometheus and node exporters with Ansible automation. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy Prometheus and node exporters with Ansible automation. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Configure SSH Keys — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-configure-ssh-keys-complete-guide Description: Deploy SSH authorized keys and generate key pairs with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Configure SSH Keys. # Ansible Configure SSH Keys — Complete Guide ## Introduction Deploy SSH authorized keys and generate key pairs with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy SSH authorized keys and generate key pairs with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Connection Plugins — SSH WinRM and Beyond URL: https://www.ansiblebyexample.com/articles/ansible-connection-plugins-ssh-winrm-and-beyond Description: Ansible Connection Plugins guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Connection Plugins — SSH WinRM and Beyond ## Introduction SSH WinRM and Beyond. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Connection Plugins requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible Connection Plugins — SSH, WinRM, Local & Network URL: https://www.ansiblebyexample.com/articles/ansible-connection-plugins-ssh-winrm-network Description: Understand Ansible connection plugins: SSH, WinRM, local, network_cli, httpapi, and netconf. Configure per-host connection types, troubleshoot. # Ansible Connection Plugins — SSH, WinRM, Local & Network ## Introduction Connection plugins are how Ansible communicates with managed hosts. While SSH is the default, Ansible supports multiple connection types for different platforms — Windows (WinRM/PSRP), network devices (network_cli, httpapi, netconf), containers (docker, podman), and local execution. Understanding connection plugins lets you automate heterogeneous environments with a single Ansible control node. ## Available Connection Plugins | Plugin | Use Case | Transport | |--------|----------|-----------| | \`ansible.builtin.ssh\` | Linux/Unix hosts (default) | OpenSSH | | \`ansible.builtin.paramiko_ssh\` | SSH without OpenSSH | Python paramiko | | \`ansible.builtin.local\` | Run on control node | Direct | | \`ansible.builtin.winrm\` | Windows hosts | WinRM/HTTPS | | \`ansible.builtin.psrp\` | Windows via PowerShell | PSRP/WSMan | | \`ansible.netcommon.network_cli\` | Network device CLI | SSH | | \`ansible.netcommon.httpapi\` | Network device REST API | HTTPS | | \`ansible.netcommon.netconf\` | Network device NETCONF | SSH/NETCONF | | \`community.docker.docker\` | Docker containers | Docker API | | \`containers.podman.podman\` | Podman containers | Podman API | | \`community.libvirt.libvirt_lxc\` | LXC containers | libvirt | | \`kubectl\` | Kubernetes pods | kubectl | ## SSH Connection (Default) ### Basic Configuration \`\`\`ini # ansible.cfg [defaults] remote_user = ansible private_key_file = ~/.ssh/ansibl... --- ## Ansible Consul — Service Discovery and Service Mesh URL: https://www.ansiblebyexample.com/articles/ansible-consul-service-discovery-mesh Description: Deploy HashiCorp Consul with Ansible. Server cluster and client agents, service registration, DNS and HTTP discovery, health checks, KV store, Consul. ## Introduction HashiCorp Consul provides service discovery, health checking, KV store, and service mesh (Consul Connect) for distributed infrastructure. Ansible automates the entire stack: server cluster bootstrap, client agent deployment on all hosts, service registration, DNS configuration, ACLs, and Connect sidecar proxies. ## Deploy Consul Server Cluster [code example] ### Server Config Template [code example] ## Deploy Client Agents [code example] [code example] ## Register Services [code example] ## KV Store [code example] ## DNS Integration [code example] ## ACL Bootstrap [code example] ## Health Check [code example] ## Troubleshooting ### Agent Not Joining [code example] ### Generate Encrypt Key [code example] ## Related Articles - Ansible HashiCorp Vault - Ansible Nomad - Ansible Nginx Load Balancer - Ansible HAProxy ## Conclusion Consul provides service discovery, health checking, KV configuration, and service mesh from a single tool. Ansible deploys the server cluster and client agents, registers services with health checks, configures DNS integration so applications resolve `service.consul` names, and bootstraps ACLs. Combined with Nomad and Vault, it forms the complete HashiCorp infrastructure stack — all managed as code. --- ## Ansible Container Registry — Harbor Nexus ECR Setup URL: https://www.ansiblebyexample.com/articles/ansible-container-registry-harbor-nexus-ecr-setup Description: Ansible Container Registry guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Container Registry — Harbor Nexus ECR Setup ## Introduction Harbor Nexus ECR Setup. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Container Registry requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible Controller — Prometheus Grafana URL: https://www.ansiblebyexample.com/articles/integrate-automation-controller-prometheus-and-grafana-to-it-monitor-realtime Description: Set up real-time Ansible Automation Controller monitoring with Prometheus and Grafana. Scrape metrics, build dashboards, and create alerts for job. ## Introduction Ansible Automation Controller (formerly AWX/Tower) exposes a Prometheus-compatible `/api/v2/metrics` endpoint that provides real-time data about job execution, host status, system performance, and more. By connecting Prometheus to scrape these metrics and Grafana to visualize them, you get a complete real-time monitoring stack for your automation platform. This article covers the full integration setup from metrics endpoint to production dashboards. ## Architecture Overview [code example] ## Prerequisites | Component | Version | Purpose | |---|---|---| | Automation Controller | 4.x+ | Metrics source | | Prometheus | 2.x+ | Metrics collection and storage | | Grafana | 9.x+ | Visualization and alerting | | Network access | HTTPS 443 | Controller → Prometheus | ## Step 1: Enable Metrics on Automation Controller The metrics endpoint is available at `https://controller.example.com/api/v2/metrics`. You need an API token: ### Create an API Token [code example] Or create one in the UI: **Settings → Tokens → Add Token** (read scope only). ### Verify Metrics Endpoint [code example] ### Available Metrics | Metric | Type | Description | |---|---|---| | `awx_system_info` | gauge | Controller version and install info | | `awx_organizations_total` | gauge | Total organizations | | `awx_users_total` | gauge | Total users | | `awx_teams_total` | gauge | Total teams | | `awx_inventories_total` | gauge | Total inventories | | `awx_projects_total` | gauge | Total pr... --- ## Ansible Copy File from Local to Remote — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-copy-file-from-local-to-remote-complete-guide Description: Copy files from local to remote hosts with Ansible copy module. Handle permissions, ownership, backup, recursive copies, and content generation. # Ansible Copy File from Local to Remote — Complete Guide ## Introduction The `ansible.builtin.copy` module transfers files from the Ansible controller (local machine) to remote hosts. It handles permissions, ownership, backups, validation, and content generation — all idempotently. This guide covers every copy pattern you'll need. ## Quick Reference [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | — | Local file/directory path | | `dest` | (required) | Remote destination path | | `content` | — | String content (instead of src) | | `owner` | — | File owner on remote | | `group` | — | File group on remote | | `mode` | — | File permissions (e.g., '0644') | | `backup` | false | Create backup before overwrite | | `force` | true | Overwrite if different | | `validate` | — | Command to validate before placing | | `remote_src` | false | If true, src is on the remote host | | `directory_mode` | — | Permissions for created directories | | `follow` | false | Follow symlinks | ## Copy Patterns ### Single File [code example] ### File with Backup [code example] ### Generate Content Inline [code example] ### Recursive Directory Copy [code example] ### Validate Before Placing [code example] ### Copy from Remote to Remote [code example] ## copy vs template vs synchronize | Module | Use When | |--------|----------| | `copy` | Static files, no Jinja2 needed | | `template` | Files with variables (Jinja2 templ... --- ## Ansible Copy from Remote to Local — Fetch Files from Hosts URL: https://www.ansiblebyexample.com/articles/ansible-copy-from-remote-to-local-fetch-files-from-hosts Description: Download files from remote hosts to local machine with Ansible fetch module. Retrieve logs, configs, backups, and diagnostic data from managed nodes. # Ansible Copy from Remote to Local — Fetch Files from Hosts ## Introduction The `ansible.builtin.fetch` module downloads files from remote hosts to the Ansible controller. It's the reverse of `copy` — pull logs, configs, certificates, and backups from managed nodes to your local machine. Files are organized by hostname automatically. ## Quick Reference [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | Remote file to fetch | | `dest` | (required) | Local destination path | | `flat` | false | Don't create hostname subdirectory | | `fail_on_missing` | true | Fail if source doesn't exist | | `validate_checksum` | true | Verify file integrity | ## Default Behavior (with hostname) [code example] [code example] ## Flat Mode (Single Host) [code example] ### Flat Mode with Multiple Hosts [code example] ## Common Patterns ### Fetch Log Files for Debugging [code example] ### Fetch and Archive [code example] ### Fetch Database Backup [code example] ### Fetch SSL Certificates [code example] ### Conditional Fetch [code example] ## fetch vs Other Methods | Method | Direction | Use Case | |--------|-----------|----------| | `fetch` | Remote → Local | Single files, configs, logs | | `synchronize` (mode=pull) | Remote → Local | Large dirs, rsync-based | | `copy` | Local → Remote | Deploy files | | `slurp` | Remote → Variable | Read file into memory (base64) | ### synchronize for Large Dire... --- ## Ansible copy Module — Copy Files to Remote Hosts URL: https://www.ansiblebyexample.com/articles/ansible-copy-module-files-to-remote-hosts Description: Copy files from the control node to remote hosts with Ansible copy module. Inline content, permissions, backup, validate, and directory copy with examples. ## Introduction The `ansible.builtin.copy` module copies files from the Ansible control node to remote hosts, or creates files with inline content. It handles permissions, ownership, backup, and is idempotent — it won't copy if the destination already matches. ## Basic Syntax [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | — | Local file path (mutually exclusive with `content`) | | `content` | — | Inline content to write (mutually exclusive with `src`) | | `dest` | (required) | Remote destination path | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions (e.g., `"0644"`) | | `backup` | `false` | Create backup of existing file | | `force` | `true` | Overwrite if different; `false` = copy only if missing | | `validate` | — | Command to validate before final placement | | `remote_src` | `false` | Copy from remote to remote (not control → remote) | | `directory_mode` | — | Mode for auto-created directories | | `follow` | `false` | Follow symlinks on the remote | ## Copy a File with Permissions [code example] ## Create File with Inline Content [code example] ## Copy vs Template [code example] | Feature | copy (src) | copy (content) | template | |---------|-----------|----------------|----------| | Jinja2 in file | ❌ | ✅ | ✅ | | External file | ✅ | ❌ | ✅ | | Loops/conditionals | ❌ | Limited | ✅ | | Best for | Static files | Small dynamic content | Complex templates |... --- ## Ansible copy Module — Transfer Files to Remote Hosts URL: https://www.ansiblebyexample.com/articles/ansible-copy-module-transfer-files Description: Use the Ansible copy module to transfer files, create files from content, set permissions, and manage file distribution across your infrastructure. ## Introduction `ansible.builtin.copy` transfers files from the Ansible controller to remote hosts, or creates files from inline content. It handles permissions, ownership, backups, and validation — the go-to module for file distribution. ## Basic File Copy [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | — | Source file on controller | | `dest` | (required) | Destination path on remote | | `content` | — | Inline content (instead of src) | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions (e.g., `"0644"`) | | `backup` | `false` | Create backup before overwrite | | `force` | `true` | Overwrite if different | | `remote_src` | `false` | Copy from remote to remote | | `validate` | — | Validation command before placing | | `directory_mode` | — | Mode for created directories | | `follow` | `false` | Follow symlinks | | `checksum` | — | Verify file integrity | ## Create File from Content [code example] ## Copy Directory [code example] ## Copy Multiple Files [code example] ## With Validation [code example] ## Remote-to-Remote Copy [code example] ## Fetch (Remote to Controller) [code example] ## Practical Patterns ### Deploy Application Files [code example] ### Distribute SSH Keys [code example] ### Copy with Content from Variable [code example] ## copy vs template | Use case | Module | |----------|--------| | Static files (no variables) | `copy` | | File... --- ## Ansible copy Module: Transfer Files to Remote Hosts URL: https://www.ansiblebyexample.com/articles/ansible-copy-module-transfer-files-to-remote-hosts Description: Master the Ansible copy module — transfer files to remote hosts, create files from content, set permissions, and backup originals. Practical examples for. ## The ansible.builtin.copy Module The `copy` module transfers files from the control node to remote hosts, or creates files from inline content. ## Copy a File [code example] ## Create a File from Content [code example] ## Copy a Directory [code example] ## Copy with Backup [code example] ## Copy Multiple Files [code example] ## Remote to Remote Copy [code example] ## Remote to Local (Use fetch) [code example] ## Conditional Copy [code example] ## Validate Before Deploying [code example] ## Parameters | Parameter | Description | Default | |-----------|-------------|---------| | `src` | Local source path | — | | `content` | File content (string) | — | | `dest` | Remote destination (required) | — | | `mode` | Permissions | Preserve | | `owner` | File owner | — | | `group` | File group | — | | `backup` | Backup before overwrite | `false` | | `force` | Overwrite if different | `true` | | `remote_src` | Source is on remote host | `false` | | `validate` | Validation command | — | | `directory_mode` | Dir permissions for recursive | — | ## copy vs template vs synchronize | Module | Use when | |--------|----------| | `copy` | Static files, no variable substitution | | `template` | Files with Jinja2 variables/logic | | `synchronize` | Large directory sync (uses rsync) | | `fetch` | Remote → local file transfer | --- *Browse 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible copy vs template vs lineinfile — File Management Compared URL: https://www.ansiblebyexample.com/articles/ansible-copy-vs-template-vs-lineinfile Description: Compare Ansible copy, template, and lineinfile modules. Learn when to use each for file management with practical examples, performance tips, and common. ## Introduction Ansible offers three primary modules for managing file content: `ansible.builtin.copy` for static files, `ansible.builtin.template` for dynamic Jinja2 files, and `ansible.builtin.lineinfile` for surgical single-line edits. Choosing the wrong one leads to brittle playbooks, performance problems, or configuration drift. This guide compares all three with clear decision criteria. ## Quick Decision Guide [code example] ## Side-by-Side Comparison [code example] ## When to Use copy [code example] ## When to Use template [code example] ## When to Use lineinfile [code example] ## Common Mistakes [code example] ## Performance Comparison [code example] ## Decision Matrix [code example] ## Related Articles - Ansible template Module - Ansible lineinfile Module - Ansible blockinfile Module - Ansible copy Module - Ansible file Module ## Conclusion Use **copy** for static files without variables. Use **template** for any file with dynamic content — it's the safest default. Use **lineinfile** for surgical single-line changes to files you don't fully own. When you find yourself chaining more than 3 lineinfile tasks on the same file, switch to template. The right choice keeps playbooks fast, readable, and idempotent. --- ## Ansible Core 2.14.2 & Community 7.2.0: Latest Updates URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-14-2-and-ansible-7-2-0 Description: Discover the latest updates for Ansible Core 2.14.2 and Community 7.2.0. Learn about new features, installation tips, and how these releases impact your. Welcome to a new episode of the Ansible Pilot from Luca Berton. The big news of the last week of January 2023 is the release of two important versions of Ansible: Ansible Core 2.14.2 and Ansible Community 7.2.0. These updates are primarily bug-fix releases aimed at improving stability and performance. ### Key Differences **Ansible Core vs. Ansible Community** - **Ansible Core**: This package contains the Ansible framework and the `ansible.builtin` collection. It’s the smallest and most basic package, focused solely on core functionalities. - **Ansible Community**: This package includes everything in Ansible Core plus a variety of additional collections, such as those for interacting with cloud providers (e.g., AWS, Google Cloud, Azure) and other community-generated and Red Hat vendor collections. The decision to release two packages allows for more flexibility. You can choose a minimal package for specific workloads or use the broader community package for a more comprehensive solution. This separation also allows for asynchronous releases of Ansible Core and its collections. ### New Releases #### Ansible Core 2.14.2 Released on January 30, 2023, Ansible Core 2.14.2 is a maintenance update for the Ansible codename "C'mon, Everybody." This version primarily focuses on bug fixes. Ansible Core 2.14 was first introduced in November 2022, setting the foundation for future updates. A notable change is the requirement for Python 3.9, which breaks compatibility with Red Hat... --- ## Ansible Core 2.14.3, 2.13.8 & Community 7.3.0: Updates URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-14-3-2-13-8-and-ansible-7-3-0 Description: Explore the latest bug-fix releases of Ansible Core 2.14.3, 2.13.8, and Community 7.3.0. Get installation tips and insights into new features. Welcome to a new episode of the Ansible Pilot from Luca Berton. The big news of the last week of February 2023 is the release of three versions of Ansible: Ansible Core 2.14.3, 2.13.8, and Ansible Community 7.3.0. Basically, these are bug-fix releases. Let me quickly remind you that the Ansible Core contains the Ansible framework and the `ansible.builtin` collection. Nothing else. Whereas the Ansible community includes a lot of other collections. For example, interactive with cloud providers (Amazon, Google, Azure), community-generated collection, and Red Hat vendor partners. ## Links - New releases: ansible-core 2.14.3 and 2.13.8 https://groups.google.com/g/ansible-project/c/yokousquPLU - Ansible 7.3.0 has been Released! https://groups.google.com/g/ansible-project/c/yg4oL-_QD30 - ansible-core 2.14.3 https://pypi.org/project/ansible-core/ - ansible 7.3.0 https://pypi.org/project/ansible/ - ansible-core 2.14 "C'mon Everybody" Release Notes https://github.com/ansible/ansible/blob/v2.14.2/changelogs/CHANGELOG-v2.14.rst - ansible-core 2.13 "Nobody's Fault but Mine" Release Notes https://github.com/ansible/ansible/blob/v2.13.8/changelogs/CHANGELOG-v2.13.rst - Introduction to ansible-test https://www.ansible.com/blog/introduction-to-ansible-test - Ansible project 7.0 https://docs.ansible.com/ansible/devel/roadmap/COLLECTIONS_7.html - Ansible 2.15 roadmap https://docs.ansible.com/ansible/devel/roadmap/ROADMAP_2_15.html ## Ansible Core vs Ansible Community - What's the difference... --- ## Ansible Core 2.14.4 & Community 7.4.0: Latest Updates URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-14-4-and-ansible-7-4-0 Description: Discover the new bug-fix releases for Ansible Core 2.14.4 and Community 7.4.0. Find out about improvements, installation tips, and upcoming features. Welcome to a new episode of the Ansible Pilot from Luca Berton. The big news of the last week of February 2023 is the release of two versions of Ansible: Ansible Core 2.14.4 and Ansible Community 7.4.0. Basically, these are bug-fix releases. Let me quickly remind you that the Ansible Core contains the Ansible framework and the `ansible.builtin` collection. Nothing else. Whereas the Ansible community includes a lot of other collections. For example, interactive with cloud providers (Amazon, Google, Azure), community-generated collection, and Red Hat vendor partners. ## Links - New releases: ansible-core 2.14.4 https://groups.google.com/g/ansible-project/c/Hgx-Mwqamgw - Release announcement : Ansible Community Package 7.4.0 https://groups.google.com/g/ansible-project/c/ILuT3R7XGQ4 - ansible-core 2.14.4 https://pypi.org/project/ansible-core/ - ansible 7.4.0 https://pypi.org/project/ansible/ - ansible-core 2.14 "C'mon Everybody" Release Notes https://github.com/ansible/ansible/blob/v2.14.4/changelogs/CHANGELOG-v2.14.rst - Introduction to ansible-test https://www.ansible.com/blog/introduction-to-ansible-test - Ansible 7.4.0 Release Notes: https://docs.ansible.com/ansible/devel/porting_guides/porting_guide_7.html#porting-guide-for-v7-4-0 - Ansible project 7.0 https://docs.ansible.com/ansible/devel/roadmap/COLLECTIONS_7.html - Ansible 2.15 roadmap https://docs.ansible.com/ansible/devel/roadmap/ROADMAP_2_15.html ## Ansible Core vs Ansible Community - What's the difference? The s... --- ## Ansible Core 2.15.0 Beta 3 Released: Key Updates URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-15-0-beta-3 Description: Discover the latest Ansible Core 2.15.0 beta 3 release, featuring new modules and performance improvements. No Ansible Community release this time. Welcome to a new episode of the Ansible Pilot from Luca Berton. The big news of the last week of April '23 is the release of the beta version of Ansible Core 2.15.0 beta 3. This time there wasn't any Ansible Community release. Let me quickly remind you that the Ansible Core contains the Ansible framework and the `ansible.builtin` collection. Nothing else. At the same time, the Ansible Community includes a lot (76+) of other collections. For example, interactive with cloud providers (Amazon, Google, Azure) and also the community-generated collection and Red Hat vendor partners. ## Links - New releases: ansible-core 2.15.0https://groups.google.com/g/ansible-devel/c/gmesMFht1Wo - ansible-core 2.15 "Ten Years Gone" Release Notes https://github.com/ansible/ansible/blob/v2.15.0b2/changelogs/CHANGELOG-v2.15.rst - ansible-core 2.15.0b3 https://pypi.org/project/ansible-core/2.15.0b3/ - Ansible 2.15 roadmap https://docs.ansible.com/ansible/devel/roadmap/ROADMAP_2_15.html ## Ansible Core vs Ansible Community - What's the difference? The size and amount of resources the Ansible Core is the smallest package. At the same time, the Ansible Community package is more extensive and has many more resources in the footprint. Why did the engineering team release two packages? Well, because sometimes you have a different use case. You want a smaller package for a specific workload. And you would like the Ansible community for her. When developing or needing a complete overview of the answerab... --- ## Ansible Core 2.15.0 Released: New Features & Changes URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-2-15-0 Description: Discover Ansible Core 2.15.0's latest features, improvements, and breaking changes. Includes new modules and key updates for better performance. ## Ansible Core 2.15.0 The changelog for version 2.15.0 of Ansible was released on 15th May 2023, a popular open-source automation tool. Here is a summary of the changes listed in the changelog: 1. New Features: - Added new tech preview dnf5 module - Added new deb822_repository module 2. Module Improvements: - Multiprocessing workers have a new mechanism for prompting for user input, instead of direct stdin access - ansible-galaxy collection install performance and reliability improvements - ansible-test improved container compatibility with hosts using cgroup v2 3. Bug Fixes: - Several bug fixes have been implemented in various modules and plugins. 4. Breaking Changes: - ansible-doc - no longer treat plugins in collections whose name starts with _ as deprecated (#79362). - ansible-test - Integration tests which depend on specific file permissions when running in an ansible-test managed host environment may require changes. Tests that require permissions other than 755 or 644 may need to be updated to set the necessary permissions as part of the test run. - ansible-test - The vcenter test plugin now defaults to using a user-provided static configuration instead of the govcsim simulator for collections. Set the ANSIBLE_VCSIM_CONTAINER environment variable to govcsim to use the simulator. Keep in mind that the simulator is deprecated and will be removed in a future release. - ansible-test sanity - previously plugins and modules in collection... --- ## Ansible Core 2.21.3 Released - Bugfix Update Overview URL: https://www.ansiblebyexample.com/articles/ansible-core-2-21-3-released-bugfix-update-overview Description: Ansible Core 2.21.3 fixes ansible-galaxy retries, rpm_key PGP parsing, powershell exec_wrapper and more. Details and how to install. # Ansible Core 2.21.3 Released - Bugfix Update Overview ## Introduction Ansible Core 2.21.3 was released on 2026-08-10, following 2.21.2. This is a bugfix-only release with no new features. Below is a rundown of the fixes included and how to install or upgrade to this version. Release page: ansible/ansible v2.21.3 ## Whats New ### Bugfixes - Add deprecation status to the tree and oneline callback DOCUMENTATION (issue #87020) - `ansible-galaxy` - fix attempting to download the collection again if the response from the server is shorter than expected, instead of failing due to the mismatched artifact hash on the first attempt (PR #86025) - `ansible-test` - fix target filtering to preserve user-specified versions that are not in the completion configuration - collection loader - fix the collection loader logic to correctly return a Python module when calling `pkgutil.iter_modules` with a package that is inside a collection path and contains compiled Python extension modules - powershell exec_wrapper - fix handling when multiple pwsh executables match, by selecting the first result (issue #87228) - `rpm_key` - ensure a trailing newline is present on PGP armor data before passing it to librpm for parsing, fixing failures on systems where `pgpParsePkts` requires it (issue #87303) The full list of changes is available in the CHANGELOG-v2.21.rst for this release. ### Release Artifacts | Artifact | Size | SHA256 | |---|---|---| | ansible_core-2.21.3-py3-none-any.whl | 2446988... --- ## Ansible cpanm Module — Install Perl Modules from CPAN URL: https://www.ansiblebyexample.com/articles/ansible-cpanm-module-install-perl-modules-from-cpan Description: Install Perl modules from CPAN using cpanminus with Ansible automation. Tested on real machines with clear, copy-paste examples. # Ansible cpanm Module — Install Perl Modules from CPAN ## Introduction The `community.general.cpanm` module install Perl modules from CPAN using cpanminus with Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.cpanm` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--ch... --- ## Ansible Create Directory with file Module URL: https://www.ansiblebyexample.com/articles/ansible-create-directory-file-module-guide Description: Create directories with Ansible using ansible.builtin.file and state: directory. Set owner, group, mode, nested paths, and recursive permissions. ## How to Create a Directory in Ansible Creating directories is one of the most common Ansible tasks. The `ansible.builtin.file` module with `state: directory` creates single or nested directories, sets ownership and permissions, and is idempotent — running it again changes nothing if the directory already exists. The shortest reliable pattern is `ansible.builtin.file` with `path: /your/directory` and `state: directory`; add `owner`, `group`, and `mode` when the directory needs specific permissions. ## Basic Syntax [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `path` | (required) | Directory path to create | | `state` | `file` | Set to `directory` to create a directory | | `owner` | — | Owner user name or UID | | `group` | — | Group name or GID | | `mode` | — | Permissions (e.g., `"0755"`, `"u=rwx,g=rx,o=rx"`) | | `recurse` | `false` | Apply owner/group/mode recursively to contents | | `selevel` | — | SELinux level | | `setype` | — | SELinux type | ## Create a Single Directory [code example] ## Create Nested Directories `state: directory` creates parent directories automatically (like `mkdir -p`): [code example] ## Create Multiple Directories [code example] ## Set Permissions [code example] ## Check If Directory Exists [code example] Note: The `stat` check is usually unnecessary — `file` with `state: directory` is already idempotent. Use `stat` only when you need conditional logic based on existenc... --- ## Ansible Create File with Content — copy, template, lineinfile URL: https://www.ansiblebyexample.com/articles/ansible-create-file-with-content-copy-template-lineinfile Description: Create files with content on remote hosts using Ansible. Use copy content, template, lineinfile, and blockinfile modules for file generation and editing. # Ansible Create File with Content — copy, template, lineinfile ## Introduction Need to create a file with specific content on remote hosts? Ansible offers several approaches: `copy` with `content` for simple text, `template` for dynamic files with variables, `lineinfile` for single-line edits, and `blockinfile` for multi-line insertions. This guide shows when to use each. ## Method 1: copy with content [code example] ### With Variables [code example] ### JSON Content [code example] ### YAML Content [code example] ## Method 2: template Module [code example] [code example] ## Method 3: lineinfile (Single Line) [code example] ## Method 4: blockinfile (Multi-line Block) [code example] ## Method 5: Create Empty File [code example] ## Comparison: When to Use Each | Method | Use Case | |--------|----------| | `copy` + `content` | Simple text, env files, small configs | | `template` | Complex files with logic (loops, conditionals) | | `lineinfile` | Modify one line in existing file | | `blockinfile` | Insert/update a multi-line section | | `file` + `state: touch` | Create empty file | ## Advanced Patterns ### Dynamic File from Loop [code example] ### Multiline String Formats [code example] ### Create File from Command Output [code example] ### Atomic File Creation (Validate First) [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | File always "changed" | Check for trailing newlines — add `\n` to content | | Variables not expanded | Us... --- ## Ansible Create File, Directory, and Delete: file Module Guide URL: https://www.ansiblebyexample.com/articles/ansible-create-file-directory-and-delete-file-module-guide Description: Complete guide to creating files, directories, and symlinks with Ansible file module. Learn how to set permissions, delete files, and manage file states. ## The ansible.builtin.file Module The `file` module manages files, directories, and symlinks on remote hosts. It's one of the most-used Ansible modules. ## Create a Directory [code example] ### Create Nested Directories [code example] ### Create Multiple Directories [code example] ## Create an Empty File (touch) [code example] ## Create a File with Content Use the `copy` module for files with content: [code example] ## Create a Symlink [code example] ## Delete a File [code example] ## Delete a Directory [code example] ## Set File Permissions [code example] ## Check if a File Exists Use the `stat` module: [code example] ## Check if a Directory Exists [code example] ## File Module States Reference | State | Description | |-------|-------------| | `file` | Ensure file exists, set attributes (no creation) | | `directory` | Create directory if missing | | `touch` | Create empty file or update timestamps | | `link` | Create symbolic link | | `hard` | Create hard link | | `absent` | Delete file or directory | ## Common Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `path` | Target path | `/opt/myapp` | | `state` | Desired state | `directory`, `absent`, `touch`, `link` | | `mode` | Permissions | `'0755'`, `'u+rwx,g+rx'` | | `owner` | File owner | `deploy` | | `group` | File group | `deploy` | | `recurse` | Apply recursively | `true` | | `src` | Source for links | `/opt/myapp/v2` | | `force` | Force link creation ... --- ## Ansible cron Module — Schedule Jobs and Manage Crontab URL: https://www.ansiblebyexample.com/articles/ansible-cron-module-schedule-jobs-crontab Description: Use the Ansible cron module to create, update, and remove cron jobs. Schedule recurring tasks, manage crontab entries, and set environment variables. ## Introduction `ansible.builtin.cron` manages crontab entries — create, update, and remove scheduled jobs. Each entry is tracked by `name`, making it idempotent: Ansible updates existing entries instead of creating duplicates. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Unique identifier for the cron entry | | `job` | — | Command to run | | `minute` | `*` | Minute (0-59, `*/5`, etc.) | | `hour` | `*` | Hour (0-23) | | `day` | `*` | Day of month (1-31) | | `month` | `*` | Month (1-12) | | `weekday` | `*` | Day of week (0-6, 0=Sunday) | | `user` | current user | Crontab owner | | `state` | `present` | `present` or `absent` | | `disabled` | `false` | Comment out the entry | | `special_time` | — | `reboot`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, `annually` | | `cron_file` | — | File in `/etc/cron.d/` instead of user crontab | | `env` | — | Set crontab environment variable | | `backup` | `false` | Backup crontab before modifying | ## Schedule Shortcuts [code example] ## Remove a Cron Job [code example] ## Cron Environment Variables [code example] ## System Cron Files (/etc/cron.d/) [code example] ## Practical Patterns ### Backup Scheduling [code example] ### Certificate Renewal [code example] ### Multiple Cron Jobs with Loop [code example] ## Troubleshooting ### Cron Job Not Running 1. Check crontab exists: `crontab -l -u deploy` 2. Check cron daem... --- ## Ansible cron Module — Schedule Tasks URL: https://www.ansiblebyexample.com/articles/ansible-cron-module-schedule-tasks-jobs Description: Manage cron jobs with the Ansible cron module. Create, modify, and remove scheduled tasks with time expressions, environment variables, and special times. ## What Is the Ansible cron Module? The Ansible cron module (`ansible.builtin.cron`) manages cron jobs on remote hosts — create, modify, and delete scheduled tasks without manually editing crontab files. It's idempotent: running the same task twice doesn't create duplicate entries. ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Description of the cron job (used as unique identifier) | | `job` | — | Command to execute | | `state` | `present` | `present` to create, `absent` to remove | | `minute` | `*` | Minute (0-59) | | `hour` | `*` | Hour (0-23) | | `day` | `*` | Day of month (1-31) | | `month` | `*` | Month (1-12) | | `weekday` | `*` | Day of week (0-6, 0=Sunday) | | `special_time` | — | `reboot`, `hourly`, `daily`, `weekly`, `monthly`, `yearly` | | `user` | current user | User whose crontab to modify | | `cron_file` | — | File in `/etc/cron.d/` instead of user crontab | | `env` | `false` | Manage environment variable instead of job | | `disabled` | `false` | Comment out the job (keep but don't run) | | `backup` | `false` | Backup crontab before modifying | ## Create a Cron Job [code example] ## Special Time Strings [code example] ## Cron Environment Variables [code example] ## System Cron Files (/etc/cron.d/) [code example] ## Remove a Cron Job [code example] ## Disable Without Removing [code example] ## Practical Patterns ### Application Server Cron Jobs [code example] ### Database Maint... --- ## Ansible cron Module: Schedule Jobs on Linux Servers URL: https://www.ansiblebyexample.com/articles/ansible-cron-module-schedule-jobs-on-linux-servers Description: Manage cron jobs with Ansible — create, update, and remove scheduled tasks using the cron module. Practical examples for backups, cleanup, monitoring. ## The ansible.builtin.cron Module The `cron` module manages crontab entries on remote hosts — create, modify, and remove scheduled jobs without manually editing crontab files. ## Create a Cron Job [code example] ## Common Schedule Patterns ### Every 5 Minutes [code example] ### Every Hour [code example] ### Daily at Midnight [code example] ### Weekly (Sunday at 3 AM) [code example] ### Monthly (1st of month at 4 AM) [code example] ## Cron for a Specific User [code example] ## Set Environment Variables [code example] ## Remove a Cron Job [code example] ## Disable (Comment Out) a Cron Job [code example] ## Use special_time Shortcuts [code example] Available `special_time` values: `reboot`, `yearly`, `annually`, `monthly`, `weekly`, `daily`, `hourly`. ## Multiple Cron Jobs with a Loop [code example] ## Parameters Reference | Parameter | Description | Example | |-----------|-------------|---------| | `name` | Description (identifier) | `"daily backup"` | | `job` | Command to execute | `"/opt/backup.sh"` | | `minute` | Minute (0-59, */5) | `"0"` | | `hour` | Hour (0-23) | `"2"` | | `day` | Day of month (1-31) | `"1"` | | `month` | Month (1-12) | `"*/3"` | | `weekday` | Day of week (0-6, Sun=0) | `"1-5"` | | `user` | Crontab owner | `"deploy"` | | `state` | present/absent | `"present"` | | `disabled` | Comment out | `true` | | `special_time` | Schedule shortcut | `"daily"` | | `env` | Environment variable | `true` | --- *Explore 800+ Ansible tutorial... --- ## Ansible Custom Facts — Create Local Facts for Host-Specific Data URL: https://www.ansiblebyexample.com/articles/ansible-custom-facts-create-local-facts-for-host-specific-data Description: Create custom Ansible facts with local fact files, set_fact, and custom fact scripts. Store host-specific data like app versions, roles. # Ansible Custom Facts — Create Local Facts for Host-Specific Data ## Introduction Ansible gathers system facts automatically (OS, IP, memory, etc.), but you often need host-specific data that doesn't come from the system — application version, deployment environment, business unit, or custom health metrics. Custom facts let you define this data on each host and use it in playbooks just like built-in facts. ## Local Facts (fact.d) Place `.fact` files in `/etc/ansible/facts.d/` on the remote host. Ansible reads them during `gather_facts` and makes them available as `ansible_local`. ### INI Format [code example] [code example] ### JSON Format [code example] Save as `/etc/ansible/facts.d/app.fact` — Ansible detects JSON automatically. [code example] ### Executable Fact Scripts Make the `.fact` file executable — Ansible runs it and parses the JSON output: [code example] [code example] ## Deploy Custom Facts with Ansible [code example] ### Template for Dynamic Facts [code example] ## Custom Facts Module (set_fact) For facts that don't need to persist on disk: [code example] ## Local Facts vs set_fact | Feature | Local Facts (`facts.d`) | `set_fact` | |---------|------------------------|-----------| | Stored on | Remote host disk | In-memory | | Persists across runs | ✅ | ❌ (unless `cacheable`) | | Needs `gather_facts` | ✅ | ❌ | | Namespace | `ansible_local.*` | Top-level | | Dynamic computation | Via executable scripts | Via Jinja2 | | Use case | Host ident... --- ## Ansible Custom Modules — Write Your Own in Python URL: https://www.ansiblebyexample.com/articles/ansible-custom-module-development-python Description: Build custom Ansible modules in Python. Module structure, argument spec, return values, check mode support, and testing with ansible-test. Complete. # Ansible Custom Modules — Write Your Own in Python ## Introduction When Ansible's 6,000+ built-in modules don't cover your specific use case, writing a custom module is the solution. Custom modules let you extend Ansible with your own logic while maintaining idempotency, check mode support, and seamless integration with playbooks. This guide walks you through creating production-quality custom modules in Python, from basic structure to testing and distribution. ## Why Write Custom Modules? **Use cases for custom modules:** - Interact with proprietary APIs not covered by existing modules - Wrap complex shell commands in an idempotent interface - Enforce organization-specific business logic - Create simplified interfaces for common multi-step operations - Integrate with internal tools and services ## Module Structure Every Ansible module follows a standard structure: \`\`\`python #!/usr/bin/python # -*- coding: utf-8 -*- DOCUMENTATION = r''' --- module: my_custom_module short_description: Description of what the module does version_added: "1.0.0" description: - Detailed description of the module functionality. - Supports check mode and diff mode. options: name: description: - Name of the resource to manage. required: true type: str state: description: - Desired state of the resource. choices: ['present', 'absent'] default: present type: str force: description: - Force the operation even if the resource exist... --- ## Ansible Data Monetization Platform Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/ansible-data-monetization-platform-infrastructure Description: Automate data monetization infrastructure with Ansible. Deploy data marketplaces, manage access controls, and orchestrate privacy-preserving data sharing. ## Introduction Data monetization — turning organizational data into revenue through products, marketplaces, or licensing — requires infrastructure for data catalogs, access control, privacy preservation, usage metering, and billing. As data becomes a core enterprise asset, the platforms that manage sharing and monetization become critical. Ansible automates the provisioning and governance of this infrastructure. ## Data Monetization Platform [code example] ## Data Catalog Deployment [code example] ## Privacy-Preserving Data Sharing [code example] ## Usage Metering and Billing [code example] ## Data Governance and Compliance [code example] ## Related Articles - Ansible AI Infrastructure Optimization - Ansible ServiceNow Integration - Ansible Confidential Computing - Ansible Digital Provenance C2PA ## Conclusion Data monetization platforms require infrastructure across five layers: cataloging (discovery and metadata), privacy (anonymization and clean rooms), access control (authentication and authorization), metering (usage tracking and billing), and governance (compliance and lineage). Ansible automates all five — from deploying Apache Atlas catalogs to configuring differential privacy engines to setting up Stripe-based usage billing. As organizations recognize data as a revenue asset, the infrastructure to safely share and monetize it becomes a competitive differentiator. --- ## Ansible date_time — Timestamp Examples URL: https://www.ansiblebyexample.com/articles/using-date-time-and-timestamp-in-ansible-playbook-ansible-tip-and-tricks Description: Use ansible_date_time for dates, timestamps, and time formatting in Ansible Playbooks. Complete guide with strftime filters, comparisons. ## Introduction Working with dates, times, and timestamps is essential for tasks like naming backups, rotating logs, scheduling operations, and adding deployment metadata. Ansible provides the `ansible_date_time` fact and powerful Jinja2 filters for all date/time operations. This guide covers everything from basic timestamp usage to advanced date arithmetic and conditional time-based logic. ## The ansible_date_time Fact The `ansible_date_time` variable is automatically populated when `gather_facts: true` (the default). It contains: [code example] **Important**: `ansible_date_time` is captured at the start of fact gathering. It does NOT update during playbook execution. For real-time timestamps within a playbook, use the `now()` function or `strftime` filter. ## Basic Usage ### Display Date and Time [code example] ### Use in File Names [code example] ### Use in Variables [code example] ## The now() Function and strftime Filter For **real-time** timestamps (not captured at fact-gather time), use `now()`: [code example] ### Common strftime Formats | Format | Example | Description | |--------|---------|-------------| | `%Y-%m-%d` | 2026-04-20 | ISO date | | `%H:%M:%S` | 22:15:30 | Time (24h) | | `%Y%m%d%H%M%S` | 20260420221530 | Compact timestamp | | `%s` | 1745187600 | Unix epoch | | `%A` | Monday | Weekday name | | `%B` | April | Month name | | `%d/%m/%Y` | 20/04/2026 | European date | | `%m/%d/%Y` | 04/20/2026 | US date | | `%Y-%m-%dT%H:%M:%SZ` | 2026-04-20T2... --- ## Ansible dconf Module — Manage GNOME Desktop Settings URL: https://www.ansiblebyexample.com/articles/ansible-dconf-module-manage-gnome-desktop-settings Description: Configure GNOME desktop settings and preferences using dconf with Ansible. Hands-on, tested examples and best practices for Ansible dconf Module. # Ansible dconf Module — Manage GNOME Desktop Settings ## Introduction The `community.general.dconf` module configure GNOME desktop settings and preferences using dconf with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.dconf` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--... --- ## Ansible debconf Module — Configure Debian Package Questions URL: https://www.ansiblebyexample.com/articles/ansible-debconf-module-configure-debian-package-questions Description: Pre-seed debconf answers for Debian/Ubuntu package installations with Ansible. Hands-on, tested examples and best practices for Ansible debconf Module. # Ansible debconf Module — Configure Debian Package Questions ## Introduction The `ansible.builtin.debconf` module pre-seed debconf answers for Debian/Ubuntu package installations with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.debconf` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run... --- ## Ansible debug Module — Print Variables and Messages URL: https://www.ansiblebyexample.com/articles/ansible-debug-module-print-variables-messages Description: Use the Ansible debug module to print variables, facts, registered output, and custom messages during playbook execution. Verbosity levels. ## Introduction `ansible.builtin.debug` prints messages and variable values during playbook runs. It's the primary tool for troubleshooting — inspect facts, check registered output, verify variable values, and trace playbook logic. ## Print a Message [code example] ## Print a Variable [code example] ### msg vs var [code example] ## Print Registered Output [code example] ## Verbosity Levels Only show debug output at certain verbosity levels (`-v`, `-vv`, `-vvv`): [code example] [code example] ## Practical Patterns ### Debug Loop Results [code example] ### Debug Variables Before Using Them [code example] ### Print All Host Variables [code example] ### Checkpoint Messages [code example] ### Assert vs Debug For validation, consider `assert` instead of debug + manual checking: [code example] ## Troubleshooting ### "msg" and "var" Are Mutually Exclusive [code example] ### Variable Shows as String Instead of Dict/List Jinja2 converts everything to strings in `msg`. Use `var` to see the actual structure: [code example] ## Related Articles - Ansible Facts Guide - Ansible register Variables - Ansible set_fact Module - Ansible assert Module - Ansible when Conditional ## Conclusion `debug` is essential for Ansible troubleshooting. Use `msg` for custom formatted messages and `var` for raw variable inspection. Add `verbosity` levels to keep output clean during normal runs while having detailed diagnostics available with `-v` flags. For production playbook... --- ## Ansible debug vs assert — Validate and Troubleshoot Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-debug-vs-assert Description: Compare Ansible debug and assert modules. Learn when to use each for troubleshooting variables, validating conditions, and building defensive playbooks. ## Introduction `debug` and `assert` look similar — both evaluate expressions and print messages. But they serve different purposes: `debug` is for inspecting values during development, `assert` is for enforcing conditions that must be true. Using `debug` when you need `assert` means silent failures; using `assert` for inspection clutters playbooks with unnecessary failures. ## Quick Comparison | Feature | `debug` | `assert` | |---------|---------|----------| | Purpose | Print/inspect values | Validate conditions | | On failure | Never fails | Fails the play | | Output | Shows msg or var | Shows success_msg or fail_msg | | Use case | Troubleshooting, development | Pre-flight checks, validation | | Production use | Remove or disable | Keep — they're guardrails | ## debug — Inspect Values [code example] ### Debug Patterns [code example] ## assert — Enforce Conditions [code example] ### Assert Patterns [code example] ## Using Both Together [code example] ## Common Mistakes [code example] ## Related Articles - Ansible debug Module - Ansible assert Module - Ansible Error Handling - Ansible Undefined Variable Error ## Conclusion **debug** = "show me this value" (development/troubleshooting). **assert** = "this must be true or stop" (validation/guardrails). Use `assert` at the start of playbooks for pre-flight checks and after critical operations for verification. Use `debug` during development, then either remove it or gate it behind `verbosity` for production. T... --- ## Ansible Debugger — Interactive Debugging for Failed Tasks URL: https://www.ansiblebyexample.com/articles/ansible-debugger Description: How to use the Ansible debugger to inspect and fix failed tasks interactively. Enable with debugger: on_failed, use p, r, c, q commands to examine. ## What is the Ansible Debugger? The Ansible debugger is an interactive prompt that activates when a task fails (or always, depending on configuration). It lets you inspect variables, modify arguments, and retry the task without restarting the entire playbook. ## Enable the Debugger ### Per-Play [code example] ### Per-Task [code example] ### Global (ansible.cfg) [code example] ### Via Environment Variable [code example] ## Debugger Strategies | Strategy | When debugger activates | |----------|----------------------| | `always` | After every task | | `never` | Never (default) | | `on_failed` | Only on task failure | | `on_unreachable` | When host is unreachable | | `on_skipped` | When task is skipped | ## Debugger Commands When the debugger activates, you get an interactive prompt: [code example] | Command | Short | Description | |---------|-------|-------------| | `print` | `p` | Print variable or task info | | `task.args[key] = value` | — | Modify task arguments | | `task_vars[key] = value` | — | Modify task variables | | `redo` | `r` | Retry the task with current args | | `continue` | `c` | Continue to next task (mark as failed) | | `quit` | `q` | Quit the playbook | | `update_task` | `u` | Update task from modified args | ## Practical Example: Fixing a Typo [code example] When this fails: [code example] ## Inspecting Variables [code example] ## Modifying and Retrying [code example] ## Real-World Debugging Workflow [code example] If the template t... --- ## Ansible Default SSH Username & Password URL: https://www.ansiblebyexample.com/articles/set-default-ansible-ssh-username-and-password-for-automation Description: Configure default SSH credentials in ansible.cfg, inventory, and group_vars. Set ansible_user, ansible_password, and ansible_ssh_private_key_file. Learn how to configure default SSH credentials for seamless Ansible automation. ## Introduction When using Ansible to manage infrastructure, specifying the same username and password for each host in the inventory file can be repetitive. To streamline this process and set default credentials globally, follow these best practices. --- ## 1. **Setting Default Variables in the Inventory File** You can use the `[all:vars]` group in your inventory file to define default values for all hosts. For example: [code example] This method eliminates the need to specify `ansible_user` and `ansible_password` for individual hosts. --- ## 2. **Using Group Variables** If you want to specify default credentials for a specific group of hosts, you can create a directory structure following Ansible best practices. For instance: [code example] Content of `all.yml`: [code example] You can also create separate files for each group like `group_vars/master.yml` for the `master` group. --- ## 3. **Dynamic Inventory or Central Configuration** For larger environments: - Use **dynamic inventory** scripts to generate host details dynamically. - Define these variables in `ansible.cfg` to make them universally available. For `ansible.cfg`: [code example] --- ## 4. **Avoid Hardcoding Credentials** While these methods work well, hardcoding credentials in plain text is a security risk. To secure your Ansible environment: - Use **SSH keys** instead of passwords. - Store sensitive credentials in... --- ## Ansible Delay and Sleep — Wait Between Tasks URL: https://www.ansiblebyexample.com/articles/ansible-delay-and-sleep-wait-between-tasks Description: Add delays between Ansible tasks using pause, wait_for, and async. Implement retries with until loops, connection wait patterns, and timed task spacing. # Ansible Delay and Sleep — Wait Between Tasks ## Introduction Sometimes tasks need breathing room — wait for a service to start, pause between API calls to avoid rate limits, or delay a reboot check. Ansible provides several mechanisms: `pause`, `wait_for`, `until` loops with `delay`, and `async`. This guide covers when to use each. ## ansible.builtin.pause [code example] ### pause Parameters | Parameter | Description | |-----------|-------------| | `seconds` | Number of seconds to pause | | `minutes` | Number of minutes to pause | | `prompt` | Message to display during pause | | `echo` | Whether to echo user input (default: true) | ## wait_for — Wait for a Condition [code example] ### wait_for Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `port` | — | TCP port to check | | `host` | 127.0.0.1 | Host to check | | `path` | — | File path to check | | `search_regex` | — | Regex to search in file | | `state` | started | started, stopped, present, absent, drained | | `delay` | 0 | Seconds to wait before first check | | `timeout` | 300 | Max seconds to wait | | `sleep` | 1 | Seconds between checks | ## until Loop with delay [code example] ## Common Patterns ### Reboot and Wait [code example] ### Rate-Limited API Calls [code example] ### Service Start + Verify [code example] ### Rolling Deployment Spacing [code example] ### Database Migration Wait [code example] ## Comparison | Method | Use Case | Blocks Play? | |--... --- ## Ansible delegate_to: Run Tasks on Localhost & Other Hosts URL: https://www.ansiblebyexample.com/articles/ansible-delegate-to-run-tasks-different-hosts Description: Ansible delegate_to runs tasks on localhost or remote hosts while keeping variable context. Guide with load balancer, database, monitoring, and DNS examples. ## Introduction `delegate_to` is an Ansible keyword that runs a task on a different host while keeping variables bound to the original play target. The task executes on the delegated host (localhost, a load balancer, database, or control point), but all variables still reference the original managed host. This is essential for rolling updates with load balancer management, monitoring checks, DNS registration, centralized database operations, and any task that needs to run outside the primary play target while maintaining context. ## Basic Usage [code example] ## Common Patterns ### Load Balancer Management [code example] ### Monitoring / Alerting [code example] ### Database Operations from App Server [code example] ### DNS Registration [code example] ## delegate_to: localhost [code example] ## delegate_to with delegate_facts By default, facts from delegated tasks are assigned to the **original host**. Use `delegate_facts: true` to assign them to the delegated host: [code example] ## delegate_to with run_once [code example] ## Variable Context Tasks run on the delegated host, but variables reference the **original play host**: [code example] ## Troubleshooting ### "SSH connection failed" on Delegated Host The delegated host must be reachable and in the inventory (or use `add_host` first): [code example] ### Connection Type for localhost [code example] ## Related Articles - Ansible Playbook Guide - Ansible when Conditional - Ansible wait_for Modul... --- ## Ansible Delete File — Remove Files and Directories URL: https://www.ansiblebyexample.com/articles/ansible-delete-file-remove-files-and-directories Description: Delete files and directories on remote hosts with Ansible file module. Remove single files, directories, wildcards, and conditional deletions. # Ansible Delete File — Remove Files and Directories ## Introduction The `ansible.builtin.file` module with `state: absent` removes files and directories on remote hosts. It's idempotent — running it again on an already-deleted path doesn't fail or report "changed". This guide covers single files, directories, wildcards, conditional deletion, and cleanup patterns. ## Quick Reference [code example] ## Delete Patterns (Wildcards) [code example] ### Delete All Files in Directory (Keep Directory) [code example] ## Conditional Deletion [code example] ## Common Cleanup Patterns ### Post-Deployment Cleanup [code example] ### Clean Temp Files by Age [code example] ### Remove Package and Config [code example] ## Delete Symlinks [code example] ## Safe Deletion with Backup [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | Permission denied | Use `become: true` | | Directory not empty | `state: absent` removes recursively — this always works | | Symlink target deleted instead | This doesn't happen — `file: absent` removes the path itself | | Need to delete by pattern | Use `find` module first, then loop over results | | Task shows "ok" not "changed" | File already absent — this is correct idempotent behavior | ## file (absent) vs shell rm | Feature | `file: absent` | `shell: rm` | |---------|----------------|-------------| | Idempotent | ✅ | ❌ (fails if missing without -f) | | Check mode | ✅ | ❌ | | Diff mode | ✅ | ❌ | | Wildcards | ❌ (use find)... --- ## Ansible Deploy Docker Containers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-deploy-docker-containers-complete-guide Description: Deploy Docker containers with Ansible community.docker collection. Hands-on, tested examples and best practices for Ansible Deploy Docker Containers. # Ansible Deploy Docker Containers — Complete Guide ## Introduction Deploy Docker containers with Ansible community.docker collection. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy Docker containers with Ansible community.docker collection. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Deploy Java Applications — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-deploy-java-applications-complete-guide Description: Deploy WAR and JAR files to Tomcat and Spring Boot with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible Deploy Java Applications — Complete Guide ## Introduction Deploy WAR and JAR files to Tomcat and Spring Boot with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy WAR and JAR files to Tomcat and Spring Boot with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible deploy_helper Module — Manage Deployment Directory Structure URL: https://www.ansiblebyexample.com/articles/ansible-deploy-helper-module-manage-deployment-directory-structure Description: Create and manage Capistrano-style deployment directory structures with Ansible. With clear, copy-paste, step-by-step examples. # Ansible deploy_helper Module — Manage Deployment Directory Structure ## Introduction The `community.general.deploy_helper` module create and manage Capistrano-style deployment directory structures with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.deploy_helper` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4.... --- ## Ansible Development: A Comprehensive Guide URL: https://www.ansiblebyexample.com/articles/ansible-development Description: Learn how to automate IT tasks using Ansible, covering everything from installation to advanced integration with Kubernetes and cloud services. ## Ansible Development: A Comprehensive Guide Ansible is an open-source automation tool developed by Red Hat that enables IT professionals to automate tasks such as configuration management, application deployment, and task automation. This article delves into the essential aspects of Ansible development, covering its architecture, core concepts, and practical applications. ## Understanding Ansible Architecture Ansible's architecture comprises the following key components: 1. **Ansible Engine**: This is the core component that executes the automation tasks defined in Ansible playbooks. 2. **Ansible Playbooks**: Written in YAML, playbooks describe the desired state of the system and define the tasks to be executed. 3. **Ansible Inventory**: This is a file that lists the hosts and groups of hosts that Ansible will manage. 4. **Modules**: These are the units of work that Ansible executes. They can be anything from installing software to managing services. 5. **Plugins**: These extend Ansible’s core functionalities, including action plugins, cache plugins, and callback plugins. Ansible operates on a push model, where tasks are executed from a central control node to the managed nodes over SSH or WinRM, eliminating the need for agent software on the managed nodes. ## Getting Started with Ansible Ansible is favored for its simplicity and ease of use. Here’s how you can get started with Ansible: 1. **Installation**: Ansible can be installed on any Unix-like system, including... --- ## Ansible DigitalOcean Droplets — Create and Manage URL: https://www.ansiblebyexample.com/articles/ansible-digitalocean-droplets-create-and-manage Description: Ansible DigitalOcean Droplets guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible DigitalOcean Droplets — Create and Manage ## Introduction Create and Manage. Automate DigitalOcean infrastructure with Ansible using the `community.digitalocean` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches DigitalOcean naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different invento... --- ## Ansible Disk Management — Partitions LVM and RAID URL: https://www.ansiblebyexample.com/articles/ansible-disk-management-partitions-lvm-and-raid Description: Ansible Disk Management guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Disk Management — Partitions LVM and RAID ## Introduction Partitions LVM and RAID. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Disk Management requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible Dnsmasq DHCP — Network Services Automation URL: https://www.ansiblebyexample.com/articles/ansible-dnsmasq-dhcp-dns-network-services Description: Deploy Dnsmasq with Ansible for DHCP, DNS, and PXE boot services. DHCP reservations, DNS forwarding, split DNS, PXE/TFTP configuration, and network boot. ## Introduction Dnsmasq provides lightweight DHCP, DNS, and TFTP services in a single daemon — perfect for lab environments, edge networks, and PXE boot infrastructure. Ansible automates the full setup: DHCP ranges with MAC-based reservations, DNS forwarding with local overrides, and PXE boot for automated OS installation. ## Deploy Dnsmasq [code example] ### Main Config [code example] ### DHCP Reservations [code example] [code example] ### Local DNS [code example] [code example] ## PXE Boot Setup [code example] ## Health Check [code example] ## Troubleshooting ### DHCP Not Assigning [code example] ### Config Validation [code example] ## Related Articles - Ansible BIND DNS - Ansible Chrony NTP - Ansible Firewall Module - Ansible Hostname Module ## Conclusion Dnsmasq combines DHCP, DNS, and TFTP in a single lightweight daemon — Ansible templates the config from YAML variables for DHCP ranges, MAC reservations, local DNS entries, and PXE boot menus. Generate DNS records directly from Ansible inventory so every managed host is automatically resolvable. Perfect for labs, edge sites, and bootstrap infrastructure. --- ## Ansible Docker — Containers & Images URL: https://www.ansiblebyexample.com/articles/ansible-docker-containers-images-compose Description: Automate Docker with Ansible. Pull images, run containers, manage networks and volumes, deploy with docker_compose, and build images with practical. ## Introduction The `community.docker` collection lets you manage Docker from Ansible — pull images, run containers, manage networks and volumes, and deploy multi-container apps with Docker Compose. Automate your entire container lifecycle alongside infrastructure provisioning. ## Install the Collection [code example] Requirements on remote hosts: - Docker Engine installed - Python `docker` SDK (`pip install docker`) [code example] ## Run a Container [code example] ## Container Parameters | Parameter | Description | |-----------|-------------| | `name` | Container name (required) | | `image` | Docker image with tag | | `state` | `started`, `stopped`, `absent`, `present` | | `ports` | Port mappings (`host:container`) | | `volumes` | Volume mounts (`host:container[:mode]`) | | `env` | Environment variables (dict) | | `restart_policy` | `no`, `always`, `unless-stopped`, `on-failure` | | `network_mode` | `bridge`, `host`, `none`, or network name | | `networks` | List of networks to connect to | | `command` | Override container command | | `entrypoint` | Override entrypoint | | `memory` | Memory limit (`512m`, `1g`) | | `cpus` | CPU limit | | `labels` | Container labels (dict) | | `pull` | Pull policy: `always`, `missing`, `never` | | `recreate` | Force recreate even if running | | `comparisons` | Control what triggers recreation | ## Pull Images [code example] ## Docker Networks [code example] ## Docker Volumes [code example] ## Docker Compose [code example] ###... --- ## Ansible docker_network Module — Manage Docker Networks URL: https://www.ansiblebyexample.com/articles/ansible-docker-network-module-manage-docker-networks Description: Create, configure, and remove Docker networks for container communication. Hands-on, tested examples and best practices for Ansible docker_network Module. # Ansible docker_network Module — Manage Docker Networks ## Introduction The `community.docker.docker_network` module create, configure, and remove Docker networks for container communication. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.docker` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.docker.docker_network` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode... --- ## Ansible docker_volume Module — Manage Docker Volumes URL: https://www.ansiblebyexample.com/articles/ansible-docker-volume-module-manage-docker-volumes Description: Create and manage Docker volumes for persistent container storage with Ansible. With clear, copy-paste, step-by-step examples. # Ansible docker_volume Module — Manage Docker Volumes ## Introduction The `community.docker.docker_volume` module create and manage Docker volumes for persistent container storage with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.docker` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.docker.docker_volume` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mod... --- ## Ansible Documentation: Your Comprehensive Guide URL: https://www.ansiblebyexample.com/articles/ansible-documentation Description: Explore Ansible documentation with essential guides, practical examples, and best practices for effective IT automation and management. ## Ansible Documentation: Your Comprehensive Guide Ansible, an open-source automation tool developed by Red Hat, is designed to simplify complex IT tasks such as configuration management, application deployment, and orchestration. Its clear and straightforward documentation is essential for both beginners and experienced users to understand and implement Ansible effectively. This article explores the structure, key components, and best practices for navigating Ansible documentation. ## Understanding Ansible Documentation Ansible documentation is well-structured and divided into several main sections, each catering to different aspects of the tool. Here's a breakdown of the key sections: 1. **Introduction and Getting Started**: - **Overview**: Provides a high-level understanding of Ansible, its architecture, and core concepts. - **Installation Guide**: Step-by-step instructions on how to install Ansible on various platforms including Linux, macOS, and Windows. 2. **User Guide**: - **Getting Started**: Introduction to basic Ansible concepts and how to set up your first playbook. - **Inventory**: Detailed explanation of how to define and manage your inventory of hosts. - **Modules and Plugins**: Comprehensive list of built-in modules and plugins, with examples and usage guidelines. 3. **Playbooks**: - **Writing Playbooks**: Guidelines on how to write effective and efficient playbooks using YAML. - **Variables and Facts**: How to use variables and gathe... --- ## Ansible Domain-Specific Language Models Fine-Tuning Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-domain-specific-language-models-fine-tuning Description: Automate domain-specific LLM infrastructure with Ansible. Deploy fine-tuning pipelines, manage training data, and serve specialized models at scale. ## Introduction General-purpose LLMs are powerful but often insufficient for specialized domains — legal, medical, financial, scientific. Domain-specific language models (DSLMs) are fine-tuned on industry data to deliver superior accuracy in narrow fields. Building and serving these models requires substantial infrastructure: GPU clusters for training, data pipelines for curation, model registries for versioning, and inference servers for production. Ansible automates the full lifecycle. ## Domain-Specific LM Architecture [code example] ## Training Data Pipeline [code example] ## Fine-Tuning Infrastructure [code example] ## Evaluation Pipeline [code example] ## Model Serving [code example] ## Industry Examples [code example] ## Related Articles - Ansible AI Supercomputing GPU Clusters - Ansible AI Infrastructure Optimization - Ansible AI-Native Development - Ansible Agentic AI Infrastructure ## Conclusion Domain-specific language models outperform general LLMs in specialized fields but require significant infrastructure: data pipelines for curation and quality control, GPU clusters for fine-tuning, evaluation pipelines for benchmarking, and inference servers for production serving. Ansible automates this entire lifecycle — from provisioning multi-node training clusters with DeepSpeed to deploying vLLM inference servers with A/B testing. As organizations invest in proprietary AI models trained on their domain data, the infrastructure to build and serve these m... --- ## Ansible Download File from URL — get_url & uri Module Guide URL: https://www.ansiblebyexample.com/articles/ansible-download-file-from-url-get-url-uri Description: Download files from URLs with Ansible using get_url and uri modules. Includes checksum verification, authentication, proxy support, and large file. ## Introduction Downloading files is a core Ansible task — binaries, archives, config files, scripts, certificates. The `ansible.builtin.get_url` module handles most cases: HTTP/HTTPS/FTP downloads with checksum verification, authentication, and proxy support. For more control (custom headers, API downloads, POST requests), use `ansible.builtin.uri` with `dest`. ## Quick Start [code example] ## get_url Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `url` | (required) | URL to download from | | `dest` | (required) | Destination path (file or directory) | | `checksum` | — | Verify integrity: `sha256:` or URL | | `mode` | — | File permissions after download | | `owner` | — | File owner | | `group` | — | File group | | `timeout` | 10 | Connection timeout in seconds | | `force` | `false` | Download even if file exists | | `headers` | — | Custom HTTP headers (dict) | | `url_username` | — | HTTP Basic Auth username | | `url_password` | — | HTTP Basic Auth password | | `validate_certs` | `true` | Verify SSL certificates | | `use_proxy` | `true` | Use system proxy settings | | `tmp_dest` | — | Temporary download location | | `backup` | `false` | Backup existing file before overwriting | ## Download with Checksum Verification Always verify checksums for binaries and security-sensitive files: [code example] ## Download with Authentication [code example] ## Download and Extract Archive [code example] ## Download Scripts and Execute ... --- ## Ansible dpkg_selections — Hold and Unhold Packages URL: https://www.ansiblebyexample.com/articles/ansible-dpkg-selections-hold-and-unhold-packages Description: Ansible dpkg_selections guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible dpkg_selections — Hold and Unhold Packages ## Introduction Hold and Unhold Packages. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible dpkg_selections requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible Dry Run — Check & Diff Mode URL: https://www.ansiblebyexample.com/articles/ansible-playbook-dry-run-check-and-diff-mode Description: Run Ansible playbooks in dry-run mode with --check and --diff. Preview changes before applying, test idempotency, and validate configurations safely. ## How to Dry Run an Ansible Playbook? **An Ansible dry run previews the changes a playbook would make to the target hosts without actually applying them**, using the `--check` and `--diff` command-line flags or the equivalent `check_mode` and `diff` task statements. The check and diff modes are extremely useful to have a clear vision of the changes that are going to be performed on the target node. ## Ansible Playbook Dry Run How to Dry Run the Ansible Playbook: - check - diff command-line interface parameters - `--check` - `--diff` Ansible Task statements - `check_mode: true` - `diff: true` ## How to Dry Run an Ansible Playbook Sometimes you need to deep-dive your Ansible Playbook to validate any changes on the target node. It is useful to validate the code and have a clear vision of the single Ansible Task or Ansible Playbook outcome. Let's explore the two modes: `check` and `diff` that you could enable via the `ansible-playbook` command or the Ansible Task statements `check_mode: true` and `diff: true`inside the Playbook code. These modes can be used separately or together. The `check` mode is just a simulation, it's great to validate the Ansible Playbook without performing any action on the target machine. The `diff` mode reports the changes made for any module that supports the diff mode. It's common to combine together the two modes `--check --diff` in order to simulate the execution and have the full reports of changes and increase the execution verbosity. ## Lin... --- ## Ansible Dry Run — Check Mode and Diff Mode Explained URL: https://www.ansiblebyexample.com/articles/ansible-dry-run-check-mode-diff-mode-preview-changes-safely Description: Preview Ansible changes without applying them using --check and --diff flags. Test playbooks safely, validate configurations, and audit drift. # Ansible Dry Run — Check Mode and Diff Mode Explained ## Introduction Ansible's check mode (`--check`) previews what would change without making any modifications. Diff mode (`--diff`) shows the exact content differences. Together, they let you audit changes before applying them — essential for production deployments. ## Quick Reference [code example] ## Check Mode Output [code example] "changed" in check mode = **would change** if run for real. ## Diff Mode Output [code example] ## Per-Task Check Mode Control [code example] ### check_mode Parameter [code example] ## ansible_check_mode Variable [code example] ## Modules That Support Check Mode | Module | Check Mode Support | |--------|-------------------| | `copy` | ✅ Full (shows diff) | | `template` | ✅ Full (shows diff) | | `file` | ✅ Full | | `service` | ✅ Full | | `apt`/`yum` | ✅ Full | | `lineinfile` | ✅ Full | | `command`/`shell` | ❌ Skipped (use `check_mode: false`) | | `raw` | ❌ Skipped | | `script` | ❌ Skipped | ## Common Patterns ### Pre-Flight Validation [code example] ### Configuration Audit (Drift Detection) [code example] [code example] ### Safe Partial Runs [code example] ### CI/CD Integration [code example] ## Diff Mode Options [code example] [code example] ## Limitations 1. **`command`/`shell` modules are skipped** — Ansible can't predict their output 2. **Dependent tasks may fail** — if task B depends on task A's changes 3. **Idempotency issues visible** — modules that aren't... --- ## Ansible Dry Run: Check and Diff Mode Explained URL: https://www.ansiblebyexample.com/articles/ansible-dry-run-check-and-diff-mode-explained Description: Learn Ansible dry run: Use --check and --diff flags to preview playbook changes before applying them. Safe testing without modifying servers. ## What is a Dry Run? A **dry run** lets you see what changes Ansible *would* make — without actually changing anything. Use `--check` to simulate and `--diff` to see the exact differences. [code example] ## --check (Check Mode) Check mode simulates the playbook run. Tasks report what they *would* do: [code example] Output: [code example] ### Important Limitations Not all modules support check mode. Modules that don't will either: - Skip the task (with a warning) - Run normally (ignoring check mode) The `command` and `shell` modules **always show "skipped"** in check mode because Ansible can't predict their output: [code example] ## --diff (Diff Mode) Shows the exact line-by-line differences for file changes: [code example] Output: [code example] ## Combining --check and --diff The most useful combination — see what would change and the exact differences: [code example] This is the recommended pre-deployment check: [code example] ## Per-Task Check Mode Control ### Force a task to always run (even in check mode) [code example] ### Force a task to always use check mode [code example] ## Using ansible_check_mode Variable [code example] ## Practical Workflow ### Safe Deployment Process [code example] ### CI/CD Integration [code example] ## Tips 1. **Always dry-run before production** — `--check --diff` is your safety net 2. **Not all modules support check mode** — `command`, `shell`, `raw` can't simulate 3. **Use `check_mode: false`** for data-gat... --- ## Ansible Dynamic Inventory — Auto-Discover Cloud Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-cloud-infrastructure Description: Use Ansible dynamic inventory to auto-discover AWS EC2, Azure VMs, GCP instances, and Docker containers. Plugins, scripts, and practical cloud automation. ## Introduction Dynamic inventory automatically discovers your infrastructure from cloud APIs, container platforms, and CMDBs. Instead of maintaining static host lists, Ansible queries AWS, Azure, GCP, Docker, or any API to build the inventory at runtime. ## AWS EC2 [code example] [code example] ## Azure [code example] ## GCP [code example] ## Docker [code example] ## How It Works [code example] ## Key Concepts ### keyed_groups Auto-create groups from host attributes: [code example] ### compose Set host variables from instance attributes: [code example] ### groups Define groups using conditions: [code example] ### filters Limit which instances are included: [code example] ## Multiple Inventories [code example] ## Combine Static + Dynamic [code example] Both inventories merge when using `-i inventory/` directory. ## Cache for Performance [code example] ## Custom Inventory Script For APIs without a plugin, write a script: [code example] [code example] ## Troubleshooting ### "No hosts matched" [code example] ### Slow Inventory Enable caching in `ansible.cfg`: [code example] ### AWS Credentials [code example] ## Related Articles - Ansible Inventory Guide - Ansible Variables Guide - Ansible AWS Cloud Guide - Ansible Docker Guide - Ansible cfg Guide ## Conclusion Dynamic inventory eliminates manual host management. Use inventory plugins (`aws_ec2`, `azure_rm`, `gcp_compute`, `docker_containers`) to auto-discover infrastructure from cl... --- ## Ansible Dynamic Inventory — AWS Azure GCP VMware URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-aws-azure-gcp-vmware Description: Ansible Dynamic Inventory guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Dynamic Inventory — AWS Azure GCP VMware ## Introduction AWS Azure GCP VMware. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/product... --- ## Ansible Dynamic Inventory — AWS EC2, Azure, GCP Auto-Discovery URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-aws-ec2-azure-gcp-auto-discovery Description: Use Ansible dynamic inventory plugins to auto-discover hosts from AWS EC2, Azure, GCP, and other cloud providers. No static host files needed. # Ansible Dynamic Inventory — AWS EC2, Azure, GCP Auto-Discovery ## Introduction Static inventory files don't work in cloud environments where instances are created and destroyed constantly. Dynamic inventory plugins query your cloud provider's API in real-time, automatically discovering hosts and their metadata. This guide covers AWS EC2, Azure, GCP, and custom scripts. ## AWS EC2 Dynamic Inventory ### Setup [code example] ### Configuration [code example] ### Test It [code example] ## Azure Dynamic Inventory [code example] [code example] ## GCP Dynamic Inventory [code example] [code example] ## Enable Inventory Plugins [code example] ## Combine Static and Dynamic [code example] [code example] ## Custom Inventory Script [code example] [code example] ## Caching [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | No hosts found | Check filters, verify credentials, test with `--list` | | Authentication failed | Set env vars (`AWS_ACCESS_KEY_ID`) or check service account | | Wrong hostname used | Adjust `hostnames` or `compose.ansible_host` | | Slow inventory load | Enable caching, restrict regions/resource groups | | Plugin not found | Run `ansible-galaxy collection install`, check `enable_plugins` | | Groups not created | Verify `keyed_groups` key exists in instance metadata | ## Best Practices 1. **Use `keyed_groups` for automatic grouping** — tags become Ansible groups 2. **Filter aggressively** — only discover hosts you'... --- ## Ansible Dynamic Inventory Plugins — Write Your Own URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-plugins-write-your-own Description: Write custom Ansible dynamic inventory plugins. Complete guide to the inventory plugin API — parsing, caching, grouping, hostvars, and packaging in. ## Introduction Ansible inventory plugins pull host data from external sources — cloud APIs, CMDBs, spreadsheets, databases, or any system that knows about your infrastructure. While Ansible ships with plugins for AWS, Azure, GCP, NetBox, and others, you can write your own plugin for any data source. This guide covers the inventory plugin API from scratch, with a complete working example. ## How Inventory Plugins Work [code example] 1. User creates a YAML file that declares `plugin: my_plugin` 2. Ansible loads the plugin and calls `verify_file()` then `parse()` 3. Plugin queries the data source and populates hosts, groups, and variables 4. Ansible uses the populated inventory for playbook execution ## Inventory Plugin API Every inventory plugin is a Python class that inherits from `BaseInventoryPlugin`: [code example] ## Complete Example: CSV Inventory Plugin ### The Plugin [code example] ### The CSV File [code example] ### The Inventory Source File [code example] ### Test It [code example] ## Example: REST API Inventory Plugin [code example] ## Packaging in a Collection [code example] [code example] [code example] ## Enable Plugin in ansible.cfg [code example] ## Caching Use the `Cacheable` mixin for expensive API calls: [code example] ## Troubleshooting ### "No inventory plugin matched" - Check file extension matches `verify_file()` - Ensure plugin is in `enable_plugins` in ansible.cfg - Check `plugin:` value in YAML matches `NAME` in class ##... --- ## Ansible Dynamic Inventory Script — Custom Host Sources URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-script-custom-host-sources Description: Write custom dynamic inventory scripts and plugins for Ansible. Pull hosts from APIs, databases, CMDBs, and cloud providers with JSON output format. # Ansible Dynamic Inventory Script — Custom Host Sources ## Introduction Static inventory files don't scale when your infrastructure changes constantly. Dynamic inventory pulls host information from external sources — cloud provider APIs, CMDBs, databases, or any HTTP API. Ansible supports both inventory scripts (executable programs) and inventory plugins (Python classes). This guide covers both approaches. ## Dynamic Inventory JSON Format Every dynamic inventory must output JSON in this format: [code example] ## Simple Inventory Script (Bash) [code example] [code example] ## Python Inventory Script [code example] ## Inventory Plugin (Recommended) Inventory plugins are the modern approach — they integrate with Ansible's caching, support `compose` and `keyed_groups`, and don't require separate scripts. [code example] [code example] [code example] ## Built-in Cloud Inventory Plugins [code example] [code example] ## Combining Inventories [code example] ## Caching [code example] ## Testing Your Inventory [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Script not executing | `chmod +x script.py`; check shebang line | | Invalid JSON output | Test with `./script.py --list | python3 -m json.tool` | | Plugin not found | Add to `enable_plugins` in `ansible.cfg` | | Stale cache | Delete cache: `rm -rf /tmp/ansible-inventory-cache` | | API timeout | Increase timeout; enable caching | | Empty inventory | Check API response; verify fi... --- ## Ansible ec2_security_group Module — Manage AWS Security Groups URL: https://www.ansiblebyexample.com/articles/ansible-ec2-security-group-module-manage-aws-security-groups Description: Create and manage EC2 security group rules for network access control. Tested on real machines with clear, copy-paste examples. # Ansible ec2_security_group Module — Manage AWS Security Groups ## Introduction The `amazon.aws.ec2_security_group` module create and manage EC2 security group rules for network access control. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ec2_security_group` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — r... --- ## Ansible ec2_vpc_net Module — Manage AWS VPC Networks URL: https://www.ansiblebyexample.com/articles/ansible-ec2-vpc-net-module-manage-aws-vpc-networks Description: Create, modify, and delete Amazon VPC networks with Ansible automation. Hands-on, tested examples and best practices for Ansible ec2_vpc_net Module. # Ansible ec2_vpc_net Module — Manage AWS VPC Networks ## Introduction The `amazon.aws.ec2_vpc_net` module create, modify, and delete Amazon VPC networks with Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ec2_vpc_net` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` befor... --- ## Ansible ec2_vpc_subnet Module — Manage AWS VPC Subnets URL: https://www.ansiblebyexample.com/articles/ansible-ec2-vpc-subnet-module-manage-aws-vpc-subnets Description: Create and configure VPC subnets across availability zones with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible ec2_vpc_subnet Module — Manage AWS VPC Subnets ## Introduction The `amazon.aws.ec2_vpc_subnet` module create and configure VPC subnets across availability zones with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ec2_vpc_subnet` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--che... --- ## Ansible ecr_repository Module — Manage AWS ECR Container Repositories URL: https://www.ansiblebyexample.com/articles/ansible-ecr-repository-module-manage-aws-ecr-container-repositories Description: Create and manage Elastic Container Registry repositories with Ansible. Hands-on, tested examples and best practices for Ansible ecr_repository Module. # Ansible ecr_repository Module — Manage AWS ECR Container Repositories ## Introduction The `amazon.aws.ecr_repository` module create and manage Elastic Container Registry repositories with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ecr_repository` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — r... --- ## Ansible ecs_cluster Module — Manage AWS ECS Clusters URL: https://www.ansiblebyexample.com/articles/ansible-ecs-cluster-module-manage-aws-ecs-clusters Description: Create and manage Amazon ECS clusters for container orchestration. Hands-on, tested examples and best practices for Ansible ecs_cluster Module. # Ansible ecs_cluster Module — Manage AWS ECS Clusters ## Introduction The `amazon.aws.ecs_cluster` module create and manage Amazon ECS clusters for container orchestration. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ecs_cluster` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before app... --- ## Ansible ecs_service Module — Manage AWS ECS Services URL: https://www.ansiblebyexample.com/articles/ansible-ecs-service-module-manage-aws-ecs-services Description: Deploy and manage ECS services with load balancing and auto-scaling. Hands-on, tested examples and best practices for Ansible ecs_service Module. # Ansible ecs_service Module — Manage AWS ECS Services ## Introduction The `amazon.aws.ecs_service` module deploy and manage ECS services with load balancing and auto-scaling. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.ecs_service` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before a... --- ## Ansible eks_cluster Module — Manage AWS EKS Kubernetes Clusters URL: https://www.ansiblebyexample.com/articles/ansible-eks-cluster-module-manage-aws-eks-kubernetes-clusters Description: Create and manage Amazon EKS clusters for Kubernetes workloads. Hands-on, tested examples and best practices for Ansible eks_cluster Module. # Ansible eks_cluster Module — Manage AWS EKS Kubernetes Clusters ## Introduction The `amazon.aws.eks_cluster` module create and manage Amazon EKS clusters for Kubernetes workloads. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.eks_cluster` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` be... --- ## Ansible Elasticsearch — Deploy and Manage Search Clusters URL: https://www.ansiblebyexample.com/articles/ansible-elasticsearch-cluster-deployment Description: Deploy Elasticsearch clusters with Ansible. Configure nodes, indices, security, snapshots, ILM policies, and cluster health monitoring with complete. # Ansible Elasticsearch — Deploy and Manage Search Clusters ## Introduction Elasticsearch is the backbone of the ELK stack and one of the most widely deployed search and analytics engines. A production cluster requires careful node configuration, memory tuning, security setup, and lifecycle management — all of which Ansible automates reliably across dozens of nodes. ## Inventory Structure [code example] ## Install Elasticsearch [code example] ## Configuration Template [code example] ## Index Lifecycle Management [code example] ## Snapshot and Backup [code example] ## Health Check Playbook [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Fluent Bit Log Forwarding - Ansible Rsyslog Centralized Logging - Ansible Prometheus Grafana Integration - Ansible Redis Cache Cluster - Ansible Vault Encrypt Decrypt ## Conclusion A production Elasticsearch cluster requires coordinated configuration of master, data, and coordinating nodes with proper JVM tuning, security, and lifecycle management. Ansible makes this repeatable — from initial deployment through rolling upgrades, snapshot management, and health monitoring. --- ## Ansible Elasticsearch Cluster Deployment URL: https://www.ansiblebyexample.com/articles/ansible-elasticsearch-cluster-deployment-management Description: Deploy and manage Elasticsearch clusters with Ansible including node roles, security, index lifecycle management, and performance tuning # Ansible Elasticsearch Cluster Deployment Elasticsearch is the backbone of the ELK/Elastic Stack, handling search, logging, and analytics at scale. Deploying Elasticsearch clusters manually is error-prone — node discovery, JVM tuning, shard allocation, and security all need precise configuration. Ansible makes this manageable. ## Why Automate Elasticsearch with Ansible - **Cluster topology** is defined in inventory — add/remove nodes by editing a file - **Rolling upgrades** without cluster downtime - **Consistent JVM and OS tuning** across all nodes - **Security configuration** (TLS, users, roles) version-controlled - **Index lifecycle policies** deployed as code ## Prerequisites - Ansible 2.14+ on controller - Target nodes: 4+ GB RAM minimum (8+ GB recommended) - Dedicated disks for data nodes - Network connectivity between all cluster nodes (ports 9200, 9300) ## Cluster Architecture [code example] ## Inventory Structure [code example] ## Main Deployment Playbook [code example] ## Elasticsearch Configuration Template `templates/elasticsearch.yml.j2`: [code example] ## JVM Heap Configuration `templates/jvm.options.d/heap.options.j2`: [code example] ## Index Lifecycle Management [code example] ## Rolling Cluster Upgrade [code example] ## Snapshot and Backup [code example] ## Troubleshooting | Problem | Cause | Solution | |---------|-------|----------| | Cluster RED status | Unassigned primary shards | Check disk space, node connectivity | | OutOfMemor... --- ## Ansible elb_application_lb Module — Manage AWS Application Load Balancers URL: https://www.ansiblebyexample.com/articles/ansible-elb-application-lb-module-manage-aws-application-load-balancers Description: Create and configure ALBs with target groups and listener rules. Hands-on, tested examples and best practices for Ansible elb_application_lb Module. # Ansible elb_application_lb Module — Manage AWS Application Load Balancers ## Introduction The `amazon.aws.elb_application_lb` module create and configure ALBs with target groups and listener rules. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.elb_application_lb` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode*... --- ## Ansible ELK Stack — Deploy Elasticsearch, Logstash, and Kibana URL: https://www.ansiblebyexample.com/articles/ansible-elk-stack-elasticsearch-logstash-kibana Description: Deploy the ELK stack (Elasticsearch, Logstash, Kibana) with Ansible. Complete guide to installation, cluster configuration, index management, Filebeat. ## Introduction The ELK stack (Elasticsearch, Logstash, Kibana) — now called the Elastic Stack — is the most popular open-source solution for centralized logging and observability. Ansible automates the entire deployment: Elasticsearch cluster, Logstash pipelines, Kibana dashboards, and Filebeat agents on every server. This guide covers single-node dev setups through multi-node production clusters. ## Architecture [code example] ## Install Elasticsearch [code example] ### Elasticsearch Config Template [code example] [code example] ## Install Logstash [code example] ### Logstash Pipeline [code example] ## Install Kibana [code example] [code example] ## Deploy Filebeat Agents [code example] [code example] ## Index Lifecycle Management [code example] ## Docker-Based Deployment [code example] ## Troubleshooting ### Elasticsearch Won't Start [code example] ### Cluster Health Yellow/Red [code example] ## Related Articles - Ansible Prometheus Grafana - Ansible Docker Compose - Ansible Logrotate - Ansible Template Module ## Conclusion Ansible deploys the entire ELK stack from inventory — Elasticsearch cluster with proper discovery, Logstash pipelines with grok filters, Kibana connected to the cluster, and Filebeat agents on every server. Template all configurations from group variables so adding a node is just adding a host to inventory. For smaller setups, use Docker Compose; for production, use dedicated hosts with ILM policies for automatic index lif... --- ## Ansible Encrypt Sensitive Data — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-encrypt-sensitive-data-complete-guide Description: Protect secrets in Ansible with Vault encryption and no_log. Follow clear, copy-paste examples and real-world usage notes for Ansible Encrypt Sensitive Data. # Ansible Encrypt Sensitive Data — Complete Guide ## Introduction Protect secrets in Ansible with Vault encryption and no_log. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Protect secrets in Ansible with Vault encryption and no_log. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Engineered Living Therapeutics Biomanufacturing Automation URL: https://www.ansiblebyexample.com/articles/ansible-engineered-living-therapeutics-biomanufacturing Description: Automate biomanufacturing infrastructure for engineered living therapeutics with Ansible. Deploy bioreactor controls, GMP compliance, and cell therapy. ## Introduction Engineered living therapeutics (ELTs) — genetically modified cells programmed to treat disease — are moving from clinical trials to commercial manufacturing. Producing these therapies at scale requires GMP-compliant biomanufacturing infrastructure: bioreactor process control, environmental monitoring, chain-of-custody tracking, and regulatory documentation. Ansible automates the IT systems supporting these critical manufacturing operations. ## Biomanufacturing Infrastructure [code example] ## Bioreactor Process Control [code example] ## GMP Compliance Automation [code example] ## Chain of Custody and Traceability [code example] ## Related Articles - Ansible Structural Battery Manufacturing - Ansible Advanced Nuclear Technology - Ansible Autonomous Industrial Systems - Ansible Confidential Computing ## Conclusion Engineered living therapeutics require manufacturing infrastructure where every parameter is monitored, every action is documented, and every product is traceable to a specific patient. Ansible automates the IT systems supporting this: bioreactor process control with predictive analytics, 21 CFR Part 11 compliant electronic records, cleanroom environmental monitoring, and patient-specific chain of custody. As ELTs move from boutique clinical production to commercial scale, automated, validated infrastructure becomes the foundation for consistent, compliant manufacturing. --- ## Ansible Enterprise Windows Backup: win_robocopy & win_copy URL: https://www.ansiblebyexample.com/articles/ansible-playbook-backup-windows-win-copy-win-robocopy Description: Enterprise Windows backup with Ansible: win_robocopy, win_copy, SQL Server, system state, retention. Designed for production multi-OS environments. ## Introduction Backing up Windows systems with Ansible automates what's often a manual, error-prone process. Whether you're protecting Windows 10/11 workstations, Windows Server 2019/2022, or entire fleets, Ansible modules like `ansible.windows.win_copy`, `community.windows.win_robocopy`, and `ansible.windows.win_shell` give you repeatable, idempotent backup automation. This guide covers file-level backups, system state, database dumps, and scheduled backup tasks. ## Prerequisites [code example] ## Backup Methods Comparison [code example] ## Enterprise Backup Scenario For an enterprise backup playbook, keep Windows hosts in a dedicated inventory group and use this workflow for file shares, IIS data, registry exports, SQL Server dumps, and scheduled tasks. If the same backup policy also covers Linux hosts, pair this Windows playbook with a separate Linux file backup role or a general Ansible backup and restore guide so each operating system uses the right modules while sharing retention, verification, and destination naming rules. ## Basic File Backup with win_copy [code example] ## Folder Backup with win_robocopy `win_robocopy` is the best choice for large directory backups — it's fast, supports mirroring, and handles retries. [code example] ## Complete Backup Playbook [code example] ## Backup with Scheduled Task [code example] ## Backup SQL Server Database [code example] ## Pull Backups to Ansible Controller [code example] ## Common Mistakes [code exam... --- ## Ansible Environment Variables — Set and Use in Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-environment-variables-set-and-use-in-playbooks Description: Set, pass, and manage environment variables in Ansible tasks and playbooks. Configure PATH, proxy settings, API keys, and application environments. # Ansible Environment Variables — Set and Use in Playbooks ## Introduction Environment variables configure how programs behave — database URLs, API keys, proxy settings, PATH, and more. Ansible lets you set environment variables at the task, play, block, or role level using the `environment` keyword. This guide covers every technique for managing environment variables in your automation. ## Task-Level Environment [code example] ## Play-Level Environment Set once, applies to all tasks in the play: [code example] ## Block-Level Environment [code example] ## Using Variables for Environment [code example] ## Proxy Configuration [code example] ## Persistent Environment Variables Set permanent environment variables on the target: [code example] ## Reading Remote Environment [code example] ## Controller Environment Variables [code example] [code example] ## Environment File Pattern [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Env var not visible | `environment` only applies to that task's process | | PATH not working | Append to existing: `"{{ ansible_env.PATH }}"` | | Proxy not used | Set both `http_proxy` and `https_proxy` (lowercase) | | become resets env | Use `become_flags: '-E'` to preserve environment | | Env var has quotes | Don't double-quote: `APP_ENV: production` not `APP_ENV: "'production'"` | ## Best Practices 1. **Use Vault for secrets** — never hardcode API keys or passwords 2. **Define at play level** for co... --- ## Ansible Environment Variables Guide URL: https://www.ansiblebyexample.com/articles/ansible-environment-variables-set-and-use-env-vars-in-playbooks Description: Set environment variables in Ansible tasks, plays, and roles. Pass secrets, configure PATH, proxy settings, and application config via the environment. # Ansible Environment Variables — Set and Use env vars in Playbooks ## Introduction Ansible's `environment` keyword sets environment variables for task execution on remote hosts. This is essential for commands that need `PATH` modifications, proxy settings, API tokens, database connection strings, or any application that reads configuration from the environment. ## Setting Environment Variables ### Per Task [code example] ### Per Play [code example] ### Per Role [code example] ### From Variables [code example] ## Reading Environment Variables ### From the Controller [code example] ### From the Remote Host [code example] ## Common Use Cases ### PATH Modification [code example] ### Python Virtual Environments [code example] ### Java Applications [code example] ### Persistent Environment Variables [code example] ### Systemd Environment Files [code example] [code example] ## Proxy Configuration [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Environment not applied | `environment` only affects that task, not the session | | `lookup('env')` returns empty | Variable not set on controller; check with `echo $VAR` | | `ansible_env` missing variable | Run `gather_facts: true`; variable must be in remote shell | | Proxy not working | Set both uppercase AND lowercase variants | | PATH not found | Prepend to existing: `"/new/path:{{ ansible_env.PATH }}"` | ## Best Practices 1. **Use `environment` keyword, not `shell: export`*... --- ## Ansible eos_command Module — Run Commands on Arista EOS Devices URL: https://www.ansiblebyexample.com/articles/ansible-eos-command-module-run-commands-on-arista-eos-devices Description: Execute show and operational commands on Arista EOS switches with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible eos_command Module — Run Commands on Arista EOS Devices ## Introduction The `arista.eos.eos_command` module execute show and operational commands on Arista EOS switches with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install arista.eos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `arista.eos.eos_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `... --- ## Ansible eos_config Module — Manage Arista EOS Configuration URL: https://www.ansiblebyexample.com/articles/ansible-eos-config-module-manage-arista-eos-configuration Description: Deploy and manage configuration on Arista EOS network switches. Tested on real machines with clear, copy-paste examples. # Ansible eos_config Module — Manage Arista EOS Configuration ## Introduction The `arista.eos.eos_config` module deploy and manage configuration on Arista EOS network switches. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install arista.eos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `arista.eos.eos_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before a... --- ## Ansible Error 205: Fix playbook-extension Lint Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-205-playbook-extension Description: Fix ansible-lint Error 205 playbook-extension. Learn why playbook files should use .yml extension, not .yaml or other extensions, and how to configure. ## Introduction Error 205 (`playbook-extension`) is an ansible-lint rule that flags playbook files using incorrect file extensions. While Ansible itself accepts multiple extensions, following consistent naming conventions improves project organization and enables proper tooling integration. ## The Error When running `ansible-lint`, you may see: [code example] Or in newer versions: [code example] ## Root Cause The ansible-lint rule `playbook-extension` enforces that all playbook files use one of the standard YAML extensions: - `.yml` (preferred) - `.yaml` (acceptable) Files that trigger this error may have: - Uppercase extensions: `.YML`, `.YAML` - No extension at all: `deploy` (no `.yml`) - Non-standard extensions: `.ansible`, `.playbook` - Mixed case: `.Yml` ## The Fix ### Option 1: Rename the File (Recommended) [code example] ### Option 2: Configure ansible-lint to Accept Your Convention If your organization uses `.yaml` instead of `.yml`, both are valid. But if you want to suppress the rule entirely: **.ansible-lint:** [code example] Or to warn instead of error: [code example] ## Best Practices for File Extensions ### Standard Convention | File Type | Recommended Extension | Example | |-----------|----------------------|---------| | Playbooks | `.yml` | `deploy.yml`, `site.yml` | | Roles tasks | `.yml` | `tasks/main.yml` | | Variable files | `.yml` | `vars/main.yml` | | Inventory (YAML) | `.yml` | `inventory.yml` | | Inventory (INI) | `.ini` or no exte... --- ## Ansible Error 401: Fix latest[git] Lint Warning URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-401-latest-git Description: Fix ansible-lint Error 401 latest[git]. Learn why using HEAD or branch names in ansible.builtin.git is risky and how to pin commits, tags, or versions. ## Introduction Ansible-lint rule 401 (`latest[git]`) flags Git module tasks that use unpinned versions like `HEAD` or branch names. These create non-reproducible deployments — the same playbook run on different days may check out completely different code. This guide explains why the rule exists, shows correct patterns, and covers legitimate cases where you need to suppress it. ## The Error [code example] ## Root Cause The rule triggers when the `ansible.builtin.git` module uses values that resolve to different commits over time: | Problematic Value | Why It's Risky | |-------------------|---------------| | `version: HEAD` | Always latest commit on default branch | | `version: main` | Branch moves with every merge | | `version: develop` | Branch changes constantly | | (no version specified) | Defaults to `HEAD` | ## Problematic Code Examples [code example] ## Correct Code ### Pin to a Specific Commit Hash (Most Secure) [code example] ### Pin to a Release Tag [code example] ### Use a Variable for the Version [code example] ## Suppressing the Rule (When Intentional) Sometimes you genuinely want the latest code — for example, in development environments or CI pipelines: ### Inline Suppression [code example] ### In .ansible-lint Configuration [code example] ### Per-Environment Approach [code example] ## Complete Deployment Playbook [code example] ## Best Practices 1. **Always pin versions in production** — use tags or commit hashes 2. **Use variables ... --- ## Ansible Error 504: Fix deprecated-local-action Lint Warning URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-504-deprecated-local-action Description: Fix ansible-lint Error 504 deprecated-local-action. Replace local_action with delegate_to: localhost for clearer, modern Ansible playbooks with. ## Introduction Ansible-lint rule 504 (`deprecated-local-action`) flags the use of `local_action` in playbooks. This syntax is deprecated in favor of `delegate_to: localhost`, which is clearer, more consistent, and better supported by modern Ansible tooling. ## The Error [code example] ## Root Cause The `local_action` keyword was an early Ansible shorthand for running tasks on the controller instead of remote hosts. It has been superseded by `delegate_to: localhost` which: - Uses standard task syntax (no special keyword) - Supports all task attributes consistently - Is more readable and explicit - Works properly with `become`, `register`, and other directives ## Problematic Code [code example] ## Correct Code ### Replace with delegate_to: localhost [code example] ## Common Use Cases for delegate_to: localhost ### Health Checks Before Deployment [code example] ### API Calls from Controller [code example] ### Local File Operations [code example] ## delegate_to vs connection: local There's another way to run tasks locally — `connection: local` at the play level: [code example] **When to use which:** | Method | Use Case | |--------|----------| | `delegate_to: localhost` | One task needs to run locally in a remote play | | `hosts: localhost` + `connection: local` | Entire play targets the controller | | `local_action` | **Never** (deprecated) | ## Important Notes ### delegate_to and become When using `delegate_to: localhost`, `become` still applies but ta... --- ## Ansible Error Handling — rescue URL: https://www.ansiblebyexample.com/articles/ansible-error-handling-rescue-ignore-failed-when Description: Handle errors in Ansible playbooks with block/rescue/always, ignore_errors, failed_when, and any_errors_fatal. Build resilient automation with graceful. ## Introduction By default, Ansible stops when a task fails. Error handling lets you control that behavior — retry, ignore, rescue, or fail fast. Use `block/rescue/always` (like try/catch/finally), `ignore_errors`, `failed_when`, and `any_errors_fatal` to build resilient playbooks. ## block / rescue / always [code example] - **block** — tasks to try - **rescue** — runs only if block fails (like `catch`) - **always** — runs regardless (like `finally`) ## ignore_errors [code example] ## failed_when Custom failure conditions — override what Ansible considers a failure: [code example] ## changed_when Control when Ansible reports a task as "changed": [code example] ## any_errors_fatal Stop ALL hosts immediately when any single host fails: [code example] Without `any_errors_fatal`, Ansible removes the failed host and continues with the rest. With it, the entire play stops. ## max_fail_percentage Allow partial failure: [code example] ## Retry with until [code example] ## Practical Patterns ### Graceful Service Restart [code example] ### Pre-Flight Validation with Bail-Out [code example] ### Ignore Individual Items in a Loop [code example] ### Nested Blocks [code example] ## Summary Table | Technique | Use When | |-----------|----------| | `ignore_errors: true` | Task failure is acceptable | | `failed_when` | Custom failure condition | | `changed_when` | Custom change detection | | `block/rescue/always` | Error recovery / rollback | | `any_errors_fatal... --- ## Ansible Error Handling: rescue, always, ignore_errors, and failed_when URL: https://www.ansiblebyexample.com/articles/ansible-error-handling-rescue-always-ignore-errors-and-failed-when Description: Master Ansible error handling — use block/rescue/always, ignore_errors, failed_when, and retries to build resilient playbooks that handle failures. ## block / rescue / always Like try/catch/finally in programming: [code example] ## ignore_errors Continue playbook execution even if a task fails: [code example] ### Check if Error Occurred [code example] ## failed_when Define custom failure conditions: [code example] ## changed_when Control when a task reports "changed": [code example] ## Retries with until Retry a task until it succeeds: [code example] ## any_errors_fatal Stop the entire play if any host fails: [code example] ## max_fail_percentage Allow some hosts to fail: [code example] ## Practical Patterns ### Safe Service Restart [code example] ## Quick Reference | Keyword | Purpose | |---------|---------| | `block/rescue/always` | Try/catch/finally | | `ignore_errors: true` | Continue on failure | | `failed_when` | Custom failure condition | | `changed_when` | Custom changed condition | | `retries` + `until` + `delay` | Retry with condition | | `any_errors_fatal` | Stop play on any host failure | | `max_fail_percentage` | Tolerate N% failures | ## Related Articles - Ansible Tutorial for Beginners — Complete getting started guide - How to Install Ansible — Installation on all platforms - Ansible Training — Courses and certifications - Ansible Dry Run — Test playbooks safely - Ansible Facts — Gather system info - Ansible Vault — Encrypt secrets - Ansible Error Handling — Handle failures --- *Learn more resilient automation patterns in our 800+ tutorials on AnsibleByExample.* --- ## Ansible etcd — Deploy Distributed Key-Value Store URL: https://www.ansiblebyexample.com/articles/ansible-etcd-distributed-key-value-store Description: Deploy etcd clusters with Ansible. Static and discovery-based bootstrapping, TLS mutual authentication, snapshot backups, member management, monitoring,. ## Introduction etcd is the distributed key-value store that underpins Kubernetes — storing all cluster state, configuration, and service discovery data. Ansible automates etcd cluster deployment: static bootstrapping, TLS mutual authentication, automated backups, member management, and health monitoring. ## Deploy etcd Cluster [code example] ### Config Template [code example] ## TLS Certificates [code example] ## Automated Backups [code example] ## Health Check [code example] ## Restore from Backup [code example] ## Troubleshooting ### Database Too Large [code example] ## Related Articles - Ansible Kubernetes - Ansible Consul - Ansible OpenSSL Certificates - Ansible Cron Module ## Conclusion etcd is the backbone of Kubernetes and many distributed systems. Ansible deploys clusters with static bootstrapping, configures mutual TLS, schedules automated backups, and monitors cluster health. Template the config from inventory — the initial-cluster list is built dynamically from the `etcd_nodes` group. Use automated snapshots and tested restore procedures to ensure data durability. --- ## Ansible Event-Driven Automation with EDA Controller — Reactive Infrastructure at Scale URL: https://www.ansiblebyexample.com/articles/ansible-event-driven-automation-eda-controller-reactive-infrastructure Description: Implement event-driven automation with Ansible EDA Controller. Create rulebooks for auto-remediation, integrate with monitoring tools, and build reactive. ## Introduction Traditional automation is reactive — a human sees an alert, logs into a system, diagnoses the problem, and runs a playbook. Event-Driven Ansible (EDA) closes that loop: monitoring tools fire events, EDA evaluates rules, and playbooks execute automatically. Disk full? EDA cleans up logs. Service crashed? EDA restarts it and opens a ticket. Certificate expiring? EDA renews it before anyone notices. The shift from "human-in-the-loop" to "human-on-the-loop" is what separates mature automation from scripting. ## Architecture [code example] ## EDA Components | Component | Description | |-----------|-------------| | **Event source** | Plugin that receives events (webhook, Kafka, file watch, etc.) | | **Rulebook** | YAML file defining conditions → actions | | **Condition** | Jinja2 expression that matches events | | **Action** | What to do: run_playbook, run_job_template, debug, post_event | | **EDA Controller** | Web UI + API for managing rulebook activations | ## Installation [code example] ## Rulebook Basics ### Structure [code example] ### Running a Rulebook [code example] ## Pattern 1: Prometheus Alertmanager Integration ### Alertmanager Configuration [code example] ### EDA Rulebook for Alertmanager [code example] ## Pattern 2: Self-Healing Infrastructure ### Service Recovery Playbook [code example] ## Pattern 3: Kafka Event Stream Processing [code example] ## Pattern 4: CloudWatch Integration (AWS) [code example] ## Throttling and Dedupl... --- ## Ansible Execution Environment Example: Adding a Collection via the EE Builder URL: https://www.ansiblebyexample.com/articles/ansible-execution-environment-example-adding-a-collection-via-the-ee-builder Description: Walk through Step 2 of the AAP 2.7 EE Builder wizard: adding redhat.rhel_system_roles from Automation Hub to a new execution environment, no YAML required. The Execution Environment (EE) Builder in AAP 2.7's Automation Portal is a 4-step visual wizard for assembling custom EEs without hand-writing an `execution-environment.yml`. Step 2, Configuration, is where you attach collections to the base image you picked in Step 1. This example walks through adding `redhat.rhel_system_roles` v1.20.5 from Private Automation Hub. Once the EE Builder publishes and builds your image, you reference it in a playbook like any other EE: [code example] ## Walkthrough: Step 2 of the EE Builder 1. **Start from Step 1.** Choose a Red Hat-provided base image — for new builds, pick the recommended **Red Hat Ansible Minimal EE (Ansible Core 2.18 on RHEL 9)**. A stable-channel variant of 2.18, plain Ansible Core 2.16 on RHEL 9, its stable-channel variant, or a fully custom base image are also selectable if you have compatibility constraints. 2. **Move to Step 2: Configuration.** The collections picker searches two sources: **Private Automation Hub** (`rh-certified` content) and **GitHub**. Type `rhel_system_roles` in the search box, select the `redhat.rhel_system_roles` result, and pin the version to **1.20.5**. 3. **Add more collections if needed.** Repeat the search/add action for every additional collection your playbooks require — each one is appended to the EE's dependency list shown on the same screen. 4. **Open Advanced Configuration (optional).** This is where you add extra Python requirements (e.g., a package your custom modules import), ext... --- ## Ansible Execution Environment Example: Final Review Before Building an EE URL: https://www.ansiblebyexample.com/articles/ansible-execution-environment-example-final-review-before-building-an-ee Description: Walk through Step 4: Review in the AAP 2.7 Execution Environment Builder wizard, and use a matching ansible-builder YAML example before you kick off a build. AAP 2.7's Automation Portal ships a 4-step wizard for building Execution Environments (EEs) without writing YAML by hand. Step 4, Review, is your last checkpoint before the build actually runs — it lays out the base image, collections, and destination settings you chose in Steps 1-3 so you can catch mistakes before committing compute time to a build. Here's what that review maps to under the hood, and a matching `execution-environment.yml` you'd get if you built the same EE by hand. [code example] ## What Step 4 actually shows you When you reach Review, the wizard renders a read-only summary of the three prior steps so you can confirm everything before triggering the build: - **Base image** — from Step 1, e.g. Red Hat Ansible Minimal EE with Ansible Core 2.18 on RHEL 9 (the recommended default), its 2.18 stable-channel counterpart, the Ansible Core 2.16 on RHEL 9 image, its 2.16 stable-channel variant, or a fully custom base image you supplied. - **Collections** — from Step 2, each collection you added through the picker (which searches both Private Automation Hub for `rh-certified` content and GitHub), listed with its pinned version — in this example, `redhat.rhel_system_roles` at `1.20.5`. - **Advanced Configuration** — any extra Python requirements, system packages, or custom build steps you attached in Step 2, shown so you notice a stray dependency before the build consumes registry pull time. - **Destination** — from Step 3, the EE definition's name, description, tag... --- ## Ansible Execution Environment Example: Publishing an EE Definition to GitHub URL: https://www.ansiblebyexample.com/articles/ansible-execution-environment-example-publishing-an-ee-definition-to-github Description: Step-by-step example of AAP 2.7's EE Builder wizard Step 3, Destination and Build, publishing an execution environment definition to a GitHub repository. Red Hat Ansible Automation Platform 2.7's Automation Portal ships a visual Execution Environment (EE) Builder — a 4-step wizard that produces an EE definition without hand-editing YAML. This example focuses on Step 3, Destination and Build, where you name the definition and push it to a GitHub repository. Shown at Red Hat Tech Day Netherlands 2026 in Bunnik, this step is where the wizard's output leaves the portal and becomes a version-controlled artifact. The generated `execution-environment.yml` that the wizard publishes looks like this: [code example] And the portal metadata captured in wizard Step 3 (Destination and Build), summarized as a reference: [code example] ## What this does and why Step 1 of the wizard picks the base image — here, the recommended Red Hat Ansible Minimal EE (Ansible Core 2.18 on RHEL 9). Step 2, Configuration, adds collections via a picker that searches both Private Automation Hub (rh-certified content) and GitHub; the example above adds `redhat.rhel_system_roles` at version `1.20.5`, matching what was demonstrated live. Advanced Configuration in that same step is where you'd layer in extra Python requirements, system packages, or custom build steps if the defaults don't cover your dependencies. Step 3, Destination and Build, is the handoff point. You give the EE definition a name, a description, and tags — these are the fields the portal's EE catalog later displays and lets you search on, alongside owner and star/edit/delete actions. You t... --- ## Ansible Execution Environment Example: Selecting a Base Image in AAP 2.7 URL: https://www.ansiblebyexample.com/articles/ansible-execution-environment-example-selecting-a-base-image-in-aap-2-7 Description: Walk through Step 1 of the AAP 2.7 Execution Environment Builder wizard and see the base image choice reflected in the generated execution-environment.yml. Ansible Automation Platform 2.7 ships a visual Execution Environment (EE) Builder in Automation Portal — a four-step wizard that builds container-based EEs without hand-writing YAML. Step 1, Base Image, is where every EE starts: pick the Red Hat-provided image your automation content will run on. Here's what that choice produces under the hood. [code example] ## What this does The wizard's Step 1 screen lists five base image choices, each mapping to a Red Hat container image reference: - **Red Hat Ansible Minimal EE — Ansible Core 2.18 on RHEL 9** (recommended, shown pre-selected) - A stable-channel variant of the Ansible Core 2.18 image - **Red Hat Ansible Minimal EE — Ansible Core 2.16 on RHEL 9** - A stable-channel variant of the Ansible Core 2.16 image - A fully custom base image, where you supply your own registry reference Selecting one of the Red Hat-provided options simply pins `images.base_image.name` in the EE definition that the portal maintains for you — nothing else in the definition changes yet. The empty `dependencies` and `additional_build_steps` blocks are placeholders the wizard fills in during Step 2 (Configuration), when you search Private Automation Hub or GitHub for collections to add — for example `redhat.rhel_system_roles` at version `1.20.5` — and optionally add extra Python packages, system packages, or custom build steps via Advanced Configuration. Choosing the minimal RHEL 9 / Ansible Core 2.18 image over the 2.16 line matters because content... --- ## Ansible Execution Environments — Build URL: https://www.ansiblebyexample.com/articles/build-and-run-an-ansible-execution-environment-ansible-builder-and-ansible-runner-tools Description: Build custom Ansible Execution Environments with ansible-builder. Add collections, Python packages, and system deps. Run with ansible-runner. ## How to build and Run an Ansible Execution Environment? Using an Ansible Execution Environment is the latest technology to maintain up-to-date Python dependency of the Ansible collections without interfering with your Linux system. It's the evolution of Python Virtual Environment. This initial configuration sometimes is a roadblock for some Ansible users. ## Ansible Execution Environment - `ansible-builder` - `ansible-runner` Let's talk about the Ansible Execution Environment. The Ansible Execution Environment is a container image that can be utilized as Ansible control nodes. It's the latest technology developed by Red Hat to simplify the automation process. The main advantage is a common environment for Development and Production images using container technology creating portable automation runtimes. This technology superseded manual Python Virtual Environments, Ansible module dependencies, and bubblewrap. Experienced users are probably familiar with a lot of challenges managing custom Python Virtual Environments and Ansible module dependencies. Enterprise users of Ansible Automation Platform were familiar limited to executing jobs under bubblewrap in order to isolate processes The creation is performed by the Ansible Builder tool. Ansible Builder produces a directory that acts as the build context for the container image build, containing the `Containerfile`, along with any other files that need to be added to the image. The execution is performed by the Ansible Runn... --- ## Ansible Execution Environments vs virtualenv vs Docker — Isolation Compared URL: https://www.ansiblebyexample.com/articles/ansible-execution-environments-vs-virtualenv-vs-docker Description: Compare Ansible Execution Environments, Python virtualenv, and Docker for isolation. Learn when to use each approach for consistent, reproducible. ## Introduction Running Ansible consistently across teams, CI/CD pipelines, and production requires isolation. Three approaches exist: Python virtualenvs, Docker containers, and Ansible Execution Environments (EE). Each solves different problems at different scales. This guide compares all three with practical setup examples. ## Quick Comparison | Feature | virtualenv | Docker | Execution Environment | |---------|-----------|--------|----------------------| | Isolation level | Python packages | Full OS + packages | Full OS + Python + collections | | System packages | ❌ Host only | ✅ Custom OS packages | ✅ Custom OS packages | | Ansible collections | Manual install | Manual install | ✅ Built-in, versioned | | Build tool | `python -m venv` | `Dockerfile` | `ansible-builder` | | Runtime | `source bin/activate` | `docker run` | `ansible-navigator` or AAP | | CI/CD integration | ⚠️ Fragile | ✅ Standard | ✅ Standard | | AAP/AWX compatible | ❌ No | ❌ Not directly | ✅ Native | | Team sharing | `requirements.txt` | Docker Hub / registry | Registry (Quay, GHCR) | ## virtualenv — Quick Python Isolation [code example] [code example] ### When virtualenv works [code example] ## Docker — Full OS Isolation [code example] [code example] ### CI/CD with Docker [code example] ## Execution Environments — Ansible-Native Containers [code example] [code example] [code example] ### ansible-navigator [code example] ### AAP / AWX Integration [code example] ## Decision Guide [code... --- ## Ansible Execution Strategy — Linear Free and Debug URL: https://www.ansiblebyexample.com/articles/ansible-execution-strategy-linear-free-and-debug Description: Ansible Execution Strategy guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Execution Strategy — Linear Free and Debug ## Introduction Linear Free and Debug. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Execution Strategy requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible expect Module — Automate Interactive Commands URL: https://www.ansiblebyexample.com/articles/ansible-expect-module-automate-interactive-commands Description: Ansible expect Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible expect Module — Automate Interactive Commands ## Introduction Automate Interactive Commands. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible expect Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible Extra Variables — --extra-vars URL: https://www.ansiblebyexample.com/articles/ansible-extra-vars-pass-variables-command-line Description: Use Ansible extra-vars to pass variables from the command line. Override defaults, use JSON, variable files, and dynamic values in playbooks. ## Introduction Extra variables (`--extra-vars` or `-e`) pass variables to Ansible from the command line. They have the **highest precedence** — overriding all other variable definitions including role defaults, inventory vars, and play vars. Perfect for one-off runs, CI/CD pipelines, and environment-specific deployments. ## Basic Usage [code example] ## Variable Formats ### Key=Value (Simple) [code example] ### JSON Format [code example] ### YAML Format [code example] ### From File (@) [code example] vars/production.yml: [code example] vars/production.json: [code example] ## Variable Precedence Extra vars have the **highest precedence** (position 22 of 22): [code example] This means `-e` **always wins**: [code example] [code example] ## Practical Patterns ### CI/CD Pipeline [code example] ### Environment Selection [code example] ### Target Specific Host [code example] [code example] ### Dynamic Values [code example] ### Boolean and Numeric Values [code example] [code example] ### Lists and Dictionaries [code example] ## Require Extra Variables [code example] ## Multiple -e Flags Later `-e` flags override earlier ones: [code example] ## With Ansible Ad-Hoc [code example] ## Security Considerations [code example] ## Troubleshooting ### Variable Not Being Used [code example] ### JSON Parse Error [code example] ## Related Articles - Ansible Variables Guide - Ansible Vault Guide - Ansible Playbook Guide - Ansible set_fact Module ... --- ## Ansible Facts — Gather System Info URL: https://www.ansiblebyexample.com/articles/ansible-facts-gather-system-information-guide Description: Collect system info with Ansible facts: OS, IP, memory, disk, and interfaces. Setup module, custom facts, fact caching, and facts in conditionals. ## Introduction Ansible facts are system properties collected automatically from managed hosts — OS name, IP addresses, CPU count, memory, disk space, network interfaces, and more. They're available as variables in your playbooks, letting you write conditional logic, generate templates, and make decisions based on actual system state. ## How Facts Work By default, Ansible runs the `setup` module at the start of every play to collect facts: [code example] ## Common Facts Reference | Fact | Example Value | Description | |------|--------------|-------------| | `ansible_hostname` | `web-01` | Short hostname | | `ansible_fqdn` | `web-01.example.com` | Fully qualified domain name | | `ansible_distribution` | `Ubuntu` | OS distribution | | `ansible_distribution_version` | `24.04` | OS version | | `ansible_distribution_major_version` | `24` | Major version | | `ansible_os_family` | `Debian` | OS family (Debian, RedHat, etc.) | | `ansible_kernel` | `6.5.0-44-generic` | Kernel version | | `ansible_architecture` | `x86_64` | CPU architecture | | `ansible_default_ipv4.address` | `10.0.0.5` | Primary IPv4 address | | `ansible_default_ipv4.interface` | `eth0` | Primary network interface | | `ansible_all_ipv4_addresses` | `["10.0.0.5", "172.17.0.1"]` | All IPv4 addresses | | `ansible_processor_vcpus` | `4` | CPU core count | | `ansible_memtotal_mb` | `8192` | Total RAM in MB | | `ansible_memfree_mb` | `4096` | Free RAM in MB | | `ansible_swaptotal_mb` | `2048` | Total swap in MB | | `... --- ## Ansible Facts: Gather and Use System Information URL: https://www.ansiblebyexample.com/articles/ansible-facts-gather-and-use-system-information Description: Understand Ansible facts: auto-gathered system info like IP, OS, memory, and disk. Use setup module, custom facts, and fact caching in playbooks. ## What Are Ansible Facts? Facts are system information automatically gathered from remote hosts at the start of each play. They include: - Operating system and version - IP addresses and network interfaces - CPU count and architecture - Memory and disk space - Hostname and domain ## Gathering Facts Facts are gathered automatically. View all facts: [code example] ## Using Facts in Playbooks ### Basic Usage [code example] ### Conditional Logic with Facts [code example] ### Network Facts [code example] ### Hardware Facts [code example] ## Common Facts Reference | Fact | Example Value | |------|---------------| | `ansible_facts['os_family']` | Debian, RedHat, Suse | | `ansible_facts['distribution']` | Ubuntu, CentOS, Fedora | | `ansible_facts['distribution_version']` | 24.04, 9.3 | | `ansible_facts['kernel']` | 6.5.0-44-generic | | `ansible_facts['architecture']` | x86_64, aarch64 | | `ansible_facts['memtotal_mb']` | 7821 | | `ansible_facts['processor_vcpus']` | 4 | | `ansible_facts['default_ipv4']['address']` | 192.168.1.10 | | `ansible_facts['hostname']` | web1 | | `ansible_facts['fqdn']` | web1.example.com | | `ansible_facts['python_version']` | 3.12.3 | ## Disable Fact Gathering If you don't need facts (faster execution): [code example] ## Custom Facts Create custom facts on remote hosts: [code example] [code example] Access in playbooks: [code example] ## Fact Caching Cache facts to avoid re-gathering on every run: [code example] ## set_fact: Cr... --- ## Ansible fail Module — Abort Playbooks with Custom Messages URL: https://www.ansiblebyexample.com/articles/ansible-fail-module-abort-playbooks-with-custom-messages Description: Use ansible.builtin.fail to abort playbook execution with custom error messages. Validate preconditions, enforce requirements, and implement guardrails. # Ansible fail Module — Abort Playbooks with Custom Messages ## Introduction `ansible.builtin.fail` intentionally stops playbook execution with a custom error message. Use it to enforce preconditions, validate inputs, and prevent playbooks from running in unsafe conditions. It's the "abort" button for Ansible — a clear way to say "something is wrong, stop here." ## Basic Usage [code example] ## Input Validation [code example] ## Precondition Checks [code example] ## Production Guardrails [code example] ## fail vs assert [code example] | Feature | `fail` | `assert` | |---------|--------|----------| | Multiple conditions | Needs multiple tasks | Single task with list | | Custom per-condition message | ✅ Each task has its own | One message for all | | Readability | Better for complex messages | Better for checklists | | Success message | ❌ | ✅ `success_msg` | ## In block/rescue [code example] ## Common Patterns ### Cluster Quorum Check [code example] ### Incompatible Versions [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Fail runs when it shouldn't | Check `when` condition logic (and/or/not) | | Want to fail but continue other hosts | Use `ignore_errors` on the fail task (unusual) | | Need to fail ALL hosts at once | Use `any_errors_fatal: true` on the play | | Multi-line message not formatting | Use `|` block scalar in YAML for multi-line `msg` | ## Best Practices 1. **Validate inputs early** — fail at the start, not after... --- ## Ansible Fail2Ban — Automate Intrusion Prevention and Brute Force Protection URL: https://www.ansiblebyexample.com/articles/ansible-fail2ban-intrusion-prevention-brute-force Description: Deploy Fail2Ban with Ansible. Protect SSH, Nginx, Apache, and custom services from brute force attacks. Jail configuration, custom filters, whitelists,. ## Introduction Fail2Ban monitors log files for authentication failures and automatically bans offending IP addresses using firewall rules. Ansible automates the full setup — install Fail2Ban, configure jails for SSH, web servers, mail, and custom applications, manage whitelists, set up email alerts, and deploy custom filters across your fleet. ## Install and Configure [code example] ### jail.local Template [code example] ## Custom Filters [code example] ## Progressive Banning [code example] ## Monitoring [code example] ## Unban IPs [code example] ## Troubleshooting ### Check Filter Regex [code example] ### Fail2Ban Not Starting [code example] ## Related Articles - Ansible Firewall Module - Ansible iptables Module - Ansible SSH Key Management - Ansible Compliance Guide ## Conclusion Ansible deploys Fail2Ban across your fleet with group-specific jails — SSH everywhere, Nginx jails on web servers, Postfix jails on mail servers. Use custom filters for application-specific log patterns, the recidive jail for repeat offenders, and whitelists for trusted networks. Template everything from variables so security policy is code. --- ## Ansible Failed to Connect to Host — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-failed-to-connect-to-host-fix-and-solutions Description: Troubleshoot connection failures from SSH config, keys, and host verification. With clear, copy-paste, step-by-step examples. # Ansible Failed to Connect to Host — Fix and Solutions ## Introduction Troubleshoot connection failures from SSH config, keys, and host verification. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Troubleshoot connection failures from SSH config, keys, and host verification. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible failed_when — Custom Failure URL: https://www.ansiblebyexample.com/articles/ansible-failed-when-custom-failure-conditions Description: Define custom failure conditions with failed_when in Ansible. Control task failure by return code, output content, registered variables, and complex. # Ansible failed_when — Custom Failure Conditions ## Introduction Ansible decides task success or failure based on module return codes. But real-world commands don't always follow conventions — `grep` returns 1 for "not found" (not an error), APIs return 200 with error payloads, and scripts use custom exit codes. `failed_when` lets you define exactly what constitutes a failure. ## Basic Usage [code example] ## Never Fail [code example] ## Fail on Output Content [code example] ## Multiple Conditions [code example] ## Complex Expressions [code example] ## With Loops [code example] ## failed_when + changed_when Together [code example] ## Practical Examples ### API Error Handling [code example] ### Package Version Check [code example] ### Cluster Quorum Check [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | `failed_when` expression error | Wrap complex expressions in quotes or use `>` block scalar | | Task succeeds when it shouldn't | Check condition logic — `and` vs `or` in multi-conditions | | Variable undefined in expression | Ensure `register` is on the same task | | Can't compare versions | Use `is version('1.0', '>=')` Jinja2 test | | Integer comparison fails | Cast with `| int`: `result.stdout | int > 90` | ## Best Practices 1. **Use `failed_when` over `ignore_errors`** — precise failure control is better than ignoring all errors 2. **Always `register` the result** — you need the output to make failure decisions 3. **... --- ## Ansible failed_when & changed_when URL: https://www.ansiblebyexample.com/articles/ansible-changed-when-failed-when-task-status Description: ansible failed_when controls when a task reports failure, letting you handle expected non-zero return codes. Pairs with changed_when. ## Introduction `changed_when` is an Ansible task directive that overrides the default `changed` status, letting you decide — based on a condition you write — whether a task counts as a change. Paired with `failed_when`, it lets you control when a task reports `changed` or `failed` status. By default, Ansible relies on module return codes — but shell commands, scripts, and some modules don't report status accurately. These directives make your playbooks idempotent and your reporting meaningful. ## The Problem [code example] ## changed_when Controls when a task reports `changed: true`. [code example] ## failed_when Controls when a task reports `failed: true`. [code example] ## Combined Patterns [code example] ## Real-World Examples [code example] ## Common Mistakes [code example] ## Best Practices [code example] ## Related Articles - Ansible Error Handling - Ansible Handlers - Ansible handlers vs post_tasks - Ansible Troubleshooting - Ansible Playbook Best Practices ## Conclusion `changed_when` and `failed_when` are essential for making command/shell tasks behave like proper Ansible modules. Use `changed_when: false` on every read-only command. Use output-based `changed_when` to make shell scripts report changes accurately. Use `failed_when` to handle expected non-zero return codes. The goal: every task in `--check` mode and every play recap should reflect reality — not module defaults. --- ## Ansible fetch — Copy from Windows URL: https://www.ansiblebyexample.com/articles/copy-files-from-windows-remote-hosts-ansible-module-fetch Description: Copy files seamlessly from Windows remote hosts using Ansible ansible.builtin.fetch module. Effortlessly fetch example.txt to a local directory. ## How to Copy files from Windows remote hosts with Ansible? ## Ansible Copy files from Windows remote hosts - ansible.builtin.fetch - Copy files from remote nodes Today we're talking about the Ansible module `fetch`. The full name is `ansible.builtin.fetch` which means is part of the collection of modules "builtin" with ansible and shipped with it. This module is pretty stable and out for years. The purpose is to copy files from remote locations. Please note that the opposite is done by Ansible copy module for Linux and Ansible win_copy module for Windows. ## Parameters - `dest` path - the local path - `src` string - Remote file path - `fail_on_missing` boolean - `yes` / `no` - `validate_checksum` boolean - `yes` / `no` - `flat` boolean - `no` / `yes` The parameter list is pretty wide but I'll summarize the most useful. The only required parameters are "dest" which specifies a directory to save the file into and the "src" specifies the source files in the remote hosts. It must be a file, not a directory. The "fail_on_missing" boolean is set to true so the task is going to fail if the file doesn't exist. The file is going to be transferred and validated in the source and the destination with a checksum. If we don't want this behavior we could override with the "validate_checksum" option. The "flat" option allows you to override the default behavior of appending hostname/path/to/file to the destination. ## Playbook Copy files from Windows remote hosts with Ansible Pla... --- ## Ansible fetch — Download Remote Files URL: https://www.ansiblebyexample.com/articles/ansible-fetch-module-download-files-from-remote-hosts Description: Use the Ansible fetch module to download files from remote hosts to your control node. Pull logs, configs, backups, and reports with practical examples. ## The ansible.builtin.fetch Module The `fetch` module copies files **from remote hosts to the control node** — the reverse of `copy`. It saves each host's file in a separate directory to avoid overwriting. ## Basic Usage [code example] Result on control node: [code example] ## Flatten the Directory Structure By default, fetch preserves the full remote path. Use `flat: true` to save directly: [code example] Result: [code example] ## Practical Examples ### Collect Logs for Analysis [code example] ### Backup Configuration Files [code example] ### Collect SSL Certificates [code example] ### Fetch and Compare [code example] ## fetch vs copy | Module | Direction | Use case | |--------|-----------|----------| | `copy` | Control → Remote | Push files to servers | | `fetch` | Remote → Control | Pull files from servers | | `synchronize` | Both (rsync) | Large file sync | [code example] ## Parameters | Parameter | Description | Default | |-----------|-------------|---------| | `src` | Remote file path (required) | — | | `dest` | Local directory (required) | — | | `flat` | Don't create host/path subdirs | `false` | | `fail_on_missing` | Fail if remote file missing | `true` | | `validate_checksum` | Verify transfer integrity | `true` | ## Limitations - **Files only** — cannot fetch directories (use `synchronize` or archive first) - **No wildcards** — specify exact file path ### Workaround: Fetch a Directory [code example] --- *Explore 800+ Ansible tutorials on... --- ## Ansible fetch Module — Remote Files URL: https://www.ansiblebyexample.com/articles/ansible-fetch-module-download-files Description: Use the Ansible fetch module to download files from remote hosts to the controller. Collect logs, configs, and backups from your infrastructure. ## Introduction `ansible.builtin.fetch` downloads files from remote hosts to the Ansible controller. It's the reverse of `copy` — use it to collect logs, configuration files, backups, certificates, and diagnostics from your infrastructure. ## Basic Usage [code example] Default behavior creates a directory tree: [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | File path on remote host | | `dest` | (required) | Destination directory on controller | | `flat` | `false` | Remove host/path directory structure | | `validate_checksum` | `true` | Verify file integrity after fetch | | `fail_on_missing` | `true` | Fail if source file doesn't exist | ## Flat Mode [code example] ## Practical Examples ### Collect Logs [code example] ### Collect Configuration for Audit [code example] ### Backup Before Changes [code example] ### Collect SSL Certificates [code example] ### Generate and Fetch Reports [code example] ### Fetch Database Dump [code example] ## fetch vs Other Download Methods | Method | Use Case | |--------|----------| | `fetch` | Single files from remote to controller | | `synchronize` (mode=pull) | Directories, large transfers | | `slurp` | Small files (returns base64 content) | | `command: scp` | When fetch doesn't work | [code example] ## Limitations - **Single files only** — use `synchronize` for directories - **No glob patterns** — use `find` + `loop` for multiple files - ... --- ## Ansible fetch Module — Retrieve Files URL: https://www.ansiblebyexample.com/articles/copy-files-from-remote-hosts-ansible-module-fetch Description: Download files from remote hosts to local machine with ansible.builtin.fetch. Collect logs, configs, and backups with flat, dest, and validate options. ## Introduction The `ansible.builtin.fetch` module copies files **from remote hosts to the Ansible control node** — the reverse of the `copy` module. It's essential for collecting logs, configuration files, certificates, database dumps, and any file you need to retrieve from managed hosts. ## Module Reference **Full name:** `ansible.builtin.fetch` **Collection:** `ansible.builtin` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `src` | string | Yes | — | Remote file path to fetch (must be a file, not directory) | | `dest` | path | Yes | — | Local directory to save fetched files | | `flat` | bool | No | `false` | Save directly to `dest` without hostname subdirectory | | `fail_on_missing` | bool | No | `true` | Fail if remote file doesn't exist | | `validate_checksum` | bool | No | `true` | Verify file integrity after transfer | ### Default Directory Structure Without `flat: true`, fetch creates a directory structure: [code example] This prevents filename collisions when fetching the same file from multiple hosts. ## Basic Playbook [code example] Result: [code example] ## Using flat Mode When fetching a unique file (or from a single host), use `flat: true` to save directly: [code example] Result: `./backups/nginx-web01.conf` **Important:** With `flat: true` and multiple hosts, you must include `{{ inventory_hostname }}` in `dest` to avoid overwriting files. ## Practical Use Cases ... --- ## Ansible file Lookup Plugin — Read Files into Variables URL: https://www.ansiblebyexample.com/articles/read-a-file-into-a-variable-on-host-ansible-lookup-plugin-file Description: Use the Ansible file lookup plugin to read file contents into variables on the controller. Load configs, certificates, templates, and secrets into your. ## Introduction The `ansible.builtin.file` lookup plugin reads the contents of a file from the Ansible controller (the machine running `ansible-playbook`) and returns it as a string. This is useful for loading configuration snippets, certificates, SSH keys, or any file content into variables without copying the file to remote hosts first. This article covers basic usage, common patterns, error handling, and the difference between the `file` lookup and the `slurp` module. ## How It Works The `file` lookup runs **on the controller**, not on remote hosts. It reads the file during playbook parsing (for `vars:`) or task execution (for `set_fact`/`debug`) and returns the content as a string. [code example] ## Basic Usage ### Read a File into a Variable [code example] ### Read with Absolute Path [code example] ### Read Relative to Playbook File lookup searches relative to the playbook directory, then the `files/` directory: [code example] [code example] ## Common Use Cases ### 1. Deploy SSH Authorized Keys [code example] ### 2. Load SSL Certificates [code example] ### 3. Load Configuration Snippets [code example] ### 4. Read Multiple Files [code example] ### 5. Load JSON or YAML Data [code example] [code example] ### 6. Inject File Content into Templates [code example] ### 7. Set Facts from File Content [code example] ## Error Handling ### File Not Found By default, a missing file causes a fatal error: [code example] ### Handle Missing Files Gracefu... --- ## Ansible file Module — Delete Files URL: https://www.ansiblebyexample.com/articles/delete-file-or-directory-ansible-module-file Description: Delete files, directories, and symlinks with Ansible file module state: absent. Complete guide with conditional deletion, batch cleanup, safe patterns,. ## Introduction Deleting files and directories is one of the most common operations in system automation — cleaning up temp files, removing old deployments, deleting stale configs, or purging log files. The `ansible.builtin.file` module with `state: absent` handles all of these, with Ansible's built-in idempotency ensuring safe repeated execution. For Windows targets, use `ansible.windows.win_file` instead. ## Basic Usage ### Delete a File [code example] If the file doesn't exist, the task succeeds with `changed: false` — this is idempotent by design. ### Delete a Directory (and All Contents) [code example] This recursively removes the directory and all its contents — equivalent to `rm -rf`. ### Delete a Symbolic Link [code example] This removes the symlink itself, not the target it points to. ## Module Parameters for Deletion | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | Path to the file or directory to delete | | `state` | string | Yes | Must be `absent` for deletion | That's it — deletion only needs `path` and `state: absent`. No `owner`, `mode`, or other attributes apply. ## Practical Examples ### Conditional Deletion Delete only if a file exists and meets certain criteria: [code example] ### Delete Multiple Files [code example] ### Clean Up Old Deployments Keep the last 3 releases and delete the rest: [code example] ### Delete Files Matching a Pattern Use `find` module to lo... --- ## Ansible file Module — Permissions URL: https://www.ansiblebyexample.com/articles/change-file-permission-ansible-module-file Description: Change file and directory permissions with Ansible file module. Complete guide to chmod, chown, chgrp, symbolic modes, recursive permissions, SELinux. ## Introduction Managing file permissions, ownership, and security contexts is fundamental to Linux system automation. The `ansible.builtin.file` module handles everything from simple `chmod`/`chown` operations to SELinux contexts and extended ACLs — all idempotently. For Windows, use `ansible.windows.win_file` and `ansible.windows.win_acl`. ## Module Parameters for Permissions | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | File or directory path | | `mode` | string | No | Permissions — octal (`'0644'`) or symbolic (`'u=rw,g=r,o=r'`) | | `owner` | string | No | User that owns the file | | `group` | string | No | Group that owns the file | | `state` | string | No | `file`, `directory`, `link`, `hard`, `touch`, `absent` | | `recurse` | bool | No | Apply recursively to directory contents | | `setype` | string | No | SELinux type context | | `seuser` | string | No | SELinux user context | | `selevel` | string | No | SELinux level/range | **Important:** Always quote octal modes as strings (`'0644'`, not `0644`). Without quotes, YAML interprets `0644` as the integer 420. ## Basic Examples ### Set File Permissions [code example] ### Set Directory Permissions [code example] ### Change Ownership Only [code example] ## Permission Formats ### Octal Notation [code example] ### Symbolic Notation [code example] ## Practical Examples ### Secure SSH Keys [code example] ### Web Server Document Root [c... --- ## Ansible File Module Demo: Create Symlinks Easily URL: https://www.ansiblebyexample.com/articles/create-a-symlink-ansible-module-file Description: Discover how to create symlinks with Ansible's file module in this easy-to-follow Playbook. Master Ansible automation with practical examples. How to create a symbolic link with Ansible? ## Ansible create a symbolic link > `ansible.builtin.file` Manage files and file properties Today we're talking about the Ansible module `file`. The full name is `ansible.builtin.file`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties. For a hardlink use see the following parameters of Ansible file module. For Windows targets, use the `ansible.windows.win_file` module instead. ## Parameters - `src` string - symlink path - `dest` string - destination file path - `state` string - file/absent/symbolic link/hard/link/touch - `mode`/`owner`/`group` - permission - `setype`/`seuser`/`selevel` - SELinux This module has some parameters to perform any tasks. The two required fields are "src" and "dest" which specify the filesystem paths of the link and the target file. The state defines the type of object we are modifying, the default is "file" but for our use case, we need the "link" option. Let me highlight also the permission and SELinux parameters. ## Playbook Let's jump into a real-life playbook on how to create a symbolic link with Ansible. ### code - create_symlink.yml [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know... --- ## Ansible File Module: Manage Files, Directories, Symlinks URL: https://www.ansiblebyexample.com/articles/ansible-file-module-manage-files-directories-links Description: Learn the Ansible file module (ansible.builtin.file): create directories, set permissions and ownership, manage symlinks, and delete files. ## Introduction The **Ansible file module** (`ansible.builtin.file`) manages file system objects — create directories, set ownership and permissions, create symlinks, and remove files. It doesn't write file content (use `copy`, `template`, or `lineinfile` for that). ## Create a Directory [code example] ## Set File Permissions [code example] ## Create Symlinks [code example] ## Remove Files and Directories [code example] ## Create Empty File [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `path` / `dest` | File/directory path (required) | | `state` | `file`, `directory`, `link`, `hard`, `touch`, `absent` | | `src` | Source for symlinks | | `owner` | File owner | | `group` | File group | | `mode` | Permissions (e.g., `"0755"`, `"u+rwx,g+rx,o+rx"`) | | `recurse` | Apply owner/group/mode recursively (directories only) | | `force` | Force symlink creation even if dest exists | | `follow` | Follow symlinks (default: true for file, false for link) | | `modification_time` | Set mtime (`preserve`, `now`, or timestamp) | | `access_time` | Set atime (`preserve`, `now`, or timestamp) | | `selevel`, `setype`, `seuser` | SELinux context | ## State Values | State | Description | |-------|-------------| | `file` | Modify existing file (fails if doesn't exist) | | `directory` | Create directory (and parents) | | `link` | Create symbolic link | | `hard` | Create hard link | | `touch` | Create empty file or update timestamp | | `absent` | Re... --- ## Ansible File Permission Denied on Copy — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-file-permission-denied-on-copy-fix-and-solutions Description: Fix copy module permission errors from ownership, SELinux, and umask. Hands-on, tested examples and best practices for Ansible File Permission Denied on Copy. # Ansible File Permission Denied on Copy — Fix and Solutions ## Introduction Fix copy module permission errors from ownership, SELinux, and umask. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix copy module permission errors from ownership, SELinux, and umask. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Filter Plugins — Transform Data in Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-filter-plugins-transform-data Description: Master Ansible Jinja2 filters to transform data, manipulate strings, handle defaults, parse JSON/YAML, do math, and work with lists and dictionaries. ## Introduction Ansible filters transform data within `{{ }}` expressions — set defaults, convert types, manipulate strings, filter lists, parse JSON, and more. They're Jinja2 filters extended with Ansible-specific additions. ## Default Values [code example] ## Type Conversion [code example] ## String Filters [code example] ## List Filters [code example] ## Dictionary Filters [code example] ## Path Filters [code example] ## IP Address Filters [code example] ## Date/Time Filters [code example] ## Practical Patterns ### Dynamic Configuration [code example] ### Conditional Lists [code example] ### Parse Command Output [code example] ### Transform Inventory Data [code example] ## Troubleshooting ### Filter Not Found Install required collections: [code example] ### Undefined Variable in Filter Chain Use `default()` before other filters: [code example] ## Related Articles - Ansible Variables Guide - Ansible Jinja2 Templates - Ansible Lookup Plugins - Ansible set_fact Module ## Conclusion Filters are the data transformation layer of Ansible. Essential ones: `default()` for safe variable access, `int`/`bool`/`float` for type conversion, `map()`/`selectattr()`/`rejectattr()` for list processing, `combine()` for merging dicts, `regex_search()`/`regex_replace()` for string matching, and `to_json`/`from_json` for serialization. Chain filters with `|` to build complex transformations. Master these and you can handle any data manipulation in your playbo... --- ## Ansible find — Delete Files in Dir URL: https://www.ansiblebyexample.com/articles/how-to-delete-only-files-inside-a-directory-ansible-module-find Description: Find and delete files inside directories with Ansible find module. Filter by age, size, pattern, and type. Complete cleanup playbook examples. ## How to Delete Only Files Inside a Directory with Ansible? ## Ansible How to Delete Only Files Inside a Directory - `ansible.builtin.find` - Return a list of files based on specific criteria Today we're talking about the Ansible module `find`. The full name is `ansible.builtin.find`, which means that is part of the collection included in the `ansible-core` builtin collection. This module returns a list of files based on specific criteria using the `find` popular Unix command. ## Parameters - paths string - List of paths of directories to search - hidden boolean - no/yes - recurse boolean - recursively descend into the directory looking for files - file_type string - file/directory/any/link The most important parameters of the `find` module for this use case. The mandatory parameter `paths` specify the list of paths of directories to search. You could include hidden files with the `hidden` parameter. As well as recurse in any directory under the main path with the `recurse` parameter. Another useful parameter is `file_type`, defaults to `file` but you could filter for `directory`, `link` or `any` filesystem object type. ## Links - ansible.builtin.find - ansible.builtin.file ## Playbook How to delete Ooly files inside a directory with Ansible Playbook. I'm going to delete only the files and directories under the example folder of my login user (`devops`). ### code [code example] ### execution [code example] ### before execution [code example] ### after execu... --- ## Ansible find Module — Search for Files and Directories URL: https://www.ansiblebyexample.com/articles/ansible-find-module-search-for-files-and-directories Description: Search files and directories in Ansible using ansible.builtin.find. Filter by name, pattern, age, size, and content like the Linux find command. # Ansible find Module — Search for Files and Directories ## What Is the Ansible find Module? The `ansible.builtin.find` module searches for files matching specific criteria — name patterns, age, size, content, and type. It's the Ansible equivalent of the Linux `find` command, returning a list of matching files that you can feed into subsequent tasks for cleanup, backup, or processing. ## Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `paths` | list | required | Directories to search | | `patterns` | list | `'*'` | Filename patterns (shell glob or regex) | | `use_regex` | boolean | false | Treat patterns as Python regex | | `age` | string | — | File age filter (`7d`, `4w`, `-1h`) | | `age_stamp` | string | mtime | Timestamp: atime, ctime, mtime | | `size` | string | — | Size filter (`1m`, `-500k`, `10g`) | | `file_type` | string | file | Type: file, directory, link, any | | `recurse` | boolean | false | Search subdirectories | | `hidden` | boolean | false | Include hidden files | | `contains` | string | — | Regex to match file content | | `excludes` | list | — | Patterns to exclude | | `depth` | integer | — | Maximum recursion depth | ## Find and Delete Old Logs [code example] ## Find Large Files [code example] ## Find Files by Content [code example] ## Find Empty Directories [code example] ## Find Recently Modified Files [code example] ## Using Regex Patterns [code example] ## Return Values Th... --- ## Ansible Firewall — firewalld & UFW URL: https://www.ansiblebyexample.com/articles/ansible-firewalld-ufw-manage-firewall-rules Description: Use Ansible to manage firewall rules with firewalld and UFW modules. Open ports, allow services, configure zones, and secure Linux servers. ## Introduction Ansible manages Linux firewalls through dedicated modules: `ansible.posix.firewalld` for RHEL/CentOS/Fedora and `community.general.ufw` for Ubuntu/Debian. Open ports, allow services, configure zones, and ensure firewall rules persist across reboots. ## firewalld (RHEL/CentOS/Fedora) ### Open a Port [code example] ### Allow a Service [code example] ### Zone Management [code example] ### Rich Rules [code example] ### Close Ports / Remove Rules [code example] ## UFW (Ubuntu/Debian) ### Open a Port [code example] ### Allow from Specific IPs [code example] ### Rate Limiting [code example] ### Deny Traffic [code example] ### Delete Rules [code example] ## Practical Patterns ### Web Server Firewall (firewalld) [code example] ### Web Server Firewall (UFW) [code example] ### Database Server Lockdown [code example] ## firewalld Parameters | Parameter | Description | |-----------|-------------| | `port` | Port/protocol (e.g., `80/tcp`) | | `service` | Service name (e.g., `http`) | | `zone` | Firewall zone | | `source` | Source IP/CIDR | | `interface` | Network interface | | `rich_rule` | Rich rule string | | `permanent` | Persist across reboots | | `immediate` | Apply immediately | | `state` | `enabled` or `disabled` | ## Troubleshooting ### "Locked out of SSH" Always allow SSH **before** enabling the firewall: [code example] ### Rules Not Persisting For firewalld, set `permanent: true` AND `immediate: true`: [code example] ## Rela... --- ## Ansible firewalld — Open Ports RedHat URL: https://www.ansiblebyexample.com/articles/open-firewall-ports-in-redhat-like-systems-ansible-module-firewalld Description: Open and manage firewall ports on RedHat, CentOS, Fedora with Ansible firewalld module. Complete guide with services, ports, rich rules, zones. ## Introduction Managing firewall rules is essential for server security. The `ansible.posix.firewalld` module provides full control over firewalld on RedHat-family systems — opening ports, enabling services, configuring zones, and applying rich rules, all idempotently. This guide covers everything from basic port opening to advanced zone-based firewall configurations with Ansible. ## The ansible.posix.firewalld Module The full module name is `ansible.posix.firewalld`, part of the `ansible.posix` collection for POSIX platforms. It requires: - Ansible 2.9+ - firewalld >= 0.2.11 on the target - Python `firewall` bindings on the target - Works on: RHEL, CentOS, CentOS Stream, Fedora, Rocky Linux, AlmaLinux, Oracle Linux, EuroLinux ### Install the Collection [code example] ## Parameters Reference | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `state` | string | Yes | — | `enabled`, `disabled`, `present`, `absent` | | `service` | string | No | — | Service name (e.g., `http`, `https`) | | `port` | string | No | — | Port/protocol (e.g., `8080/tcp`) | | `permanent` | boolean | No | false | Persist across reboots | | `immediate` | boolean | No | false* | Apply to running config now | | `zone` | string | No | system default | Target zone | | `rich_rule` | string | No | — | Rich rule string | | `source` | string | No | — | Source IP/network | | `interface` | string | No | — | Network interface | | `masquerade` |... --- ## Ansible firewalld and ufw Modules URL: https://www.ansiblebyexample.com/articles/ansible-firewalld-ufw-manage-firewall-rules Description: Use Ansible to manage firewall rules with firewalld and ufw modules. Open ports, allow services, configure zones, and automate firewall policies. ## Introduction Ansible manages Linux firewall rules through two modules: `ansible.posix.firewalld` for RHEL/CentOS/Fedora (firewalld) and `community.general.ufw` for Ubuntu/Debian (UFW). Both are idempotent — safe to run repeatedly. ## UFW (Ubuntu/Debian) ### Install and Enable [code example] ### Open Ports [code example] ### UFW Parameters | Parameter | Description | |-----------|-------------| | `rule` | `allow`, `deny`, `reject`, `limit` | | `port` | Port number or range (`8000:9000`) | | `proto` | `tcp`, `udp`, `any` | | `src` | Source address/CIDR | | `dest` | Destination address/CIDR | | `direction` | `in`, `out`, `incoming`, `outgoing`, `routed` | | `name` | Application profile name | | `state` | `enabled`, `disabled`, `reloaded`, `reset` | | `policy` | Default policy: `allow`, `deny`, `reject` | | `logging` | `on`, `off`, `low`, `medium`, `high`, `full` | | `delete` | `true` to delete a rule | | `insert` | Position to insert rule | | `insert_relative_to` | `zero`, `first-ipv4`, `last-ipv4`, etc. | ### Complete UFW Playbook [code example] ## Firewalld (RHEL/CentOS/Fedora) ### Install and Enable [code example] ### Open Ports and Services [code example] ### Firewalld Parameters | Parameter | Description | |-----------|-------------| | `service` | Firewalld service name | | `port` | Port/protocol (`8080/tcp`) | | `rich_rule` | Rich rule string | | `source` | Source address/CIDR | | `zone` | Firewall zone (default: `public`) | | `permanent` | Save to pers... --- ## Ansible Fluent Bit — Lightweight Log Processor and Forwarder URL: https://www.ansiblebyexample.com/articles/ansible-fluent-bit-log-processor-forwarder Description: Deploy Fluent Bit with Ansible for lightweight log collection and forwarding. Input plugins, parsers, filters, output to Elasticsearch/Loki/S3, Kubernetes. ## Introduction Fluent Bit is a lightweight log processor and forwarder — it collects, parses, filters, and routes logs with minimal resource usage (typically ~450KB memory). It's the CNCF-graduated log collector for Kubernetes and edge environments. Ansible automates deployment: install Fluent Bit, configure input/parser/filter/output pipelines, and manage the service across your fleet. ## Install Fluent Bit [code example] ## Pipeline Configuration [code example] ### Parsers [code example] ## Health Check [code example] ## Troubleshooting ### Check Pipeline Status [code example] ### Buffer Issues [code example] ## Related Articles - Ansible Grafana Loki - Ansible Rsyslog - Ansible ELK Stack - Ansible Prometheus Grafana ## Conclusion Fluent Bit is the lightweight alternative to Fluentd and Logstash — Ansible deploys it as a DaemonSet-equivalent across all servers with group-specific inputs (web servers get nginx parsers, app servers get JSON/multiline parsers). Route logs to Loki, Elasticsearch, S3, or Fluentd with a single config change. The built-in HTTP health endpoint and Prometheus metrics make monitoring the log pipeline itself straightforward. --- ## Ansible for Advanced Nuclear and SMR Infrastructure — Deploy Monitoring and Safety Systems URL: https://www.ansiblebyexample.com/articles/ansible-nuclear-smr-infrastructure-monitoring-safety Description: Automate nuclear facility IT infrastructure with Ansible. Deploy SMR monitoring systems, safety instrumentation, NRC compliance, radiation monitoring. ## Introduction Advanced nuclear technologies — especially Small Modular Reactors (SMRs) — are accelerating in 2026, driven by power demand from AI data centers and decarbonization goals. WEF flags advanced nuclear as a top emerging technology. The IT infrastructure behind nuclear facilities requires extreme reliability, regulatory compliance, and security hardening. Ansible automates monitoring systems, safety instrumentation networks, NRC/IAEA compliance, radiation monitoring, and SCADA security. ## Nuclear IT Infrastructure | System | Purpose | Ansible Role | |--------|---------|-------------| | Plant Information System | Real-time process data | Deploy + configure | | Radiation Monitoring | Dose tracking, environmental | Sensor deployment | | Safety Instrumentation | Emergency systems | Configuration management | | SCADA/DCS | Process control network | Security hardening | | Compliance Reporting | NRC/IAEA reports | Automated generation | | Cybersecurity | NEI 08-09 compliance | Continuous hardening | ## Deploy Radiation Monitoring Network [code example] ## SCADA/DCS Security Hardening [code example] ## Plant Information System [code example] ## NRC Compliance Automation [code example] ## Emergency System Configuration [code example] ## Related Articles - Ansible Autonomous Industrial - Ansible Preemptive Cybersecurity - Ansible Compliance as Code - Ansible cron Module ## Conclusion Nuclear IT infrastructure in 2026 — especially for SMRs — demands the hig... --- ## Ansible for Agentic AI — Automate Multi-Agent Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-agentic-ai-multi-agent-infrastructure Description: Deploy and manage agentic AI and multi-agent systems with Ansible. Automate LLM agent orchestration, GPU provisioning, and AI workflow infrastructure. ## Introduction Agentic AI — autonomous AI systems that plan, execute, and iterate on tasks — is the defining tech trend of 2026. Multi-agent architectures require complex infrastructure: GPU clusters, vector databases, message queues, API gateways, and monitoring. Ansible automates the provisioning, deployment, and lifecycle management of this entire stack. ## AI Agent Infrastructure Stack A typical multi-agent system needs: | Component | Tools | Ansible Role | |-----------|-------|-------------| | LLM Inference | vLLM, TGI, Ollama | Deploy + configure | | Agent Framework | LangChain, CrewAI, AutoGen | Install + configure | | Vector Database | Qdrant, Weaviate, Milvus | Deploy + scale | | Message Queue | Redis, RabbitMQ, NATS | Cluster setup | | API Gateway | Kong, Traefik | Route + rate-limit | | Monitoring | Prometheus, Grafana, LangSmith | Observe agents | | GPU Management | NVIDIA drivers, CUDA | Provision + maintain | ## Deploy an LLM Inference Server ### vLLM (High-Performance) [code example] ### Ollama (Local Development) [code example] ## Deploy Vector Database (Agent Memory) [code example] ## Deploy Multi-Agent Framework ### CrewAI Application [code example] Environment template: [code example] ## GPU Cluster Provisioning [code example] ## Agent Monitoring Stack [code example] ## Complete Multi-Agent Playbook [code example] [code example] ## Related Articles - Ansible Docker Guide - Ansible Kubernetes Guide - Ansible GPU and NVIDIA - Ansible ... --- ## Ansible for AI Infrastructure — GPU Clusters, Model Serving, and Token Economics URL: https://www.ansiblebyexample.com/articles/ansible-ai-infrastructure-gpu-clusters-model-serving Description: Optimize AI infrastructure with Ansible. Manage GPU clusters, balance inference costs, deploy model serving platforms, and automate token economics. ## Introduction 2026's AI infrastructure challenge isn't just buying GPUs — it's balancing model choice, inference cost, deployment architecture, and token economics. Deloitte calls this an "AI infrastructure reckoning." Ansible automates GPU cluster lifecycle, model serving deployment, multi-model routing, cost optimization, and capacity planning. ## GPU Cluster Provisioning [code example] ## NVIDIA Triton Inference Server [code example] ## Multi-Model Routing (Cost Optimization) [code example] [code example] ## GPU Monitoring and Autoscaling [code example] [code example] ## Capacity Planning [code example] ## Related Articles - Ansible for Agentic AI - Ansible Docker Guide - Ansible Kubernetes Guide - Ansible AI Security ## Conclusion AI infrastructure in 2026 is about optimization, not just procurement. Ansible automates the full stack: GPU provisioning with driver pinning and clock management, Triton/vLLM model serving, multi-model routing for cost optimization, DCGM monitoring with utilization alerts, and fleet capacity planning. The key insight: treat inference infrastructure like any other fleet — provision it declaratively, monitor it continuously, and optimize costs by routing to the cheapest adequate model. Ansible makes the "AI infrastructure reckoning" manageable at scale. --- ## Ansible for AI Security — Automate AI Platform Security and Guardrails URL: https://www.ansiblebyexample.com/articles/ansible-ai-security-platform-guardrails Description: Secure AI deployments with Ansible. Automate LLM guardrails, model access control, GPU isolation, prompt injection defenses, and AI compliance scanning. ## Introduction As organizations deploy AI at scale in 2026, AI security has become its own platform category. Gartner lists AI security platforms as a top strategic trend. Ansible automates the security hardening of AI infrastructure: model access controls, GPU isolation, prompt injection defenses, data pipeline security, and compliance scanning. ## AI Security Threat Surface | Threat | Risk | Ansible Mitigation | |--------|------|-------------------| | Model theft | Stolen weights/IP | File permissions, network isolation | | Prompt injection | Unauthorized actions | WAF rules, input validation | | Data poisoning | Corrupted training data | Pipeline integrity checks | | GPU side-channel | Cross-tenant data leak | GPU isolation, MIG config | | Model supply chain | Malicious model files | Hash verification, scanning | | Inference API abuse | DDoS, cost explosion | Rate limiting, authentication | ## Secure Model Storage [code example] ## GPU Isolation (NVIDIA MIG) [code example] ## API Gateway Security [code example] Nginx template: [code example] ## AI Data Pipeline Security [code example] ## Model Supply Chain Security [code example] ## Compliance Scanning [code example] ## Related Articles - Ansible for Agentic AI - Ansible Vault Guide - Ansible no_log - Ansible Compliance as Code ## Conclusion AI security in 2026 requires automating six layers: model storage security (permissions, integrity), GPU isolation (MIG), API gateway protection (rate limiting, WA... --- ## Ansible for AI-Native Development — CI/CD Pipelines for ML and LLM Apps URL: https://www.ansiblebyexample.com/articles/ansible-ai-native-development-cicd-ml-llm Description: Automate AI-native development with Ansible. Deploy ML CI/CD pipelines, model registries, feature stores, experiment tracking, and LLM application. ## Introduction AI-native software development — where coding, testing, and app building are increasingly AI-led — tops Gartner's 2026 trends. This shifts infrastructure needs: teams need ML CI/CD pipelines, model registries, experiment tracking, feature stores, and LLM evaluation frameworks. Ansible automates the entire MLOps platform stack. ## MLOps Platform Stack | Component | Tool | Purpose | |-----------|------|---------| | Experiment Tracking | MLflow, W&B | Track runs, metrics, artifacts | | Model Registry | MLflow, DVC | Version and stage models | | Feature Store | Feast, Hopsworks | Serve ML features | | Pipeline Orchestration | Airflow, Prefect | Schedule training jobs | | Model Serving | Triton, BentoML | Serve predictions | | Monitoring | Evidently, Whylogs | Detect data/model drift | ## Deploy MLflow (Experiment Tracking + Registry) [code example] ## Deploy Feature Store (Feast) [code example] ## ML CI/CD Pipeline [code example] ## Model Drift Monitoring [code example] [code example] ## Complete MLOps Playbook [code example] [code example] ## Related Articles - Ansible for Agentic AI - Ansible AI Infrastructure - Ansible Docker Guide - Ansible cron Module ## Conclusion AI-native development in 2026 requires MLOps infrastructure that's as mature as traditional DevOps. Ansible automates the entire platform: MLflow for experiment tracking and model registry, Feast for feature stores, Airflow for pipeline orchestration, Evidently for drift monitori... --- ## Ansible for Autonomous Industrial Systems — Factory and Supply Chain Automation URL: https://www.ansiblebyexample.com/articles/ansible-autonomous-industrial-systems-factory-supply-chain Description: Automate autonomous industrial systems with Ansible. Deploy smart factory software, PLC configuration, MES integration, supply chain orchestration. ## Introduction Autonomous industrial systems — factories, logistics networks, and supply chains becoming semi-autonomous through AI orchestration — are a defining 2026 trend. Deloitte reports enterprises deploying robot fleets and self-driving production flows. Ansible manages the IT/OT convergence: edge controllers, MES (Manufacturing Execution Systems), SCADA configuration, predictive maintenance pipelines, and supply chain orchestration. ## Industrial Inventory [code example] ## Edge Gateway Deployment [code example] ## Predictive Maintenance Pipeline [code example] ## Supply Chain Orchestration [code example] ## Network Segmentation (IT/OT) [code example] ## Rolling Updates for Production Systems [code example] ## Related Articles - Ansible Physical AI & Robotics - Ansible Docker Guide - Ansible cron Module - Ansible systemd Module ## Conclusion Autonomous industrial systems in 2026 merge IT and OT — and Ansible bridges both worlds. It deploys edge gateways with industrial protocol stacks (OPC-UA, Modbus, MQTT), manages predictive maintenance ML pipelines, orchestrates supply chain visibility platforms, enforces IT/OT network segmentation, and performs rolling updates during maintenance windows. The key pattern: treat factory floor devices like any infrastructure fleet — inventory them, configure them declaratively, update them safely with `serial: 1` and production schedule awareness. Ansible's agentless model is ideal for constrained OT environments. --- ## Ansible for AWS — EC2, S3, RDS & IAM Automation with Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-aws-ec2-s3-rds-iam-automation Description: Complete guide to AWS automation with Ansible. EC2, S3, RDS, IAM, VPC, and security groups with practical playbook examples. # Ansible for AWS ## Setup [code example] Configure credentials: [code example] ## EC2 Instances [code example] ## Security Groups [code example] ## S3 [code example] ## RDS [code example] ## VPC [code example] ## IAM [code example] ## Dynamic Inventory [code example] [code example] ## Conclusion Ansible's AWS modules cover the full AWS service catalog. Use `amazon.aws` for core services and `community.aws` for extended coverage. Combine with dynamic inventory for fully automated cloud management. --- ## Ansible for AWS Cloud Automation — EC2, RDS, S3, and Infrastructure at Scale URL: https://www.ansiblebyexample.com/articles/ansible-aws-cloud-automation-ec2-rds-s3-infrastructure Description: Automate AWS infrastructure with Ansible. Manage EC2 instances, RDS databases, S3 buckets, IAM roles, VPCs, and build complete cloud environments with. ## Introduction AWS provides 200+ services — and Ansible's `amazon.aws` and `community.aws` collections provide modules for the ones that matter most: EC2 for compute, RDS for databases, S3 for storage, VPC for networking, and IAM for security. While Terraform excels at provisioning cloud resources with state tracking, Ansible shines at combining provisioning with configuration — create an EC2 instance AND install your application in the same playbook. ## Setup [code example] ### Authentication [code example] ## Pattern 1: Complete VPC with Subnets [code example] ## Pattern 2: EC2 Fleet with Auto Scaling [code example] ## Pattern 3: RDS Database [code example] ## Pattern 4: S3 with Lifecycle Policies [code example] ## Pattern 5: IAM Roles and Policies [code example] ## AWS Dynamic Inventory [code example] ## Cost Optimization Playbook [code example] ## Troubleshooting ### Credential Errors [code example] ### Timeout on Large Operations [code example] ## Related Articles - AWS EC2 AMI Module - Ansible vs Terraform - Ansible + Terraform Pipeline - Ansible Best Practices Guide - Managing Credentials with Vault ## Conclusion Use `amazon.aws` for core services (EC2, VPC, RDS, S3, IAM) and `community.aws` for extended services (ALB, Auto Scaling, launch templates). Authenticate via environment variables in CI/CD or AAP credential injection in production. For enterprise deployments, combine VPC networking, security groups, EC2 fleets with auto scaling, en... --- ## Ansible for Beginners — Complete Getting Started Guide 2026 URL: https://www.ansiblebyexample.com/articles/ansible-beginners-complete-getting-started-guide Description: Learn Ansible from scratch. Install Ansible, write your first playbook, understand inventory and modules, and automate your first server in 15 minutes. ## Introduction Ansible automates server management: installing software, deploying configs, managing services, and more — all without agents. You write what you want in YAML, and Ansible makes it happen over SSH. This guide takes you from zero to your first working playbook. ## What Is Ansible? Ansible is an automation tool that: - **Connects** to servers via SSH (no agent needed) - **Reads** your instructions from YAML files (playbooks) - **Executes** modules on remote servers to achieve desired state - **Reports** what changed and what was already correct [code example] ## Install Ansible [code example] ## Your First Command (Ad-Hoc) [code example] ## Inventory — Define Your Servers [code example] [code example] ## Your First Playbook [code example] [code example] ## Key Concepts ### Modules — What Ansible Can Do [code example] ### Variables [code example] ### Conditionals [code example] ### Loops [code example] ### Handlers — React to Changes [code example] ### Roles — Reusable Automation [code example] [code example] ## Common First-Time Issues [code example] ## Next Steps 1. **Learn roles** — Package your playbooks into reusable components 2. **Use Ansible Vault** — Encrypt passwords and secrets 3. **Set up inventory per environment** — staging, production 4. **Add to CI/CD** — Automate deployments on git push 5. **Explore collections** — Community modules for AWS, Docker, Kubernetes ## Recommended Reading Order 1. Ansible Playbook Guid... --- ## Ansible for CI/CD Pipelines — GitHub Actions, GitLab CI, Jenkins URL: https://www.ansiblebyexample.com/articles/ansible-cicd-github-actions-gitlab-jenkins Description: Use Ansible in CI/CD pipelines with GitHub Actions, GitLab CI, and Jenkins. Learn pipeline integration patterns, secrets management, and deployment. ## Introduction Ansible is a natural fit for the deployment stage of CI/CD pipelines. After your code is built and tested, Ansible handles the infrastructure: provisioning servers, deploying artifacts, running migrations, and validating health. This guide shows integration patterns for the three most popular CI/CD platforms. ## GitHub Actions [code example] ### With Execution Environments [code example] ## GitLab CI [code example] ## Jenkins [code example] ## Secrets Management [code example] ## Pipeline Best Practices [code example] ### Dry-Run in Pull Requests [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Execution Environments - Ansible Playbook Best Practices - Ansible check mode vs diff mode - Ansible Vault Guide ## Conclusion **GitHub Actions**: Use `actions/checkout` + pip install + SSH key from secrets. **GitLab CI**: Use `.extends` for shared setup, `when: manual` for production gates. **Jenkins**: Use `withCredentials` for secrets, parameterized builds for environment selection. All three follow the same pattern: lint → dry-run (staging) → deploy (staging) → manual gate → deploy (production). Pin your Ansible version, encrypt secrets with Vault, and always clean up credentials in post-run steps. --- ## Ansible for Cisco UCS Automation — Server Profiles, VLANs, and Data Center Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-cisco-ucs-automation-server-profiles-vlans-data-center Description: Automate Cisco UCS Manager with Ansible. Configure server profiles, VLANs, service profiles, boot policies, and manage bare-metal infrastructure at scale. ## Introduction Cisco Unified Computing System (UCS) combines compute, networking, storage access, and virtualization into a single cohesive platform. Managing UCS at scale — provisioning blade servers, configuring service profiles, setting up VLANs, and enforcing boot policies across multiple UCS domains — is exactly what Ansible excels at. The `cisco.ucs` collection provides modules for every major UCS Manager operation, turning hours of GUI clicks into repeatable, version-controlled playbooks. ## Prerequisites | Requirement | Details | |-------------|---------| | Ansible | 2.8 or newer | | Python SDK | `ucsmsdk` | | Collection | `cisco.ucs` | | UCS Manager | 3.2+ recommended | | Network | HTTPS access from Ansible control node to UCS Manager | ### Installation [code example] ## Module Reference | Module | Purpose | |--------|---------| | `ucs_vlans` | Create, modify, delete VLANs | | `ucs_vlan_find` | Find VLANs by ID or name | | `ucs_service_profile_template` | Manage service profile templates | | `ucs_service_profile_from_template` | Instantiate profiles from templates | | `ucs_lan_connectivity` | LAN connectivity policies | | `ucs_san_connectivity` | SAN connectivity policies | | `ucs_mac_pool` | MAC address pools | | `ucs_wwn_pool` | WWN pools for Fibre Channel | | `ucs_uuid_pool` | UUID pools for server identity | | `ucs_ip_pool` | IP address pools for KVM/management | | `ucs_ntp_server` | NTP server configuration | | `ucs_dns_server` | DNS server configuration... --- ## Ansible for Cloud Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-cloud-engineers-complete-guide Description: Ansible cloud automation: multi-cloud provisioning, infrastructure as code, and hybrid deployments. With tested, real-world examples. # Ansible for Cloud Engineers — Complete Guide ## Introduction Ansible cloud automation: multi-cloud provisioning, infrastructure as code, and hybrid deployments. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible cloud automation: multi-cloud provisioning, infrastructure as code, and hybrid deployments. Start with the fundamentals, imple... --- ## Ansible for Compliance Officers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-compliance-officers-complete-guide Description: Ansible for compliance: automated auditing, STIG/CIS/SOC2 enforcement, and evidence collection. Tested, copy-paste examples included. # Ansible for Compliance Officers — Complete Guide ## Introduction Ansible for compliance: automated auditing, STIG/CIS/SOC2 enforcement, and evidence collection. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible for compliance: automated auditing, STIG/CIS/SOC2 enforcement, and evidence collection. Start with the fundamentals, implement... --- ## Ansible for Confidential Computing — Deploy TEE and Encrypted Workloads URL: https://www.ansiblebyexample.com/articles/ansible-confidential-computing-tee-encrypted-workloads Description: Automate confidential computing with Ansible. Deploy Intel SGX, AMD SEV, and ARM CCA trusted execution environments for encrypted workloads. ## Introduction Confidential computing protects data in use — while it's being processed — using hardware-based Trusted Execution Environments (TEEs). As sensitive AI and analytics workloads move to shared cloud infrastructure, Gartner highlights confidential computing as a 2026 strategic trend. Ansible automates the provisioning, configuration, and attestation of TEE environments across Intel SGX, AMD SEV, Intel TDX, and ARM CCA platforms. ## TEE Technologies | Technology | Vendor | Scope | Use Case | |-----------|--------|-------|----------| | Intel SGX | Intel | Application enclave | Specific secrets processing | | Intel TDX | Intel | Full VM | Confidential VMs | | AMD SEV-SNP | AMD | Full VM | Confidential VMs | | ARM CCA | ARM | Realm | Mobile/edge confidential | | NVIDIA H100 CC | NVIDIA | GPU TEE | Confidential AI inference | ## Intel SGX Setup [code example] ## AMD SEV-SNP Setup [code example] ## Confidential VM Deployment [code example] VM template: [code example] ## Confidential AI Inference (NVIDIA H100) [code example] ## Attestation Verification [code example] ## Fleet Compliance Audit [code example] ## Related Articles - Ansible AI Security - Ansible Post-Quantum Cryptography - Ansible sysctl Module - Ansible Compliance as Code ## Conclusion Confidential computing in 2026 protects data during processing — the last gap after encryption at rest and in transit. Ansible automates the full lifecycle: provisioning TEE hardware (SGX, SEV-SNP, TDX), c... --- ## Ansible for Data Monetization — Deploy Data Products and Analytics Platforms URL: https://www.ansiblebyexample.com/articles/ansible-data-monetization-products-analytics-platforms Description: Automate data monetization platforms with Ansible. Deploy data products, analytics pipelines, data catalogs, API marketplaces, and usage metering. ## Introduction Data monetization — creating measurable business value from data assets — is a top CIO priority in 2026. McKinsey reports that leading tech leaders use data monetization to drive revenue, not just cut costs. Ansible automates the infrastructure: data catalogs, analytics pipelines, API-based data products, usage metering, and access governance. ## Data Platform Stack | Component | Tool | Purpose | |-----------|------|---------| | Data Catalog | DataHub, OpenMetadata | Asset discovery | | Data Warehouse | ClickHouse, DuckDB, Snowflake | Analytics queries | | API Gateway | Kong, Traefik | Serve data products | | Metering | Stripe Metering, custom | Usage billing | | Governance | Apache Atlas, OpenMetadata | Access control, lineage | | Pipeline | Airflow, Dagster | ETL/ELT orchestration | ## Deploy Data Catalog (OpenMetadata) [code example] ## Deploy Analytics Engine (ClickHouse) [code example] ## Data Product API [code example] [code example] ## Usage Metering and Billing [code example] ## Data Access Governance [code example] ## Complete Data Platform [code example] ## Related Articles - Ansible AI Infrastructure - Ansible Docker Guide - Ansible Sovereign Cloud - Ansible cron Module ## Conclusion Data monetization in 2026 requires infrastructure that treats data as a product — with catalogs for discovery, analytics engines for queries, APIs for access, metering for billing, and governance for compliance. Ansible automates the entire platform:... --- ## Ansible for Database Administrators — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-database-administrators-complete-guide Description: Ansible for DBAs: PostgreSQL, MySQL, MongoDB automation including backups, replication, and upgrades. With clear, copy-paste, step-by-step examples. # Ansible for Database Administrators — Complete Guide ## Introduction Ansible for DBAs: PostgreSQL, MySQL, MongoDB automation including backups, replication, and upgrades. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible for DBAs: PostgreSQL, MySQL, MongoDB automation including backups, replication, and upgrades. Start with the fundame... --- ## Ansible for DevOps — Complete Workflow Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-devops-complete-workflow-guide Description: Ansible for DevOps guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible for DevOps — Complete Workflow Guide ## Introduction Complete Workflow Guide. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible for DevOps requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective tas... --- ## Ansible for DevOps Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-devops-engineers-complete-guide Description: Complete Ansible guide for DevOps engineers: CI/CD integration, infrastructure automation, and deployment patterns. With tested, real-world examples. # Ansible for DevOps Engineers — Complete Guide ## Introduction Complete Ansible guide for DevOps engineers: CI/CD integration, infrastructure automation, and deployment patterns. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Complete Ansible guide for DevOps engineers: CI/CD integration, infrastructure automation, and deployment patterns. S... --- ## Ansible for Digital Provenance — Content Authenticity and C2PA Automation URL: https://www.ansiblebyexample.com/articles/ansible-digital-provenance-content-authenticity-c2pa Description: Automate digital provenance and content authenticity with Ansible. Deploy C2PA signing, content credentials, watermarking infrastructure, and verification. ## Introduction Digital provenance — verifying where media came from — is foundational in the generative AI era. Gartner includes digital provenance in its 2026 trends, and C2PA (Coalition for Content Provenance and Authenticity) is the emerging standard. Ansible automates the deployment of content signing infrastructure, C2PA verification services, watermarking pipelines, and provenance validation across media platforms. ## C2PA Signing Infrastructure [code example] Manifest template: [code example] ## AI Content Watermarking Pipeline [code example] ## Content Verification Service [code example] ## Media Pipeline Integration [code example] ## Compliance Audit [code example] ## Related Articles - Ansible AI Security - Ansible Post-Quantum Cryptography - Ansible Nginx Guide - Ansible cron Module ## Conclusion Digital provenance in 2026 is about proving content origin in a world of AI-generated media. Ansible automates the infrastructure: deploying C2PA signing tools and certificates, running watermarking services for AI-generated content, hosting verification APIs, integrating signing into media pipelines, and auditing provenance coverage. The C2PA standard is becoming foundational — Ansible makes it deployable across your entire content infrastructure, from CMS to CDN. --- ## Ansible for Docker — Build, Run & Manage Containers with Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-docker-build-run-manage-containers Description: Complete guide to managing Docker with Ansible. Build images, run containers, manage networks, volumes, and Docker Compose deployments. # Ansible for Docker ## Setup [code example] ## Run Containers [code example] ## Build Images [code example] ## Docker Compose [code example] ## Networks [code example] ## Volumes [code example] ## Container Management [code example] ## Health Checks [code example] ## Full Stack Example [code example] ## Conclusion Ansible + Docker is perfect for standardized container deployments across environments. Use `docker_container` for individual containers, `docker_compose_v2` for multi-container apps, and combine with Ansible Vault for secrets. --- ## Ansible for Domain-Specific AI — Deploy Specialized Language Models URL: https://www.ansiblebyexample.com/articles/ansible-domain-specific-ai-specialized-language-models Description: Deploy domain-specific language models with Ansible. Automate fine-tuned LLM serving for healthcare, legal, finance, and enterprise-specific AI. ## Introduction Domain-specific language models — specialized for legal, healthcare, finance, and enterprise tasks — are rising because they're cheaper and more accurate than general-purpose LLMs. Gartner highlights DSLMs as a 2026 trend. Ansible automates the full lifecycle: fine-tuning infrastructure, model deployment, domain-specific evaluation, compliance guardrails, and multi-model routing. ## Domain-Specific Model Landscape | Domain | Models | Key Requirements | |--------|--------|-----------------| | Healthcare | Med-PaLM, BioMistral, ClinicalBERT | HIPAA, PHI protection | | Legal | SaulLM, LegalBERT | Privilege, citation accuracy | | Finance | FinGPT, BloombergGPT | SOX compliance, real-time data | | Code | CodeLlama, DeepSeek-Coder, StarCoder | Sandboxed execution | | Enterprise | Fine-tuned Llama, Mistral | Internal data, access control | ## Fine-Tuning Infrastructure [code example] Training config template: [code example] ## Deploy Domain-Specific Model [code example] ## Domain-Specific Guardrails [code example] ## Multi-Domain Model Router [code example] [code example] ## Domain-Specific Evaluation [code example] ## Related Articles - Ansible AI Infrastructure - Ansible for Agentic AI - Ansible AI Security - Ansible Vault Guide ## Conclusion Domain-specific language models in 2026 outperform general LLMs for specialized tasks while costing less to run. Ansible automates every stage: provisioning fine-tuning infrastructure with LoRA/PEFT, deployi... --- ## Ansible for Kubernetes — K8s Deploy URL: https://www.ansiblebyexample.com/articles/ansible-kubernetes-deploy-manage-automate Description: Complete guide to using Ansible with Kubernetes. Deploy applications, manage namespaces, configure RBAC, and automate cluster operations. # Ansible for Kubernetes ## Setup [code example] ## Deploy Applications ### Create Namespace [code example] ### Deploy Application [code example] ### Expose with Service [code example] ## Query Cluster [code example] ## Helm Charts [code example] ## ConfigMaps & Secrets [code example] ## RBAC [code example] ## Rolling Updates [code example] ## Delete Resources [code example] ## Conclusion Ansible + Kubernetes is powerful for teams already using Ansible. Use `kubernetes.core.k8s` for resource management, `k8s_info` for querying, and `helm` for chart deployments. Combine with Ansible Vault for secrets management. ## Related guide Related reading: running Ansible against Kubernetes clusters covers this in real-world detail. --- ## Ansible for Kubernetes by Example book URL: https://www.ansiblebyexample.com/articles/ansible-for-kubernetes-by-example-book Description: Ansible for Kubernetes by Example — the Apress book by Luca Berton. Automate K8s clusters, pods, services, and cloud providers with practical Ansible. {{}} ## What You’ll Learn - How to automate Kubernetes pods, services, and storage with Ansible - Learn to automate Kubernetes cluster management with Ansible - How to automate Kubernetes cloud services such as Amazon Elastic Kubernetes Service (EKS), Google Kubernetes Engine (GKE), and Azure Kubernetes Service (AKS) with Ansible - Understand Ansible troubleshooting ## About this book Learn how to automate your Kubernetes infrastructure using Ansible. This book will enable you to automate more tasks and save time with this human-readable platform. Augment your productivity by applying Infrastructure as Code (IaC) as part of infrastructure and operations (I&O) in your multi/hybrid cloud modern infrastructure. Containerized microservices deployed via Kubernetes allow you to save time, reduce human interaction and errors and create more robust world-scale cloud-native applications. Learn how to automate the most redundant activities such as reports, services, launching a pod, adding permanent storage, configuring load balancing, and adding or modifying any Kubernetes parameter. You’ll also look at end-to-end use cases and how advanced cluster automation (Helm packages and plugins, node states, etc.) is moving forward. Each lesson utilizes a specific use case for the modern Kubernetes cluster and focuses on a single module from the most crucial parameter with code Playbooknstrations and real-life usage. Each code example is battle-proven in real-life with console interaction... --- ## Ansible for Kubernetes by Example book by Apress URL: https://www.ansiblebyexample.com/articles/ansible-for-kubernetes-by-example-book-by-apress Description: Learn to automate Kubernetes infrastructure using Ansible. This book covers Kubernetes pods, services, cloud providers, and more with real-life use. {{}} ## What You’ll Learn - How to automate Kubernetes pods, services, and storage with Ansible - Learn to automate Kubernetes cluster management with Ansible - How to automate Kubernetes cloud services such as Amazon Elastic Kubernetes Service (EKS), Google Kubernetes Engine (GKE), and Azure Kubernetes Service (AKS) with Ansible - Understand Ansible troubleshooting ## About this book Learn how to automate your Kubernetes infrastructure using Ansible. This book will enable you to automate more tasks and save time with this human-readable platform. Augment your productivity by applying Infrastructure as Code (IaC) as part of infrastructure and operations (I&O) in your multi/hybrid cloud modern infrastructure. Containerized microservices deployed via Kubernetes allow you to save time, reduce human interaction and errors and create more robust world-scale cloud-native applications. Learn how to automate the most redundant activities such as reports, services, launching a pod, adding permanent storage, configuring load balancing, and adding or modifying any Kubernetes parameter. You’ll also look at end-to-end use cases and how advanced cluster automation (Helm packages and plugins, node states, etc.) is moving forward. Each lesson utilizes a specific use case for the modern Kubernetes cluster and focuses on a single module from the most crucial parameter with code Playbooknstrations and real-life usage. Each code example is battle-proven in real-life with console interaction... --- ## Ansible for Kubernetes Operators URL: https://www.ansiblebyexample.com/articles/ansible-kubernetes-operators-cluster-lifecycle-deployment Description: Manage Kubernetes clusters with Ansible. Automate cluster provisioning, application deployment, Helm charts, RBAC, and day-2 operations across. ## Introduction Kubernetes handles container orchestration. Ansible handles everything around it: provisioning clusters, bootstrapping namespaces, deploying Helm charts, managing RBAC, rotating secrets, and coordinating multi-cluster operations. While `kubectl` and Helm work for single-cluster manual operations, Ansible provides the automation layer for managing Kubernetes at enterprise scale — across dev, staging, and production clusters with consistent, auditable, repeatable deployments. ## Collections and Prerequisites [code example] | Collection | Key Modules | Purpose | |-----------|-------------|---------| | `kubernetes.core` | `k8s`, `k8s_info`, `helm`, `k8s_exec` | Core K8s resource management | | `amazon.aws` | `eks_cluster`, `eks_nodegroup` | AWS EKS provisioning | | `azure.azcollection` | `azure_rm_aks` | Azure AKS provisioning | | `google.cloud` | `gcp_container_cluster` | GCP GKE provisioning | ## Kubeconfig Management [code example] ## Pattern 1: Namespace and RBAC Bootstrap [code example] ## Pattern 2: Helm Chart Deployment [code example] ## Pattern 3: Rolling Deployment with Validation [code example] ## Pattern 4: Secret Management [code example] ## Pattern 5: Multi-Cluster Operations [code example] ## Troubleshooting ### Module Can't Find kubeconfig [code example] ### Timeout During Deployment [code example] ### RBAC Permission Denied [code example] ## Related Articles - Kubernetes Namespace with Ansible - Apply YAML to Kubernetes - K... --- ## Ansible for Network Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-network-engineers-complete-guide Description: Ansible network automation guide: Cisco, Arista, Juniper, configuration backup, compliance checking. Tested, copy-paste examples included. # Ansible for Network Engineers — Complete Guide ## Introduction Ansible network automation guide: Cisco, Arista, Juniper, configuration backup, compliance checking. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible network automation guide: Cisco, Arista, Juniper, configuration backup, compliance checking. Start with the fundamentals, i... --- ## Ansible for Physical AI and Robotics — Fleet and Edge Automation URL: https://www.ansiblebyexample.com/articles/ansible-physical-ai-robotics-fleet-edge Description: Automate physical AI and robotics infrastructure with Ansible. Deploy robot fleet software, edge AI models, ROS2, NVIDIA Isaac, and OTA updates. ## Introduction Physical AI — AI moving from screens into warehouses, factories, vehicles, and devices — is a defining 2026 trend. Gartner calls out physical AI, and Deloitte reports that enterprises are deploying robot fleets and autonomous production systems. Ansible manages the infrastructure behind these systems: edge device provisioning, ROS2 deployment, AI model distribution, fleet OTA updates, and monitoring. ## Edge Device Inventory [code example] ## Deploy ROS2 (Robot Operating System) [code example] ## Edge AI Model Deployment [code example] ## NVIDIA Jetson / Isaac Setup [code example] ## Fleet OTA Updates [code example] ## Edge Monitoring [code example] ## Related Articles - Ansible for Agentic AI - Ansible Docker Guide - Ansible systemd Module - Ansible Kubernetes Guide ## Conclusion Physical AI in 2026 means managing fleets of robots, drones, and edge devices at scale. Ansible handles the entire lifecycle: provisioning edge hardware (Jetson, Orin), deploying ROS2 and Isaac ROS, distributing AI models with integrity verification, performing rolling OTA updates with safety interlocks (`serial: 1`, maintenance mode), and monitoring GPU/sensor health. The key pattern: treat robots like servers — inventory them, configure them declaratively, update them safely. Ansible's agentless architecture is perfect for resource-constrained edge devices. --- ## Ansible for Platform Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-platform-engineers-complete-guide Description: Ansible in platform engineering: self-service automation, golden paths, and developer experience. With tested, real-world examples. # Ansible for Platform Engineers — Complete Guide ## Introduction Ansible in platform engineering: self-service automation, golden paths, and developer experience. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible in platform engineering: self-service automation, golden paths, and developer experience. Start with the fundamentals, implem... --- ## Ansible for Post-Quantum Cryptography — Migrate TLS and SSH Keys URL: https://www.ansiblebyexample.com/articles/ansible-post-quantum-cryptography-migrate-tls-ssh Description: Automate post-quantum cryptography migration with Ansible. Deploy PQC-ready TLS certificates, SSH keys, and crypto libraries across your fleet. ## Introduction NIST finalized three post-quantum cryptography (PQC) standards in 2024: ML-KEM (key encapsulation), ML-DSA (digital signatures), and SLH-DSA (stateless hash signatures). Organizations must migrate before quantum computers can break RSA and ECC. Ansible automates this migration across thousands of systems — updating crypto libraries, rotating certificates, reconfiguring SSH, and validating compliance. ## PQC Standards Quick Reference | Standard | NIST Name | Purpose | Replaces | |----------|-----------|---------|----------| | ML-KEM (CRYSTALS-Kyber) | FIPS 203 | Key encapsulation | RSA key exchange, ECDH | | ML-DSA (CRYSTALS-Dilithium) | FIPS 204 | Digital signatures | RSA signatures, ECDSA | | SLH-DSA (SPHINCS+) | FIPS 205 | Hash-based signatures | RSA, ECDSA (conservative) | ## Crypto Inventory Audit First, discover what crypto is deployed: [code example] ## Update Crypto Libraries [code example] ## Migrate SSH to Hybrid PQC [code example] ## Deploy PQC TLS Certificates [code example] ## PQC Compliance Validation [code example] ## Migration Roadmap Playbook [code example] [code example] ## Related Articles - Ansible Vault Guide - Ansible SSH Key Management - Ansible Nginx Guide - Ansible Security Best Practices ## Conclusion Post-quantum cryptography migration is a fleet-wide operation — exactly what Ansible excels at. Start with a crypto audit to inventory all RSA/ECC usage. Deploy PQC-capable libraries (liboqs, OQS provider). Migrate SS... --- ## Ansible for Preemptive Cybersecurity — Predictive Defense Automation URL: https://www.ansiblebyexample.com/articles/ansible-preemptive-cybersecurity-predictive-defense Description: Automate preemptive cybersecurity with Ansible. Deploy threat hunting, attack surface management, vulnerability scanning, and adaptive defense playbooks. ## Introduction Preemptive cybersecurity — shifting from reactive defense to predictive, continuously adaptive defense — is a Gartner 2026 strategic trend. Instead of waiting for attacks, organizations proactively hunt threats, reduce attack surfaces, and auto-remediate vulnerabilities. Ansible automates this entire cycle: scanning, hunting, hardening, and responding. ## Attack Surface Discovery [code example] ## Automated Vulnerability Scanning [code example] ## Threat Hunting Playbooks [code example] ## Auto-Remediation [code example] ## Scheduled Threat Hunting [code example] ## Related Articles - Ansible AI Security - Ansible Compliance as Code - Ansible SSH Key Management - Ansible Vault Guide ## Conclusion Preemptive cybersecurity in 2026 means automating the entire defense cycle: discover your attack surface (open ports, SUID binaries, exposed secrets), scan for vulnerabilities (outdated packages, expiring certificates), hunt threats proactively (cryptominers, reverse shells, unauthorized keys, suspicious crons), and auto-remediate (harden SSH, patch, enable auditing). Ansible turns security from a manual checklist into a continuous, automated process that runs daily across your entire fleet. --- ## Ansible for Quantum Computing — Provision Quantum Simulators and Hybrid Workflows URL: https://www.ansiblebyexample.com/articles/ansible-quantum-computing-simulators-hybrid-workflows Description: Automate quantum computing infrastructure with Ansible. Deploy quantum simulators, Qiskit/Cirq environments, hybrid quantum-classical pipelines. ## Introduction Quantum computing in 2026 is hitting real momentum — error-correction milestones, expanded access programs, and hybrid quantum-classical workloads moving from labs to enterprise use. Ansible automates the infrastructure side: provisioning quantum development environments, deploying simulators, managing hybrid pipelines, and preparing classical systems for quantum integration. ## Quantum Development Environment [code example] ## Quantum Simulator Cluster [code example] ## Hybrid Quantum-Classical Pipeline [code example] Backend config: [code example] ## Quantum Error Mitigation [code example] ## Quantum-Ready Network Configuration [code example] ## Related Articles - Ansible Post-Quantum Cryptography - Ansible AI Infrastructure - Ansible sysctl Module - Ansible pip Module ## Conclusion Quantum computing in 2026 is practical enough to automate. Ansible provisions quantum development environments (Qiskit, Cirq, PennyLane), deploys GPU-accelerated simulators for local testing, orchestrates hybrid quantum-classical pipelines with automatic backend routing (simulator for dev, IBM Quantum for production), manages error mitigation and calibration, and prepares networks for quantum-safe communication. The key pattern: abstract quantum hardware behind Ansible-managed services so teams can focus on algorithms, not infrastructure. --- ## Ansible for Security — CIS Benchmarks and Hardening URL: https://www.ansiblebyexample.com/articles/ansible-for-security-cis-benchmarks-and-hardening Description: Ansible for Security guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible for Security — CIS Benchmarks and Hardening ## Introduction CIS Benchmarks and Hardening. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted deviatio... --- ## Ansible for Security Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-security-engineers-complete-guide Description: Ansible for security: CIS hardening, vulnerability remediation, compliance auditing, and incident response. With tested, real-world examples. # Ansible for Security Engineers — Complete Guide ## Introduction Ansible for security: CIS hardening, vulnerability remediation, compliance auditing, and incident response. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible for security: CIS hardening, vulnerability remediation, compliance auditing, and incident response. Start with the ... --- ## Ansible for Site Reliability Engineers — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-site-reliability-engineers-complete-guide Description: Ansible for SRE: incident response automation, toil reduction, chaos engineering, and observability. With clear, copy-paste, step-by-step examples. # Ansible for Site Reliability Engineers — Complete Guide ## Introduction Ansible for SRE: incident response automation, toil reduction, chaos engineering, and observability. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible for SRE: incident response automation, toil reduction, chaos engineering, and observability. Start with the fundam... --- ## Ansible for Sovereign Cloud — Geopatriation and Data Residency Automation URL: https://www.ansiblebyexample.com/articles/ansible-sovereign-cloud-geopatriation-data-residency Description: Automate sovereign cloud and geopatriation requirements with Ansible. Enforce data residency, deploy regional infrastructure, and manage compliance across. ## Introduction Geopatriation — localizing data, compute, and cloud infrastructure for sovereignty and resilience — is a Gartner 2026 top-10 strategic trend. Countries mandate data residency (GDPR, China's PIPL, India's DPDPA), and enterprises need region-locked deployments. Ansible automates multi-region infrastructure provisioning, data residency enforcement, and compliance validation across sovereign tech stacks. ## Sovereign Infrastructure Inventory [code example] ## Enforce Data Residency [code example] [code example] ## Region-Locked Database Deployment [code example] ## Multi-Region Application Deploy [code example] ## Compliance Validation [code example] ## Sovereign Cloud Providers [code example] ## Related Articles - Ansible Compliance as Code - Ansible AWS Cloud - Ansible Post-Quantum Cryptography - Ansible Vault Guide ## Conclusion Sovereign cloud and geopatriation in 2026 mean enforcing data residency through infrastructure automation, not policies alone. Ansible makes data sovereignty deployable: region-tagged inventory, network-level residency enforcement, region-locked databases, sovereign backup destinations, and automated compliance audits. The pattern: define sovereignty requirements as variables per region, then let Ansible enforce them consistently across every host. As regulations tighten globally, this automation is what separates compliant organizations from audit failures. --- ## Ansible for System Administrators — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-system-administrators-complete-guide Description: Ansible fundamentals for sysadmins: server management, patching, user management, and monitoring setup. With clear, copy-paste, step-by-step examples. # Ansible for System Administrators — Complete Guide ## Introduction Ansible fundamentals for sysadmins: server management, patching, user management, and monitoring setup. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible fundamentals for sysadmins: server management, patching, user management, and monitoring setup. Start with the funda... --- ## Ansible For VMware By Examples book by Apress URL: https://www.ansiblebyexample.com/articles/ansible-for-vmware-by-examples-book-by-apress Description: Unlock the power of Ansible for VMware automation. This hands-on book teaches IT pros to efficiently manage VMware environments using Ansible, saving. {{}} ## Who This Book Is For IT professionals of the information technology who would like a jargon-free understanding of Ansible technology, including VMware, Linux, and Windows Systems Administrators, DevOps professionals, thought leaders, and infrastructure-as-code enthusiasts. ## Back Copy Cover Get a comprehensive, in-depth introduction to the Ansible language for the VMware infrastructure with this hands-on book. Learn how to save time and avoid human errors by efficiently automating your VMware infrastructure using the Ansible Open Source IT automation technology enabling Infrastructure as Code (IaC) for DevOps methodologies. It’s an ideal way to begin, whether you’re new to automation or a professional automation expert versed in other languages. Automate the most repetitive, boring, and error-prone chores such as the VMware virtual machines created from scratch and a template, start and stop using the shutdown and forced power-off, take and delete a snapshot, add a new hard disk and expand a currently attached hard disk, as well as generate report of information from data centers, clusters, host systems, and virtual machines. Great value with everyday chores time saving: file upload to datastore, VMware Guest Tools status and update, live Migration of a VMware Virtual Machine using vMotion. Baby steps, installation, and configuration are included for the most common operating system to interact with VMware vSphere using the latest Ansible collection and Python re... --- ## Ansible For VMware By Examples with Apress book URL: https://www.ansiblebyexample.com/articles/ansible-for-vmware-by-examples-with-apress-book Description: Ansible for VMware by Examples — the Apress book by Luca Berton. Automate VMware infrastructure with step-by-step Ansible playbook examples. {{}} ## Who This Book Is For IT professionals of the information technology who would like a jargon-free understanding of Ansible technology, including VMware, Linux, and Windows Systems Administrators, DevOps professionals, thought leaders, and infrastructure-as-code enthusiasts. ## Back Copy Cover Get a comprehensive, in-depth introduction to the Ansible language for the VMware infrastructure with this hands-on book. Learn how to save time and avoid human errors by efficiently automating your VMware infrastructure using the Ansible Open Source IT automation technology enabling Infrastructure as Code (IaC) for DevOps methodologies. It’s an ideal way to begin, whether you’re new to automation or a professional automation expert versed in other languages. Automate the most repetitive, boring, and error-prone chores such as the VMware virtual machines created from scratch and a template, start and stop using the shutdown and forced power-off, take and delete a snapshot, add a new hard disk and expand a currently attached hard disk, as well as generate report of information from data centers, clusters, host systems, and virtual machines. Great value with everyday chores time saving: file upload to datastore, VMware Guest Tools status and update, live Migration of a VMware Virtual Machine using vMotion. Baby steps, installation, and configuration are included for the most common operating system to interact with VMware vSphere using the latest Ansible collection and Python re... --- ## Ansible for VMware vSphere Automation — Enterprise Virtual Infrastructure Management URL: https://www.ansiblebyexample.com/articles/ansible-vmware-vsphere-enterprise-virtual-infrastructure Description: Automate VMware vSphere with Ansible. Provision VMs, manage templates, configure networking, handle snapshots, and orchestrate datacenter operations at. ## Introduction VMware vSphere remains the dominant virtualization platform in enterprise datacenters. Managing hundreds of VMs through the vSphere Client works for small environments, but enterprise operations — provisioning dev environments, enforcing snapshot policies, maintaining golden templates, and migrating workloads — need automation. Ansible's `community.vmware` collection provides 150+ modules covering every vSphere API operation, from VM lifecycle to distributed switch configuration. ## Setup ### Install the Collection [code example] ### Connection Variables [code example] ## Module Reference | Module | Purpose | |--------|---------| | `vmware_guest` | Create, clone, modify, delete VMs | | `vmware_guest_powerstate` | Start, stop, restart, suspend VMs | | `vmware_guest_snapshot` | Create, delete, revert snapshots | | `vmware_guest_disk` | Add, remove, resize disks | | `vmware_guest_network` | Manage VM network adapters | | `vmware_vm_inventory` | Dynamic inventory from vCenter | | `vmware_content_deploy_template` | Deploy from content library | | `vmware_dvswitch` | Manage distributed virtual switches | | `vmware_host` | ESXi host management | | `vmware_datastore_info` | Datastore capacity reporting | ## Pattern 1: VM Provisioning from Template [code example] ## Pattern 2: Golden Template Pipeline [code example] ## Pattern 3: Snapshot Management [code example] ## Pattern 4: Capacity Reporting [code example] ## Pattern 5: Dynamic Inventory from vCen... --- ## Ansible for Windows — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-windows-by-examples Description: Automate Windows systems with Ansible. Complete guide covering WinRM setup, Windows modules, file management, user administration, software deployment,. ## Introduction Ansible automates Windows servers just as effectively as Linux — managing configuration, deploying software, and orchestrating updates across your entire Windows fleet. Unlike Linux (which uses SSH), Windows automation uses **WinRM** (Windows Remote Management) for communication. ## Prerequisites ### WinRM Setup on Windows Targets Windows targets need WinRM enabled. Run this PowerShell script on each target: [code example] ### Ansible Controller Setup [code example] ### Inventory Configuration [code example] ### Verify Connectivity [code example] [code example] ## Essential Windows Modules | Module | Purpose | |--------|---------| | `win_ping` | Test connectivity | | `win_copy` | Copy files to Windows | | `win_file` | Manage files and directories | | `win_user` | Manage local users | | `win_group` | Manage local groups | | `win_service` | Manage Windows services | | `win_chocolatey` | Install software via Chocolatey | | `win_updates` | Manage Windows Updates | | `win_reboot` | Reboot Windows hosts | | `win_command` | Run commands | | `win_shell` | Run PowerShell commands | | `win_regedit` | Manage registry keys | | `win_feature` | Manage Windows features/roles | | `win_stat` | Get file information | | `win_template` | Deploy Jinja2 templates | | `win_get_url` | Download files | | `win_robocopy` | Robocopy file sync | | `win_scheduled_task` | Manage scheduled tasks | | `win_firewall_rule` | Manage firewall rules | | `win_dsc` | Apply DSC resources... --- ## Ansible for Windows Administrators — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-windows-administrators-complete-guide Description: Complete Ansible guide for Windows sysadmins: WinRM setup, AD management, patching, and GPO. With tested, real-world examples. # Ansible for Windows Administrators — Complete Guide ## Introduction Complete Ansible guide for Windows sysadmins: WinRM setup, AD management, patching, and GPO. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Complete Ansible guide for Windows sysadmins: WinRM setup, AD management, patching, and GPO. Start with the fundamentals, implement be... --- ## Ansible for Windows Enterprise Automation — Active Directory, GPO, and Fleet Management URL: https://www.ansiblebyexample.com/articles/ansible-windows-enterprise-active-directory-gpo-fleet-management Description: Automate Windows enterprise environments with Ansible. Manage Active Directory, Group Policy, IIS, Windows updates, registry, and fleet-wide configuration. ## Introduction Enterprise Windows environments are complex: Active Directory forests with dozens of OUs, Group Policy Objects layered across sites, IIS farms serving internal applications, SQL Server clusters, and thousands of endpoints needing patching. Ansible manages all of it without installing agents — using WinRM or SSH to connect, PowerShell under the hood, and the same playbook/role/inventory patterns as Linux automation. ## Setup ### WinRM Configuration on Windows Targets [code example] ### Ansible Control Node Configuration [code example] [code example] ### Collections [code example] ## Pattern 1: Active Directory Management ### Create OUs and Users [code example] ### Bulk User Import from CSV [code example] ## Pattern 2: Windows Update Management [code example] ## Pattern 3: IIS Web Server Management [code example] ## Pattern 4: Registry and Group Policy [code example] ## Pattern 5: Windows Fleet Inventory [code example] ## Troubleshooting ### WinRM Connection Failed [code example] ### CredSSP Authentication Errors [code example] ### PowerShell Execution Policy [code example] ## Related Articles - Configure Windows for Ansible - Test Windows: win_ping - Install Software with Chocolatey - Windows Registry Management - Copy Files to Windows ## Conclusion Enterprise Windows automation with Ansible covers the full stack: Active Directory management with `microsoft.ad`, Windows Updates with rolling patch windows, IIS deployment with app... --- ## Ansible Forks — Parallel Execution and Performance URL: https://www.ansiblebyexample.com/articles/ansible-forks-parallel-execution-and-performance Description: Configure Ansible forks for parallel task execution. Tune performance with forks, serial, throttle, and async for large-scale infrastructure automation. # Ansible Forks — Parallel Execution and Performance ## Introduction Ansible's `forks` setting controls how many hosts are managed simultaneously. The default is 5, meaning Ansible connects to 5 hosts at once, runs the task, then moves to the next 5. For large inventories, tuning forks (along with `serial`, `throttle`, and `async`) dramatically reduces execution time. ## Setting Forks ### ansible.cfg [code example] ### Command Line [code example] ### Environment Variable [code example] ## How Forks Work [code example] With `forks=20`, all hosts run Task 1 simultaneously, then all move to Task 2. ## Choosing the Right Value | Inventory Size | Recommended Forks | Notes | |---------------|-------------------|-------| | 1-10 hosts | 5 (default) | No tuning needed | | 10-50 hosts | 20-50 | Match inventory size | | 50-200 hosts | 50-100 | Watch controller memory | | 200-1000 hosts | 100-200 | Enable pipelining | | 1000+ hosts | 200-500 | Use pull mode or AWX | ## Performance Tuning Checklist [code example] ### SSH Pipelining Reduces SSH operations per task from 3 to 1: [code example] Requires `requiretty` disabled in `/etc/sudoers` on targets. ### SSH Multiplexing Reuse SSH connections: [code example] ### Fact Caching Avoid re-gathering facts every run: [code example] ## Forks vs Serial vs Throttle [code example] | Setting | Controls | Scope | |---------|----------|-------| | `forks` | Max parallel SSH connections | Global | | `serial` | Hosts per batch... --- ## Ansible FQCN — Fully Qualified Names URL: https://www.ansiblebyexample.com/articles/fqcn-in-ansible-fully-qualified-collection-names-explained Description: Write Ansible playbooks with FQCN. Understand namespace.collection.module format, why ansible-lint enforces it, and how to migrate from short module names. ## What is FQCN? **FQCN** stands for **Fully Qualified Collection Name**. It's the complete, unambiguous way to reference any module, plugin, or role in Ansible. The format is: [code example] For example: | Short name | FQCN | |------------|------| | `copy` | `ansible.builtin.copy` | | `yum` | `ansible.builtin.yum` | | `docker_container` | `community.docker.docker_container` | | `vmware_guest` | `community.vmware.vmware_guest` | | `k8s` | `kubernetes.core.k8s` | ## Why Use FQCN? ### 1. Avoid Ambiguity Multiple collections can provide modules with the same short name. Using FQCN ensures Ansible uses exactly the module you intend: [code example] ### 2. Required by ansible-lint Since Ansible 2.10+, `ansible-lint` enforces FQCN usage with the `fqcn` rule. Running `ansible-lint` on playbooks with short names will produce warnings: [code example] ### 3. Future-Proof Your Playbooks As the Ansible ecosystem grows, more collections will be added. FQCN protects your playbooks from naming conflicts. ## Common FQCN Examples ### ansible.builtin (core modules) [code example] ### community collections [code example] ### cloud collections [code example] ## How to Find the FQCN for a Module ### Method 1: ansible-doc [code example] ### Method 2: Check the Ansible documentation Visit docs.ansible.com and search for the module. The FQCN is shown at the top of every module page. ### Method 3: Use ansible-lint auto-fix [code example] ## Converting Existing Playbooks to... --- ## Ansible FQCN Guide — Fully Qualified Collection Names Explained URL: https://www.ansiblebyexample.com/articles/ansible-fqcn-fully-qualified-collection-names-guide Description: Learn what FQCN means in Ansible, why you should use fully qualified collection names, and how to migrate from short module names to FQCN format. ## Introduction FQCN stands for **Fully Qualified Collection Name** — the complete namespace path to an Ansible module, plugin, or role. Instead of writing `copy`, you write `ansible.builtin.copy`. Instead of `yum`, you write `ansible.builtin.yum`. This isn't just pedantic naming — it's how Ansible resolves which code actually runs when you call a module. Since Ansible 2.10, all modules live inside collections. The short names (`copy`, `file`, `template`) still work as aliases, but they're ambiguous — if two collections provide a module with the same name, Ansible picks one and you might not get the one you expected. ## FQCN Format [code example] **Examples:** | Short Name | FQCN | Collection | |-----------|------|------------| | `copy` | `ansible.builtin.copy` | Built-in | | `file` | `ansible.builtin.file` | Built-in | | `template` | `ansible.builtin.template` | Built-in | | `yum` | `ansible.builtin.yum` | Built-in | | `apt` | `ansible.builtin.apt` | Built-in | | `service` | `ansible.builtin.service` | Built-in | | `debug` | `ansible.builtin.debug` | Built-in | | `uri` | `ansible.builtin.uri` | Built-in | | `win_copy` | `ansible.windows.win_copy` | Windows | | `win_file` | `ansible.windows.win_file` | Windows | | `vmware_guest` | `community.vmware.vmware_guest` | VMware | | `postgresql_db` | `community.postgresql.postgresql_db` | PostgreSQL | | `k8s` | `kubernetes.core.k8s` | Kubernetes | | `ec2_instance` | `amazon.aws.ec2_instance` | AWS | | `mount` | `ansible.posix.m... --- ## Ansible from_json and to_json — Parse and Generate JSON URL: https://www.ansiblebyexample.com/articles/ansible-from-json-to-json-parse-and-generate-json-data Description: Parse JSON strings and generate JSON output in Ansible with from_json and to_json filters. Handle API responses, config files, and data transformations. # Ansible from_json and to_json — Parse and Generate JSON ## Introduction Ansible's `from_json` and `to_json` filters convert between JSON strings and native data structures. Use `from_json` to parse API responses and command output. Use `to_json` to generate JSON for API calls and config files. Both are essential for working with REST APIs and JSON-based tools. ## Quick Reference [code example] ## from_json — Parse JSON Strings [code example] ### Parse API Response [code example] ### Parse JSON from Shell Output [code example] ## to_json — Generate JSON Strings [code example] ### Send JSON to API [code example] ## to_nice_json — Pretty Print [code example] ## from_yaml and to_yaml [code example] ## Common Patterns ### Filter JSON Array [code example] ### Extract Nested Values [code example] ### Merge JSON Objects [code example] ### JSON Patch (Modify and Write Back) [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | `Expecting value: line 1` | Input isn't valid JSON | Verify with `echo '$var' \| jq .` | | `dict object has no attribute` | Key doesn't exist in parsed JSON | Use `default()` filter: `data.key \| default('')` | | `list object has no attribute` | JSON is array, not object | Access with index: `data[0].key` | | `to_json outputs single quotes` | Jinja2 native string | Use `\| string \| to_json` | | Unicode escape in output | Default encoding | Use `ensure_ascii=False`: `to_json(ensure_ascii=False)` | ## ... --- ## Ansible Galaxy — Create and Publish Roles and Collections URL: https://www.ansiblebyexample.com/articles/ansible-galaxy-create-publish-roles-collections Description: Create and publish Ansible roles and collections to Galaxy. Complete guide to role structure, collection scaffolding, galaxy.yml metadata, testing with. ## Introduction Ansible Galaxy is the community hub for sharing Ansible roles and collections. This guide covers creating your own roles and collections from scratch, testing them with Molecule and ansible-lint, and publishing to Galaxy (public) or Private Automation Hub (enterprise). Whether you're packaging internal automation for your team or contributing to the community, this is the complete workflow. ## Roles vs Collections | Feature | Role | Collection | |---|---|---| | Contains | Tasks, handlers, templates, vars | Roles + modules + plugins + docs | | Namespace | `username.role_name` | `namespace.collection_name` | | Install | `ansible-galaxy role install` | `ansible-galaxy collection install` | | Versioning | Git tags | `galaxy.yml` version field | | Dependencies | `meta/main.yml` | `galaxy.yml` + `requirements.yml` | | Publish to | Galaxy (role) | Galaxy (collection) or Automation Hub | **Use collections** for anything with custom modules, plugins, or multiple roles. Use standalone roles for simple, single-purpose automation. ## Create a Role ### Scaffold [code example] ### Structure [code example] ### defaults/main.yml [code example] ### tasks/main.yml [code example] ### handlers/main.yml [code example] ### meta/main.yml [code example] ### README.md [code example] ## Create a Collection ### Scaffold [code example] ### Structure [code example] ### galaxy.yml [code example] ### Custom Module [code example] ## Test Before Publishing [code ... --- ## Ansible Galaxy — Install and Share Roles and Collections URL: https://www.ansiblebyexample.com/articles/ansible-galaxy-install-share-roles-collections Description: Use Ansible Galaxy to install, create, and share roles and collections. Requirements files, private repos, and managing dependencies for your automation. ## Introduction Ansible Galaxy is the package manager for Ansible content — install community roles and collections from galaxy.ansible.com, create your own, and share them. Collections bundle roles, modules, plugins, and playbooks into distributable packages. ## Install a Role [code example] Use in a playbook: [code example] ## Install a Collection [code example] ## Requirements File Define all dependencies in one file: [code example] [code example] ## Create a Role [code example] ### Minimal Role Example [code example] ## Create a Collection [code example] [code example] [code example] ## Install from Git [code example] ## Install from Private Galaxy / Automation Hub [code example] ## Project Structure [code example] ## Popular Collections | Collection | Purpose | |-----------|---------| | `community.general` | General utilities, system modules | | `ansible.posix` | POSIX system modules | | `amazon.aws` | AWS resources | | `azure.azcollection` | Azure resources | | `google.cloud` | GCP resources | | `community.docker` | Docker management | | `community.kubernetes` | Kubernetes/K8s | | `community.mysql` | MySQL management | | `community.postgresql` | PostgreSQL management | | `ansible.netcommon` | Network automation base | | `cisco.ios` | Cisco IOS devices | ## Troubleshooting ### "Role not found" Check the roles path: [code example] ### Version Conflicts [code example] ### "Collection not found" in Playbook Use the FQCN (fully qualified co... --- ## Ansible Galaxy Complete Guide: Roles, Collections, and Best Practices URL: https://www.ansiblebyexample.com/articles/introducing-the-new-ansible-galaxy Description: Complete guide to Ansible Galaxy. Learn how to find, install, create, and publish roles and collections. Includes CLI commands, requirements files. Ansible Galaxy is the official community hub for finding, sharing, and reusing Ansible roles and collections. It is the primary way Ansible users distribute reusable automation content, with thousands of roles and collections covering everything from package management to cloud provisioning. ## What Is Ansible Galaxy? Ansible Galaxy serves two purposes: 1. **A website** (galaxy.ansible.com) where you browse, search, and download community-contributed automation content 2. **A CLI tool** (`ansible-galaxy`) that installs, creates, and manages roles and collections from the command line ### Roles vs Collections | Feature | Roles | Collections | |---------|-------|-------------| | **Content** | Tasks, handlers, templates, variables | Modules, plugins, roles, playbooks | | **Namespace** | `author.role_name` | `namespace.collection_name` | | **Install location** | `~/.ansible/roles/` | `~/.ansible/collections/` | | **Versioning** | Git tags | Semantic versioning | | **Dependencies** | `meta/main.yml` | `galaxy.yml` | | **Recommended for** | Single-purpose reusable task sets | Multi-component automation packages | **Collections are the modern standard.** Red Hat and the Ansible community have shifted from standalone roles to collections, which bundle modules, plugins, and roles together. ## Installing Content from Galaxy ### Install a Role [code example] ### Install a Collection [code example] ### Requirements Files For reproducible environments, use a `requirements.yml... --- ## Ansible Galaxy Init — Role Scaffolding URL: https://www.ansiblebyexample.com/articles/ansible-galaxy-init-create-role-and-collection-scaffolding Description: Use ansible-galaxy init to create role and collection directory structures. Generate scaffolding for roles, collections, and best-practice project layouts. # Ansible Galaxy Init — Create Role and Collection Scaffolding ## Introduction `ansible-galaxy init` generates the complete directory structure for Ansible roles and collections. Instead of manually creating 8+ directories and placeholder files, one command sets up the standard layout with `tasks/main.yml`, `defaults/main.yml`, `handlers/main.yml`, `meta/main.yml`, README, and test files — ready for you to fill in. ## Create a Role [code example] ### Generated Structure [code example] ### Fill in the Role [code example] ## Create a Collection [code example] ### Generated Structure [code example] ### galaxy.yml [code example] ## Install Roles and Collections [code example] ### requirements.yml [code example] ## Project Layout Best Practices [code example] ## List and Manage Roles [code example] ## Build and Publish Collections [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "directory already exists" | Use `--force` to overwrite | | Role not found after install | Check `roles_path` in `ansible.cfg` | | Collection not found | Run `ansible-galaxy collection list` to verify install path | | Version conflict | Pin versions in `requirements.yml` | | "permission denied" on install | Use `--roles-path` for local install | ## Best Practices 1. **Always use `init`** — don't create role directories manually 2. **Fill in `meta/main.yml`** — platforms, dependencies, and tags 3. **Use `requirements.yml`** — pin versions for reproduc... --- ## Ansible Galaxy Install Failure — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-galaxy-install-failure-fix-and-solutions Description: Resolve Galaxy collection and role installation failures and timeouts. Tested on real machines with clear, copy-paste examples. # Ansible Galaxy Install Failure — Fix and Solutions ## Introduction Resolve Galaxy collection and role installation failures and timeouts. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve Galaxy collection and role installation failures and timeouts. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Galaxy Roles — GitHub Actions URL: https://www.ansiblebyexample.com/articles/automate-ansible-galaxy-roles-with-github-actions Description: Learn how to automate infrastructure with Ansible Galaxy roles in GitHub Actions. Use Datadog for seamless monitoring integration. In modern DevOps practices, automation plays a crucial role in managing infrastructure, and tools like Ansible and GitHub Actions are essential for automating tasks such as configuration management and continuous integration. A common scenario might involve integrating monitoring solutions like Datadog with your infrastructure, and one way to achieve this is by using Ansible Galaxy roles within GitHub Actions. In this article, we'll walk through the process of importing an Ansible Galaxy role into a GitHub Action workflow. We'll use Datadog as an example, showing how you can automate the installation of monitoring agents across your infrastructure. ## Step-by-Step Guide to Using Ansible Galaxy Roles in GitHub Actions ### 1. Install the Datadog Role from Ansible Galaxy Ansible Galaxy is a public repository of roles and playbooks that you can use to automate various aspects of IT infrastructure. For our example, we'll be using the `cloin.datadog` role, which provides all the configurations necessary to set up Datadog agents on your systems. To install the Datadog role locally, run: [code example] This downloads the latest version of the role from Ansible Galaxy. If you want to install it to a specific directory, such as a `roles/` folder in your repository, you can add the `-p` option: [code example] This step ensures that your Ansible environment has the role ready to use in your playbooks. ### 2. Create a GitHub Workflow GitHub Actions allow you to automate tasks d... --- ## Ansible Galaxy: Install & Manage Roles & Collections URL: https://www.ansiblebyexample.com/articles/ansible-galaxy-install-manage-roles-collections Description: Ansible Galaxy: install and manage community roles and collections. Learn ansible-galaxy CLI, requirements.yml, versioning, and create your own roles. ## What Is Ansible Galaxy? Ansible Galaxy is the community hub for sharing Ansible roles and collections. Instead of writing everything from scratch, install pre-built roles for common tasks — Nginx, Docker, PostgreSQL, Kubernetes — and collections for vendor-specific modules (AWS, Azure, VMware). The `ansible-galaxy` CLI manages installation, versioning, and dependency resolution. ## Install a Role [code example] Use in a playbook: [code example] ## Install a Collection [code example] ## Requirements File Define all dependencies in one file and install them together: `requirements.yml`: [code example] Install everything: [code example] ## List Installed [code example] ## Remove [code example] ## Create Your Own Role [code example] This creates: [code example] ### Example Role `roles/myapp/tasks/main.yml`: [code example] `roles/myapp/defaults/main.yml`: [code example] Use in a playbook: [code example] ## Collection Structure [code example] [code example] ## Common Collections | Collection | Purpose | |-----------|---------| | `ansible.builtin` | Core modules (included) | | `ansible.posix` | POSIX systems (mount, sysctl, cron) | | `community.general` | General community modules | | `community.postgresql` | PostgreSQL management | | `community.docker` | Docker containers | | `community.vmware` | VMware vSphere | | `amazon.aws` | AWS resources | | `azure.azcollection` | Azure resources | | `google.cloud` | GCP resources | | `kubernetes.core` | Kuber... --- ## Ansible Gather and Report Facts — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-gather-and-report-facts-complete-guide Description: Collect system information and generate reports with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Gather and Report Facts. # Ansible Gather and Report Facts — Complete Guide ## Introduction Collect system information and generate reports with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Collect system information and generate reports with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Gathering Facts Failure — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-gathering-facts-failure-fix-and-solutions Description: Fix facts gathering failures from timeout, permission, and subset issues. With clear, copy-paste, step-by-step examples. # Ansible Gathering Facts Failure — Fix and Solutions ## Introduction Fix facts gathering failures from timeout, permission, and subset issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix facts gathering failures from timeout, permission, and subset issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible GCP Compute — Google Cloud Instances URL: https://www.ansiblebyexample.com/articles/ansible-gcp-compute-google-cloud-instances Description: Ansible GCP Compute guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible GCP Compute — Google Cloud Instances ## Introduction Google Cloud Instances. Automate GCP infrastructure with Ansible using the `google.cloud` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches GCP naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/product... --- ## Ansible gcp_compute_instance Module — Manage GCP Compute Engine VMs URL: https://www.ansiblebyexample.com/articles/ansible-gcp-compute-instance-module-manage-gcp-compute-engine-vms Description: Create and manage Google Cloud virtual machine instances with Ansible. Hands-on, tested examples and best practices for Ansible gcp_compute_instance Module. # Ansible gcp_compute_instance Module — Manage GCP Compute Engine VMs ## Introduction The `google.cloud.gcp_compute_instance` module create and manage Google Cloud virtual machine instances with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install google.cloud` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `google.cloud.gcp_compute_instance` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in c... --- ## Ansible gcp_compute_network Module — Manage GCP VPC Networks URL: https://www.ansiblebyexample.com/articles/ansible-gcp-compute-network-module-manage-gcp-vpc-networks Description: Create and configure Google Cloud VPC networks and subnets with Ansible. Hands-on, tested examples and best practices for Ansible gcp_compute_network Module. # Ansible gcp_compute_network Module — Manage GCP VPC Networks ## Introduction The `google.cloud.gcp_compute_network` module create and configure Google Cloud VPC networks and subnets with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install google.cloud` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `google.cloud.gcp_compute_network` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mo... --- ## Ansible gcp_storage_bucket Module — Manage GCP Cloud Storage Buckets URL: https://www.ansiblebyexample.com/articles/ansible-gcp-storage-bucket-module-manage-gcp-cloud-storage-buckets Description: Create and configure Google Cloud Storage buckets with Ansible automation. Hands-on, tested examples and best practices for Ansible gcp_storage_bucket Module. # Ansible gcp_storage_bucket Module — Manage GCP Cloud Storage Buckets ## Introduction The `google.cloud.gcp_storage_bucket` module create and configure Google Cloud Storage buckets with Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install google.cloud` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `google.cloud.gcp_storage_bucket` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in ... --- ## Ansible get_url — Download Files URL: https://www.ansiblebyexample.com/articles/ansible-get-url-module-download-files-from-urls Description: Download files from URLs with ansible.builtin.get_url. Working examples with checksum verification, authentication, proxy support, headers, and timeout. ## The ansible.builtin.get_url Module The `get_url` module downloads files from HTTP, HTTPS, and FTP URLs to remote hosts — like `wget` or `curl`, but idempotent and integrated with Ansible. ## Basic Download [code example] ## Download with Checksum Verification [code example] ## Set Permissions [code example] ## Download with Authentication ### Basic Auth [code example] ### Bearer Token [code example] ## Proxy Support [code example] ## Conditional Download [code example] ## Practical Examples ### Install Binary from GitHub Release [code example] ### Download and Extract [code example] ### Download Multiple Files [code example] ### Download with Timeout and Retries [code example] ## Windows: win_get_url For Windows hosts, use `ansible.windows.win_get_url`: [code example] ## Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `url` | Source URL | `https://example.com/file` | | `dest` | Destination path | `/tmp/file` | | `checksum` | Verify integrity | `sha256:abc123...` | | `mode` | File permissions | `'0755'` | | `owner` | File owner | `deploy` | | `group` | File group | `deploy` | | `force` | Re-download if exists | `true` | | `timeout` | Download timeout (sec) | `300` | | `headers` | Custom HTTP headers | `{Authorization: "Bearer ..."}` | | `url_username` | Basic auth username | `admin` | | `url_password` | Basic auth password | `secret` | | `validate_certs` | Verify SSL | `true` | --- *Browse 800+ Ansible... --- ## Ansible get_url — Download Files via HTTPS Proxy URL: https://www.ansiblebyexample.com/articles/download-a-file-using-an-https-proxy-via-environment-variables-working-with-proxies-ansible-environment-statement Description: Learn how to download files using Ansible get_url module with proxy settings, including checksum verification and setting file permissions. ## How to download a file using an HTTPS proxy via environment variables with Ansible? ## Download a file using an https proxy via env variables - `get_url` module - `http_proxy` and `https_proxy` environment The easiest way to download a file using an HTTPS proxy is via the `get_url` Ansible module and the environment variables. You could set the remote proxy via the `http_proxy` and `https_proxy` remote environment using the Ansible statement `environment`. This applies respectively to HTTP and HTTPS connections. The Ansible `environment` statement could be applied at the task level or play level. ## Playbook Download a file using an HTTPS proxy via environment variables with Ansible Playbook. The following scenario uses the HTTPS proxy server `http://proxy.example.com:3128`. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] [code example] code with ❤️ in GitHub ## Conclusion Now you know how to use HTTPS proxy using environment variables with Ansible Playbook. --- ## Ansible get_url Module — Download Files from URLs URL: https://www.ansiblebyexample.com/articles/download-a-file-ansible-module-get-url Description: Download files from HTTP, HTTPS, and FTP with ansible.builtin.get_url. Checksum verification, authentication, headers, retries, and timeout examples. ## Introduction Downloading files from remote URLs is a common automation task — installing software, fetching artifacts, pulling configuration files, or retrieving API responses. The `ansible.builtin.get_url` module handles HTTP, HTTPS, and FTP downloads with built-in checksum verification, authentication, and proxy support. In this guide, you'll learn how to use `get_url` effectively for all download scenarios, from simple file fetches to authenticated artifact retrieval with integrity verification. ## The ansible.builtin.get_url Module The full module name is `ansible.builtin.get_url`, part of ansible-core. It downloads files from a URL to the remote filesystem. For Windows targets, use `ansible.windows.win_get_url` instead. ### Key Characteristics - Downloads from **HTTP**, **HTTPS**, and **FTP** protocols - **Idempotent** — only downloads if file is missing or checksum differs - Supports **checksum verification** (SHA256, SHA1, MD5) - Handles **authentication** (basic, token, GSSAPI/Kerberos) - Supports **custom headers** and proxy configuration - Sets file **permissions**, **owner**, and **SELinux context** ## Parameters Reference | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `url` | string | Yes | — | URL to download | | `dest` | path | Yes | — | Absolute path for downloaded file | | `checksum` | string | No | — | `algorithm:hash` or `algorithm:url` | | `mode` | string | No | — | File permissio... --- ## Ansible getent Module — Query System Databases URL: https://www.ansiblebyexample.com/articles/ansible-getent-module-query-system-databases Description: Ansible getent Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible getent Module — Query System Databases ## Introduction Query System Databases. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible getent Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective... --- ## Ansible git Module — Clone and Manage Git Repositories URL: https://www.ansiblebyexample.com/articles/ansible-git-module-clone-manage-repositories Description: Use the Ansible git module to clone repos, checkout branches, pull updates, and deploy code from Git. SSH keys, tags, and deployment patterns. ## Introduction `ansible.builtin.git` clones and manages Git repositories on remote hosts. Deploy code, checkout specific branches or tags, pull updates, and handle SSH authentication — all idempotently. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `repo` | (required) | Repository URL (HTTPS or SSH) | | `dest` | (required) | Local path to clone into | | `version` | `HEAD` | Branch, tag, or commit hash | | `clone` | `true` | Clone if dest doesn't exist | | `update` | `true` | Pull updates if already cloned | | `force` | `false` | Discard local changes | | `depth` | — | Shallow clone depth | | `single_branch` | `false` | Only fetch the specified branch | | `key_file` | — | SSH private key path | | `accept_hostkey` | `false` | Accept unknown SSH host keys | | `bare` | `false` | Create bare repository | | `recursive` | `true` | Initialize submodules | | `track_submodules` | `false` | Track latest submodule commits | | `refspec` | — | Custom refspec | | `ssh_opts` | — | Extra SSH options | ## Checkout Branches and Tags [code example] ## Practical Patterns ### Code Deployment [code example] ### Shallow Clone (Faster) [code example] ### Release-Based Deployment [code example] ### SSH Agent Forwarding [code example] ### Deploy Key Setup [code example] ### Configuration Repository [code example] ## Register Output [code example] ## Troubleshooting ### "Permission denied (publickey)" S... --- ## Ansible git_config Module — Manage Git Configuration Settings URL: https://www.ansiblebyexample.com/articles/ansible-git-config-module-manage-git-configuration-settings Description: Set and query git config values (global, system, local) with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible git_config Module — Manage Git Configuration Settings ## Introduction The `community.general.git_config` module set and query git config values (global, system, local) with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.git_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** ... --- ## Ansible github_release Module — Manage GitHub Releases URL: https://www.ansiblebyexample.com/articles/ansible-github-release-module-manage-github-releases Description: Create and query GitHub releases, download assets, and manage release tags. Hands-on, tested examples and best practices for Ansible github_release Module. # Ansible github_release Module — Manage GitHub Releases ## Introduction The `community.general.github_release` module create and query GitHub releases, download assets, and manage release tags. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.github_release` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check ... --- ## Ansible GitOps with ArgoCD — Infrastructure as Code Delivery URL: https://www.ansiblebyexample.com/articles/ansible-gitops-argocd-infrastructure-delivery Description: Implement GitOps with Ansible and ArgoCD. Deploy ArgoCD on Kubernetes, manage Ansible playbook execution from Git, integrate with Automation Controller. ## Introduction GitOps treats Git as the single source of truth for infrastructure and application state. ArgoCD watches Git repositories and automatically syncs Kubernetes resources when changes are pushed. Ansible extends this pattern beyond Kubernetes — managing servers, networks, cloud resources, and configurations. This guide covers deploying ArgoCD with Ansible, triggering Ansible runs from Git changes, and building a complete GitOps pipeline. ## GitOps Principles 1. **Declarative** — desired state described in Git 2. **Versioned** — every change has a Git commit 3. **Automated** — changes in Git trigger deployment 4. **Self-healing** — drift is automatically corrected ## Deploy ArgoCD with Ansible [code example] ## Register Applications in ArgoCD [code example] ## GitOps for Ansible Playbooks ### Pattern 1: Webhook Triggers [code example] ### Pattern 2: ansible-pull (Self-Healing) [code example] ### Pattern 3: CI/CD Pipeline (GitHub Actions) [code example] ## Complete GitOps Pipeline [code example] ### Implementation [code example] ## Drift Detection [code example] Schedule drift detection every hour: [code example] ## ArgoCD + Ansible Operator For running Ansible from ArgoCD directly: [code example] ## Secrets Management [code example] ## Best Practices 1. **Single repo per concern** — separate repos for K8s manifests, Ansible playbooks, application code 2. **Branch protection on main** — require reviews before merge 3. **Automated testing... --- ## Ansible GitOps Workflow — ArgoCD and Flux Integration URL: https://www.ansiblebyexample.com/articles/ansible-gitops-workflow-argocd-and-flux-integration Description: Ansible GitOps Workflow guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible GitOps Workflow — ArgoCD and Flux Integration ## Introduction ArgoCD and Flux Integration. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible GitOps Workflow requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible GlusterFS — Deploy Distributed File Storage URL: https://www.ansiblebyexample.com/articles/ansible-glusterfs-distributed-file-storage Description: Deploy GlusterFS distributed file storage with Ansible. Trusted pool setup, replicated and distributed volumes, geo-replication, client mounting,. ## Introduction GlusterFS is a scalable distributed file system that aggregates storage from multiple servers into a single namespace. Ansible automates cluster setup — install GlusterFS, form trusted pools, create replicated or distributed volumes, mount on clients, configure geo-replication, and manage snapshots. ## Deploy GlusterFS Cluster [code example] ## Volume Types ### Distributed Volume (striped across nodes) [code example] ### Distributed-Replicated Volume [code example] ### Arbiter Volume (saves space) [code example] ## Mount on Clients [code example] ## Performance Tuning [code example] ## Snapshots [code example] ## Geo-Replication [code example] ## Health Check [code example] ## Troubleshooting ### Heal Volume [code example] ## Related Articles - Ansible Ceph Storage - Ansible MinIO S3 Storage - Ansible NFS Module - Ansible Samba File Sharing ## Conclusion GlusterFS provides distributed file storage without a single point of failure — Ansible automates the entire cluster lifecycle using the `gluster.gluster` collection. Form trusted pools, create replicated volumes for HA, distributed volumes for capacity, tune performance, manage snapshots, and set up geo-replication for DR. All storage configuration lives in your playbooks alongside the applications that consume it. --- ## Ansible google.cloud Collection Example: Automate Compute and Secret Manager URL: https://www.ansiblebyexample.com/articles/ansible-google-cloud-collection-example-automate-compute-and-secret-manager Description: Runnable Ansible playbook example using the google.cloud collection to provision Compute instances and manage Secret Manager secrets on GCP. At Red Hat Tech Day Netherlands 2026 (3 June 2026, Bunnik), the Ansible team announced 12 new content collections landing in AAP 2.7. Among them, `google.cloud` gets refreshed content spanning Cloud Build 2nd gen, Parameter Manager, Compute, Secret Manager, and Storage. Below is a runnable playbook that provisions a Compute instance and reads a Secret Manager secret to bootstrap it. ## Example playbook [code example] ## What it does and why The first task reads the current version of a Secret Manager secret using `gcp_secret_manager_secret_version_info`, which is the pattern the refreshed `google.cloud` collection standardizes on for read-only secret lookups — no need to shell out to `gcloud` or hardcode credentials in a vars file. The second task uses `gcp_compute_instance` to create a Debian-based VM, passing the secret's payload into instance metadata so a startup script on the VM can retrieve it locally. This mirrors a common pattern: keep application secrets in Secret Manager, and let the automation layer inject just-in-time values at provisioning time rather than baking them into images or playbooks. Both modules authenticate with a service account JSON key file via `auth_kind: serviceaccount`, which is the standard approach for unattended AAP job execution — you'd typically store `gcp_cred_file` as a machine credential in AAP rather than a plain playbook variable. ## Notes - Module names shown (`gcp_compute_instance`, `gcp_secret_manager_secret_version_info`) fo... --- ## Ansible GPG Signature Verification URL: https://www.ansiblebyexample.com/articles/project-signature-verification-with-gpg-and-ansible-sign Description: Learn how to GPG-sign an Ansible project using the ansible-sign command line tool. Watch a live Playbook by Luca Berton and transform your project from. ## How to verify an Ansible project signature? A step to step guide to verify the signature using the `ansible-sign` of a GPG-signed Ansible project. ## ansible-sign - available since 2022 - command line - GPG signature The `ansible-sign` command has been available since 2022 for installation in the most modern operating system. It is a command line tool so simplify the Project signing process using your terminal. Using the `ansible-sign` command, we can verify the GPG signature of an Ansible project. ## Playbook - GPG sign verification a project I'm going to show you how to verify the signature of an Ansible project using the ansible-sign command line utility. At the beginning of this example, we start with a project with all our Ansible files already signed with a GPG signature. By the end of this Playbook, we will verify if the signature is correct for the current Ansible project directory. Project directory files: - playbooks/ping.yml [code example] - inventory [code example] - MANIFEST.in [code example] Project signature files: - `.ansible-sign/sha256sum.txt` [code example] - `.ansible-sign/sha256sum.txt.sig` [code example] ### 1. install ansible-sign Verify if the ansible-sign command is available in your terminal. When you obtain a command not found error, you should install it. [code example] When the package is not available on our favorite package manager (apt, DNF, yum, zypper, brew, conda), we can rely on the PIP Python package manager: `$ ... --- ## Ansible Grafana Loki Log Aggregation URL: https://www.ansiblebyexample.com/articles/ansible-grafana-loki-log-aggregation-promtail Description: Deploy Grafana Loki and Promtail with Ansible for scalable log aggregation, multi-tenant storage, LogQL queries, and alerting # Ansible Grafana Loki Log Aggregation Grafana Loki is a horizontally-scalable log aggregation system inspired by Prometheus. Unlike Elasticsearch, Loki indexes only metadata (labels) rather than full log content, making it dramatically cheaper to operate at scale. ## Why Loki over Elasticsearch | Feature | Loki | Elasticsearch | |---------|------|---------------| | Storage cost | Low (compressed chunks) | High (full-text index) | | Resource usage | Minimal (no indexing) | Heavy (JVM, RAM) | | Query language | LogQL (PromQL-like) | Lucene/KQL | | Label-based filtering | Native | Via fields | | Grafana integration | Native | Plugin | ## Architecture Overview [code example] ## Loki Deployment Playbook [code example] ## Loki Configuration Template `templates/loki-config.yaml.j2`: [code example] ## Promtail Agent Deployment [code example] ## Promtail Configuration Template `templates/promtail-config.yaml.j2`: [code example] ## Loki Alerting Rules [code example] ## Grafana Data Source Configuration [code example] ## Multi-Tenant Configuration [code example] Update Promtail to send tenant header: [code example] ## Troubleshooting | Problem | Cause | Solution | |---------|-------|----------| | Promtail not shipping logs | Permission denied on log files | Run Promtail as root or add to adm group | | "entry out of order" errors | Clock skew between hosts | Sync NTP, or enable `unordered_writes` | | High memory usage in Loki | Too many active streams | Reduce l... --- ## Ansible grafana_dashboard Module — Manage Grafana Dashboards URL: https://www.ansiblebyexample.com/articles/ansible-grafana-dashboard-module-manage-grafana-dashboards Description: Import, export, and manage Grafana dashboards programmatically with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible grafana_dashboard Module — Manage Grafana Dashboards ## Introduction The `community.grafana.grafana_dashboard` module import, export, and manage Grafana dashboards programmatically with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.grafana` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.grafana.grafana_dashboard` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **T... --- ## Ansible group Module — Create & Manage Linux Groups URL: https://www.ansiblebyexample.com/articles/create-a-group-ansible-module-group Description: Create, modify, and remove Linux groups with ansible.builtin.group. Set GID, system groups, and manage group membership with playbook examples. ## How to create a group in Linux with Ansible? ## Ansible creates a group > `ansible.builtin.group` Add or remove groups Today we're talking about the Ansible module group. The full name is `ansible.builtin.group`, which means that is part of the collection of modules "builtin" with Ansible and shipped with it. It's a module pretty stable and out for years. It adds or removes groups. It supports a huge variety of Linux distributions and macOS. It relies on three Linux commands: `groupadd`, `groupdel` and `groupmod`. For Windows, use the `ansible.windows.win_group` module instead. ## Parameters - `name` string - group name - `state` string - present/absent - `system` boolean - yes/no - `gid` integer - GID to set for the group - `local` string - "local" command alternatives This module has some parameters to perform some tasks. The only required is "`name`", which is the group name. The "`state`" parameter allows us to create or delete a group, in our use case the default it's already set to "present" to create a group. The "`system`" parameter allows for the creation of a system group, default it's not. You could specify the "GID", the group identifier, in using the "`gid`" parameter. The "`local`" parameter allows using the "`local`" command alternatives on platforms that implement it if you have a central authentication system. ## Playbook Let's jump in a real-life Ansible Playbook to create a group. ### code - create_group.yml [code example] ### execution [cod... --- ## Ansible group Module — Manage Groups URL: https://www.ansiblebyexample.com/articles/ansible-group-module-manage-linux-groups Description: Create, modify, and delete Linux groups with the Ansible group module. Manage system groups, GIDs, and user membership with practical playbook examples. ## Introduction The `ansible.builtin.group` module creates, modifies, and deletes groups on Linux systems. Every server needs groups for permission management — application service accounts, deployment users, database administrators. This module handles group creation idempotently: it only makes changes when the group doesn't exist or its properties differ. ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `name` | ✅ | — | Group name | | `state` | ❌ | `present` | `present` to create, `absent` to delete | | `gid` | ❌ | — | Specific GID (group ID number) | | `system` | ❌ | `false` | Create as a system group (GID < 1000) | | `local` | ❌ | `false` | Use `lgroupadd`/`lgroupmod` (for local groups when using LDAP) | | `non_unique` | ❌ | `false` | Allow duplicate GIDs | ## Create a Group [code example] ## Create Multiple Groups [code example] ## Delete a Group [code example] ⚠️ You cannot delete a group that is any user's primary group. Remove or reassign users first. ## Add Users to Groups The `group` module only manages the group itself. To add users to groups, use the `ansible.builtin.user` module: [code example] ### ⚠️ The `append` Trap [code example] ## Practical Patterns ### Application Service Account [code example] ### Shared Directory with Group Access [code example] ### Standard Server Groups [code example] ### Verify Group Exists [code example] ## group vs user Module | Task | Module ... --- ## Ansible group_by — Create Dynamic Groups at Runtime URL: https://www.ansiblebyexample.com/articles/ansible-group-by-create-dynamic-groups-at-runtime Description: Use ansible.builtin.group_by to organize hosts into groups during playbook execution based on facts, variables, or conditions for targeted task execution. # Ansible group_by — Create Dynamic Groups at Runtime ## Introduction `ansible.builtin.group_by` creates host groups dynamically during playbook execution based on facts or variables. Instead of maintaining static inventory groups for every OS, datacenter, or role combination, `group_by` builds them automatically — then you target those groups in subsequent plays. ## Basic Usage [code example] ## Common Grouping Patterns ### By Distribution [code example] ### By Architecture [code example] ### By Memory/Capacity [code example] ### By Network [code example] ### By Custom Variable [code example] ## Multi-Play Pattern [code example] ## group_by vs Static Groups | Feature | `group_by` | Static Groups | |---------|-----------|--------------| | Defined in | Playbook (runtime) | Inventory file | | Based on | Facts, variables | Manual assignment | | Maintenance | Automatic | Manual updates needed | | Available | After the `group_by` task | From start | | Persistence | Current run only | Permanent | ## Combining with add_host [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Group is empty | Check fact/variable value; use `debug` to verify | | Invalid group name | Key must be valid group name (alphanumeric, underscore, hyphen) | | Group not available | `group_by` must run in an earlier play | | Special characters in key | Use `replace` filter: `{{ value \| replace('.', '_') }}` | | Always reports "changed" | Add `changed_when: false` ... --- ## Ansible group_vars vs host_vars vs role defaults — Variable Organization URL: https://www.ansiblebyexample.com/articles/ansible-group-vars-vs-host-vars-vs-role-defaults Description: Compare group_vars, host_vars, and role defaults in Ansible. Learn the right place for every variable with practical directory structure and precedence. ## Introduction Ansible variables can live in many places: `group_vars/`, `host_vars/`, role `defaults/`, role `vars/`, playbook `vars:`, and more. Putting variables in the wrong place leads to precedence confusion and hard-to-debug overrides. This guide shows exactly where each type of variable belongs. ## Quick Comparison | Location | Scope | Precedence | Purpose | |----------|-------|-----------|---------| | Role `defaults/` | Role | 2 (lowest) | Sensible defaults users should override | | `group_vars/all` | All hosts | 4 | Organization-wide defaults | | `group_vars/` | Group | 10-12 | Environment/team-specific values | | `host_vars/` | Single host | 13 | Host-specific overrides | | Play `vars:` | Play | 14 | Play-specific values | | Role `vars/` | Role | 18 | Internal role constants (hard to override) | | `set_fact` | Host | 19 | Runtime-computed values | | Extra vars `-e` | Global | 22 (highest) | CLI overrides | ## Directory Structure [code example] ## group_vars — Environment & Team Variables [code example] ### Splitting Large group_vars [code example] ## host_vars — Host-Specific Overrides [code example] ## Role defaults — Overridable Defaults [code example] ## Role vars — Internal Constants [code example] ## When to Use Each ### Role defaults/ (precedence 2) [code example] ### group_vars/ (precedence 10-12) [code example] ### host_vars/ (precedence 13) [code example] ### Role vars/ (precedence 18) [code example] ## Common Mistakes [code exam... --- ## Ansible GRUB Bootloader — Kernel Params URL: https://www.ansiblebyexample.com/articles/ansible-grub-bootloader-kernel-parameters Description: Configure GRUB bootloader with Ansible. Manage kernel command-line parameters, default boot entries, timeout settings, password protection. ## Introduction GRUB (GRand Unified Bootloader) controls which kernel boots, with what parameters, and how the boot menu behaves. Ansible automates GRUB configuration — set kernel command-line parameters, change default boot entries, configure timeouts, add password protection, and manage multi-kernel environments. Every change requires regenerating `grub.cfg`, which Ansible handles automatically. ## How GRUB Config Works [code example] ## Set Kernel Parameters [code example] ## Add/Remove Individual Parameters [code example] ## Configure Boot Timeout [code example] ## Default Boot Entry [code example] ## Security Parameters [code example] ## GRUB Password Protection [code example] ## Disable Console Output (Headless Servers) [code example] ## Multi-Kernel Management [code example] ## Complete GRUB Configuration Role [code example] [code example] [code example] ## Troubleshooting ### System Won't Boot After Change GRUB changes can make systems unbootable. Always: [code example] ### Verify Parameters Applied [code example] ## Related Articles - Ansible sysctl Module - Ansible Swap Management - Ansible File Module - Ansible Lineinfile Module ## Conclusion GRUB configuration with Ansible follows a simple pattern: edit `/etc/default/grub` with `lineinfile`, `replace`, or `template`, then regenerate `grub.cfg` with a handler. Always backup before changes — GRUB errors can make systems unbootable. Use `lineinfile` for individual parameter tweaks and... --- ## Ansible Handler — Run Immediately URL: https://www.ansiblebyexample.com/articles/run-immediately-an-ansible-handler-ansible-playbook Description: How to flush the execution of an Ansible handler after the notification task using the ansible.builtin.meta module. Tested, copy-paste examples included. ## When do Ansible Handlers run? > By default, handlers run after all the tasks in a particular play have been completed. ## Links - https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_handlers.html#controlling-when-handlers-run ## Demo Let's jump into a real-life example of how to run an Ansible Handler immediately. First of all, we need a task changed status. The simplest Ansible module returning a "changed" status is Ansible `command` module with a Linux command, like "uptime". Let's suppose we would like to execute a handler immediately after the changed status and not wait for the next task using the `ansible.builtin.meta` module. ### Initial Playbook - flush_before.yml [code example] ### inventory [code example] ### Initial Execution As you can notice the `message 1` handler is executed AFTER the last task (`message 2`) of the Play being executed. [code example] ### Modified Playbook Let's add the `ansible.builtin.meta` Ansible module after the first task. [code example] ### Modified Execution As you can notice the `message 1` handler is executed BEFORE the last task (`message 2`) of the Play being executed. [code example] ### Conclusion Now you know how to run immediately an Ansible Handler in a Playbook. --- ## Ansible Handler Not Running — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-handler-not-running-fix-and-solutions Description: Fix handlers that never trigger from notify typos, flush issues, and play scope. Tested on real machines with clear, copy-paste examples. # Ansible Handler Not Running — Fix and Solutions ## Introduction Fix handlers that never trigger from notify typos, flush issues, and play scope. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix handlers that never trigger from notify typos, flush issues, and play scope. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Handlers — notify on Change URL: https://www.ansiblebyexample.com/articles/ansible-handlers-notify-trigger-on-change Description: Trigger service restarts and reloads only when changes occur with Ansible handlers. notify, listen, flush_handlers, and run-once examples. ## Introduction Handlers are tasks that only run when **notified** by another task that made a change. The classic use case: restart a service only when its config file changes. Without handlers, you'd restart the service on every playbook run — wasteful and potentially disruptive. ## Basic Syntax [code example] ## How Handlers Work 1. A task runs and reports `changed: true` 2. If that task has `notify:`, the named handler is **queued** 3. Handlers run **once** at the **end of the play** (not immediately) 4. If multiple tasks notify the same handler, it still runs **only once** 5. If no task notified a handler, it **doesn't run at all** [code example] ## Notify Multiple Handlers [code example] ## Flush Handlers (Run Immediately) By default, handlers run at the end. Use `meta: flush_handlers` to run them mid-play: [code example] This is critical when subsequent tasks depend on the service being restarted. ## listen (Group Handlers) `listen` lets multiple handlers respond to a single notification topic: [code example] ## Handlers in Roles [code example] `roles/nginx/handlers/main.yml`: [code example] `roles/nginx/tasks/main.yml`: [code example] ## Handler Ordering Handlers run in the **order they're defined** in the handlers section, not the order they're notified: [code example] ## Practical Patterns ### Config Deploy with Validation [code example] ### Multiple Config Files, One Restart [code example] ## Troubleshooting ### Handler Not Running **C... --- ## Ansible handlers vs post_tasks — When to Trigger Actions URL: https://www.ansiblebyexample.com/articles/ansible-handlers-vs-post-tasks Description: Compare Ansible handlers and post_tasks. Learn when to use each for service restarts, notifications, and post-deployment actions with practical examples. ## Introduction Handlers and `post_tasks` both run after your main tasks, but they work differently. Handlers are event-driven — they only run when notified by a changed task. `post_tasks` always run after all roles and tasks complete. Mixing them up leads to unnecessary restarts or missed triggers. ## Quick Comparison | Feature | Handlers | post_tasks | |---------|----------|-----------| | Trigger | Only when notified | Always runs | | Runs when | End of tasks section (or `meta: flush_handlers`) | After tasks + roles | | Deduplication | ✅ Runs once even if notified multiple times | ❌ Runs every time | | Conditional | Based on `notify` from changed tasks | Normal `when` conditions | | Best for | Service restarts after config changes | Cleanup, health checks, notifications | ## Handlers — Event-Driven Actions [code example] ### Force Handlers to Run Early [code example] ### Listen — Multiple Triggers, One Event [code example] ## post_tasks — Always Run After [code example] ## Execution Order [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Handlers Guide - Ansible Strategies Guide - Ansible run_once vs delegate_to vs serial - Ansible Error Handling ## Conclusion **Handlers** for conditional actions triggered by changes (service restarts, cache clears). **post_tasks** for actions that must always run after deployment (health checks, load balancer re-enable, notifications). Use `meta: flush_handlers` when you need a handler to run... --- ## Ansible HAProxy Load Balancer Configuration URL: https://www.ansiblebyexample.com/articles/ansible-haproxy-load-balancer-configuration Description: Deploy and configure HAProxy load balancer with Ansible for high availability, SSL termination, health checks, and backend server management # Ansible HAProxy Load Balancer Configuration HAProxy is the industry-standard open-source load balancer used by companies like GitHub, Reddit, and Stack Overflow. Automating HAProxy deployment with Ansible ensures consistent, repeatable configurations across environments. ## Why Automate HAProxy with Ansible Managing HAProxy manually creates drift between environments and makes scaling painful. Ansible solves this by: - **Templating configurations** from inventory variables - **Rolling deployments** that update backends without downtime - **Consistent SSL/TLS** certificate management - **Health check validation** after every change ## Prerequisites - Ansible 2.14+ installed on controller - Target servers running Ubuntu 22.04+ or RHEL 8+ - SSH access with sudo privileges - SSL certificates (for HTTPS frontends) ## HAProxy Installation Playbook [code example] ## HAProxy Configuration Template Create `templates/haproxy.cfg.j2`: [code example] ## SSL Termination with Let's Encrypt [code example] ## Rolling Backend Updates Update backend servers without dropping connections: [code example] ## Multi-Tier Load Balancing Layer 4 + Layer 7 configuration for complex architectures: [code example] ## Rate Limiting and Security [code example] ## HAProxy Monitoring with Prometheus [code example] ## Complete Inventory Example [code example] ## Keepalived for Active-Passive HA [code example] ## Troubleshooting | Problem | Cause | Solution | |---------|-------|--... --- ## Ansible Harden Linux Security — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-harden-linux-security-complete-guide Description: Apply CIS benchmarks and security hardening with Ansible. Hands-on, tested examples and best practices for Ansible Harden Linux Security. # Ansible Harden Linux Security — Complete Guide ## Introduction Apply CIS benchmarks and security hardening with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Apply CIS benchmarks and security hardening with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible HashiCorp Vault — Secrets Management and Dynamic Credentials URL: https://www.ansiblebyexample.com/articles/ansible-hashicorp-vault-secrets-management Description: Integrate HashiCorp Vault with Ansible. Deploy Vault, manage secrets with lookup plugins, generate dynamic database credentials, PKI certificates. ## Introduction HashiCorp Vault manages secrets, encryption, and dynamic credentials. Ansible integrates through lookup plugins and modules — read static secrets, generate dynamic database credentials, issue PKI certificates, and manage Vault policies. This keeps secrets out of playbooks and inventory while providing audit trails for every access. **Note:** HashiCorp Vault is different from Ansible Vault. Ansible Vault encrypts files at rest; HashiCorp Vault is a centralized secrets management platform. ## Prerequisites [code example] ## Read Secrets with Lookup Plugin [code example] ## Authentication Methods ### Token Auth [code example] ### AppRole Auth [code example] ### Kubernetes Auth [code example] ## Deploy HashiCorp Vault [code example] [code example] ## Dynamic Database Credentials [code example] [code example] ## PKI Certificates [code example] ## Manage Vault Policies [code example] ## KV Secrets Engine [code example] ## Transit Encryption [code example] ## Troubleshooting ### "Permission denied" Errors Check the Vault policy allows the path you're accessing: [code example] ### Token Expired [code example] ## Related Articles - Ansible Vault Encrypt/Decrypt - Ansible Let's Encrypt SSL - Ansible SSH Key Management - Ansible Compliance Guide ## Conclusion HashiCorp Vault + Ansible provides centralized secrets management with full audit trails. Use the `hashi_vault` lookup plugin to read secrets in playbooks, dynamic database crede... --- ## Ansible hashicorp.vault Module Example: Dynamic Secrets in a Playbook URL: https://www.ansiblebyexample.com/articles/ansible-hashicorp-vault-module-example-dynamic-secrets-in-a-playbook Description: Learn how the hashicorp.vault collection fetches dynamic secrets in an Ansible playbook, with a runnable example, notes, and gotchas. The `hashicorp.vault` collection lets a playbook pull secrets straight out of HashiCorp Vault instead of hardcoding them in a vars file. It was one of 12 new content collections announced for AAP 2.7 at Red Hat Tech Day Netherlands 2026 in Bunnik, alongside OIDC, PKI, dynamic credentials, and Event-Driven Ansible (EDA) integration. Below is a minimal playbook that reads a static secret and requests a short-lived dynamic database credential in the same run. ## Example playbook [code example] ## What it does The first task uses `vault_kv2_get` to read a plain KV v2 secret at `secret/app/database` — the kind of static value you'd otherwise store in an encrypted vars file. The second task calls `vault_read` against a database secrets engine path (`database/creds/readonly-role`), which Vault generates on demand: every run gets a brand-new username and password with a lease duration instead of a value that sits in Vault forever. The third task just prints the lease so you can see it expire on its own schedule, and the last task writes the freshly minted credential into a config file with tight file permissions. Authentication here uses a token for simplicity, but `hashicorp.vault` also supports OIDC login, so a playbook run through AAP 2.7 can authenticate with the platform's own identity provider instead of a long-lived Vault token. Combined with the collection's PKI support for issuing short-lived certificates, and its dynamic-credentials integration with AAP's credential sy... --- ## Ansible Helm Charts — Deploy Kubernetes Applications URL: https://www.ansiblebyexample.com/articles/ansible-helm-charts-deploy-kubernetes-applications Description: Ansible Helm Charts guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Helm Charts — Deploy Kubernetes Applications ## Introduction Deploy Kubernetes Applications. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Helm Charts requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** f... --- ## Ansible Hetzner Cloud — Server Management URL: https://www.ansiblebyexample.com/articles/ansible-hetzner-cloud-server-management Description: Ansible Hetzner Cloud guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Hetzner Cloud — Server Management ## Introduction Server Management. Automate Hetzner infrastructure with Ansible using the `hetzner.hcloud` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches Hetzner naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/produ... --- ## Ansible Host Groups — Organize Inventory for Targeted Automation URL: https://www.ansiblebyexample.com/articles/ansible-host-groups-organize-inventory-for-targeted-automation Description: Structure Ansible inventory with host groups, nested groups, group variables, and patterns. Target specific servers with group-based playbook execution. # Ansible Host Groups — Organize Inventory for Targeted Automation ## Introduction Host groups are how you organize servers in Ansible inventory. Instead of listing individual hosts in every playbook, you group them by function (webservers, databases), environment (production, staging), location (us-east, eu-west), or any criteria that makes sense for your infrastructure. This guide covers group structure, nesting, variables, and targeting patterns. ## Basic Group Structure ### INI Format [code example] ### YAML Format [code example] ## Nested Groups (Children) [code example] A host can belong to multiple groups: [code example] ## Group Variables ### Directory Structure [code example] ### Variable Files [code example] ## Variable Precedence with Groups [code example] ## Targeting Groups in Playbooks [code example] ## Command Line Targeting [code example] ## Built-in Groups Ansible provides two groups automatically: [code example] ## Multi-Environment Inventory ### Separate Files [code example] [code example] ## Dynamic Group Membership [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "No hosts matched" | Check group name spelling; run `ansible-inventory --list` | | Variables not applied | Check `group_vars/` directory name matches group name exactly | | Wrong variable value | Check precedence: child group vars override parent | | Host in wrong group | Run `ansible-inventory --graph` to visualize | | `group_vars` not... --- ## Ansible Host Unreachable Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-host-unreachable-error-fix-and-solutions Description: Resolve host unreachable errors caused by SSH, DNS, firewall, and network issues. Tested on real machines with clear, copy-paste examples. # Ansible Host Unreachable Error — Fix and Solutions ## Introduction Resolve host unreachable errors caused by SSH, DNS, firewall, and network issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve host unreachable errors caused by SSH, DNS, firewall, and network issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible hostname and timezone Modules — System Configuration URL: https://www.ansiblebyexample.com/articles/ansible-hostname-timezone-system-configuration Description: Use Ansible to set hostnames and timezones on Linux servers. Configure system identity, NTP, and locale settings with practical examples. ## Introduction System identity and time configuration are foundational server setup tasks. Ansible's `hostname` and `timezone` modules configure these idempotently, ensuring consistency across your fleet. ## Set Hostname [code example] ### Hostname Parameters | Parameter | Description | |-----------|-------------| | `name` | Hostname to set (required) | | `use` | Backend: `systemd`, `debian`, `redhat`, `alpine`, etc. (auto-detected) | ## Set Timezone [code example] ### Common Timezones | Timezone | Region | |----------|--------| | `UTC` | Universal | | `America/New_York` | US Eastern | | `America/Chicago` | US Central | | `America/Denver` | US Mountain | | `America/Los_Angeles` | US Pacific | | `Europe/London` | UK | | `Europe/Berlin` | Germany | | `Europe/Rome` | Italy | | `Europe/Paris` | France | | `Asia/Tokyo` | Japan | | `Asia/Shanghai` | China | | `Asia/Kolkata` | India | | `Australia/Sydney` | Australia Eastern | [code example] ## Configure NTP [code example] ## Practical Pattern: Full System Bootstrap [code example] ## Set Locale [code example] ## Troubleshooting ### Hostname Reverts After Reboot Ensure cloud-init isn't overriding it: [code example] ### Timezone Module Not Found Install the collection: [code example] ## Related Articles - Ansible Playbook Guide - Ansible lineinfile Module - Ansible blockinfile Module - Ansible service Module ## Conclusion `ansible.builtin.hostname` and `community.general.timezone` handle fundamental server ... --- ## Ansible hostname Module — Set System Hostname URL: https://www.ansiblebyexample.com/articles/ansible-hostname-module-set-system-hostname Description: Permanently change hostnames on remote Linux hosts with ansible.builtin.hostname. Works with systemd, hostnamectl, and BSD — no reboot required. ## Introduction `ansible.builtin.hostname` sets the system hostname on remote hosts. It works across Linux distributions, macOS, and Windows — using the appropriate method for each OS (systemd, hostnamectl, scutil, etc.). ## Basic Usage [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `name` | (required) Hostname to set | | `use` | Backend: `systemd`, `alpine`, `debian`, `freebsd`, `generic`, `macos`, `openbsd`, `openwrt`, `redhat`, `sles`, `solaris` | ## Set Hostname from Inventory [code example] ## Update /etc/hosts Setting hostname alone isn't enough — also update `/etc/hosts`: [code example] [code example] ## Complete Hostname Setup [code example] ## Hostname Facts Ansible gathers hostname facts automatically: [code example] | Fact | Example | Source | |------|---------|--------| | `ansible_hostname` | `web-01` | System (short) | | `ansible_fqdn` | `web-01.example.com` | DNS/system | | `ansible_nodename` | `web-01` | `uname -n` | | `inventory_hostname` | `web-01` | Inventory file | | `ansible_domain` | `example.com` | DNS | ## Cloud Hostname Patterns ### AWS EC2 [code example] ### Dynamic Naming [code example] ## Windows Hostname [code example] ## Troubleshooting ### Hostname Resets After Reboot [code example] ### FQDN Not Resolving [code example] ## Related Articles - Ansible sysctl Module - Ansible lineinfile Module - Ansible template Module - Ansible Inventory Guide ## Conclusion `ansible.builtin.ho... --- ## Ansible htpasswd Module — Manage Apache htpasswd Files URL: https://www.ansiblebyexample.com/articles/ansible-htpasswd-module-manage-apache-htpasswd-files Description: Create and manage HTTP basic authentication password files for Apache/Nginx. With clear, copy-paste, step-by-step examples. # Ansible htpasswd Module — Manage Apache htpasswd Files ## Introduction The `community.general.htpasswd` module create and manage HTTP basic authentication password files for Apache/Nginx. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.htpasswd` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — ru... --- ## Ansible iam_policy Module — Manage AWS IAM Policies URL: https://www.ansiblebyexample.com/articles/ansible-iam-policy-module-manage-aws-iam-policies Description: Create, attach, and manage IAM policies for AWS access control with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible iam_policy Module — Manage AWS IAM Policies ## Introduction The `amazon.aws.iam_policy` module create, attach, and manage IAM policies for AWS access control with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.iam_policy` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` bef... --- ## Ansible iam_role Module — Manage AWS IAM Roles URL: https://www.ansiblebyexample.com/articles/ansible-iam-role-module-manage-aws-iam-roles Description: Create IAM roles with trust policies and permission boundaries using Ansible. With clear, copy-paste, step-by-step examples. # Ansible iam_role Module — Manage AWS IAM Roles ## Introduction The `amazon.aws.iam_role` module create IAM roles with trust policies and permission boundaries using Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.iam_role` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before appl... --- ## Ansible Idempotency Problems — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-idempotency-problems-fix-and-solutions Description: Fix tasks that report changed on every run due to state checking issues. Tested on real machines with clear, copy-paste examples. # Ansible Idempotency Problems — Fix and Solutions ## Introduction Fix tasks that report changed on every run due to state checking issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix tasks that report changed on every run due to state checking issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Ignore Errors — Handle Failures Gracefully URL: https://www.ansiblebyexample.com/articles/ansible-ignore-errors-handle-failures-gracefully Description: Use ignore_errors, ignore_unreachable, failed_when, and block/rescue to handle task failures in Ansible playbooks without stopping execution. # Ansible Ignore Errors — Handle Failures Gracefully ## Introduction By default, Ansible stops playbook execution when a task fails. But sometimes failures are expected — a package that might not exist, a service that's already stopped, a command that returns non-zero on success. This guide covers every technique for handling failures gracefully: `ignore_errors`, `failed_when`, `block/rescue/always`, and `ignore_unreachable`. ## ignore_errors Continue playbook execution even if a task fails: [code example] ### When to Use [code example] ## failed_when — Custom Failure Conditions Override what Ansible considers a failure: [code example] ## block / rescue / always Try-catch-finally for Ansible: [code example] ## ignore_unreachable Continue with other hosts when one is down: [code example] ## any_errors_fatal Opposite of ignore_errors — fail the entire play if ANY host fails: [code example] ## max_fail_percentage Allow some hosts to fail before stopping: [code example] ## Retry Failed Hosts [code example] [code example] ## Comparison Table | Technique | Scope | Use Case | |-----------|-------|----------| | `ignore_errors: true` | Single task | Expected failures | | `failed_when` | Single task | Custom failure logic | | `block/rescue/always` | Task group | Rollback on failure | | `ignore_unreachable` | Play/task | Unreachable hosts | | `any_errors_fatal` | Play | Critical operations | | `max_fail_percentage` | Play | Rolling updates | | `retries/until` ... --- ## Ansible Ignore SSH Host Key Checking URL: https://www.ansiblebyexample.com/articles/ignore-ansible-ssh-host-key-checking-ansible-configuration Description: How to avoid the SSH Host Key checking at the beginning of every Ansible execution in our laboratory, CI/CD pipeline, or cloud computing provider. ## How to Ignore Ansible SSH Host Key Checking? ## SSH Host Key > % ssh devops@demo.example.com > The authenticity of host 'demo.example.com (192.168.0.190)' can't be established. > RSA key fingerprint is SHA256:42JErOjO9fKNNBapEEyhpfTNn+rt8SPNob00uRlmqRs. > This key is not known by any other names > Are you sure you want to continue connecting (yes/no/[fingerprint])? A host key is a cryptographic key used for authenticating computers in the SSH protocol. Host keys are normally generated automatically when OpenSSH is first installed or when the computer is first booted. In a production environment is considered a security mechanism to verify our machine has not been altered. However, in a developer laboratory often, we need to destroy our machines often and recreate them. This behavior stops the Ansible execution and requires some manual developer work. We can apply this behavior also in a CI/CD pipeline or cloud computing provider. ## Links - HOST_KEY_CHECKING ## Playbook How to Ignore Ansible SSH Host Key Checking in our Ansible laboratory. I'm going to show how to create a ansible.cfg file to ignore the SSH Host Key Checking at the beginning of the Ansible Playbooks execution. - ansible.cfg [code example] - ping.yml [code example] - inventory [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] ## Conclusion Now you know how to ignore SSH Host Key checking wit... --- ## Ansible ignore_errors — Best Practices URL: https://www.ansiblebyexample.com/articles/ansible-best-practices-ignore-errors-in-ansible-playbooks Description: Use ignore_errors, failed_when, and block/rescue in Ansible playbooks. Best practices to handle failures without masking real problems. ## Introduction In the realm of IT automation, Ansible is a powerful tool that helps streamline tasks and manage infrastructure efficiently. While Ansible makes automation accessible and user-friendly, it’s essential to follow best practices to ensure the reliability and predictability of your automation workflows. One critical aspect of writing Ansible playbooks is error handling, and that’s where the `ignore_errors` Ansible-Lint rule comes into play. This rule checks that playbooks do not use the `ignore_errors` directive to ignore all errors. In this article, we’ll explore the rationale behind this rule and best practices for handling errors in Ansible playbooks. ### The Role of `ignore_errors` in Ansible In Ansible playbooks, the `ignore_errors` directive is employed to instruct Ansible to continue execution even when a task fails. This directive can be beneficial in specific scenarios, but it should be used judiciously. Using `ignore_errors` to bypass all errors across all tasks in a playbook is generally discouraged. Here’s why relying too heavily on `ignore_errors` is problematic: 1. **Concealing Failures**: When you ignore all errors across tasks, you essentially hide any failures that occur during playbook execution. This can lead to the execution of tasks that shouldn’t run, potentially causing further problems down the line. 2. **Incorrect Task Status**: The use of `ignore_errors` can wrongly mark tasks as “succeeded” even when they encounter errors. This can b... --- ## Ansible ignore_errors — Continue Playbook on Task Failure URL: https://www.ansiblebyexample.com/articles/ansible-ignore-errors-continue-playbook-on-task-failure Description: Use ignore_errors to continue Ansible playbook execution when tasks fail. Handle expected failures, combine with failed_when, and implement error recovery. # Ansible ignore_errors — Continue Playbook on Task Failure ## Introduction When an Ansible task fails, the playbook stops execution for that host. `ignore_errors: true` overrides this behavior, allowing the playbook to continue even when a task fails. This is essential for handling expected failures — checking if something exists, attempting optional operations, or building graceful degradation into your automation. ## Basic Usage [code example] ## Capturing Failures [code example] ## ignore_errors vs failed_when [code example] **When to use which:** | Scenario | Use | |----------|-----| | Task might fail and that's fine | `ignore_errors: true` | | You want to redefine what "fail" means | `failed_when` | | Check existence of something | `failed_when: result.rc > 1` | | Optional cleanup steps | `ignore_errors: true` | | API returns non-zero for "not found" | `failed_when` | ## ignore_errors with Blocks [code example] ## ignore_unreachable [code example] ## Common Patterns ### Pre-Flight Checks [code example] ### Cleanup Tasks [code example] ### Optional Package Installation [code example] ### Graceful Service Restart [code example] ## Using any_errors_fatal [code example] ## max_fail_percentage [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Playbook stops despite `ignore_errors` | Check if error is `unreachable`, not `failed` — use `ignore_unreachable` | | Handler fires on ignored failure | Handlers only fire on `cha... --- ## Ansible import_playbook vs include URL: https://www.ansiblebyexample.com/articles/ansible-import-playbook-vs-include Description: Compare import_playbook and include_playbook in Ansible. Learn static vs dynamic inclusion, when to use each, and best practices for large projects. ## Introduction Large Ansible projects split automation across multiple playbook files. `import_playbook` and task-level includes (`import_tasks`/`include_tasks`) are the two mechanisms for composing them. Understanding when each is processed — parse time vs runtime — is essential for conditional logic, tags, and debugging. ## Quick Comparison | Feature | `import_playbook` | `include_tasks` (in a play) | |---------|-------------------|---------------------------| | Processed at | Parse time (static) | Runtime (dynamic) | | Conditional (`when`) | ❌ Cannot conditionally import | ✅ Can conditionally include | | Tags | ✅ Tags flow into imported plays | ⚠️ Tags on include apply to all tasks | | Loops | ❌ Cannot loop | ✅ Can loop | | Variables from runtime | ❌ Not available | ✅ Available | | Error if file missing | ✅ Immediate error | ✅ Runtime error | | `--list-tasks` visibility | ✅ Shows all tasks | ❌ Shows include line only | ## import_playbook — Static Inclusion [code example] [code example] ### Project Structure [code example] ### Using Tags with import_playbook [code example] [code example] ## Composing Plays Within Playbooks [code example] ## Dynamic Task Inclusion Within Plays [code example] ## Environment-Based Composition [code example] ## Common Mistakes [code example] ## Debugging [code example] ## Related Articles - Ansible include_tasks vs import_tasks - Ansible Roles Guide - Ansible Playbook Guide - Ansible roles vs collections ## Conclusion ... --- ## Ansible import_role vs include_role — Static and Dynamic Role Loading URL: https://www.ansiblebyexample.com/articles/ansible-import-role-vs-include-role-static-and-dynamic-role-loading Description: Compare import_role and include_role in Ansible. Learn static vs dynamic role loading, when to use each, and how they affect handlers, tags. # Ansible import_role vs include_role — Static and Dynamic Role Loading ## Introduction Ansible provides two ways to load roles in tasks: `ansible.builtin.import_role` (static) and `ansible.builtin.include_role` (dynamic). The difference matters for tags, handlers, conditionals, and performance. Choosing wrong can lead to tasks being skipped unexpectedly, handlers not firing, or tags not working as expected. ## Quick Comparison | Feature | `import_role` (Static) | `include_role` (Dynamic) | |---------|----------------------|------------------------| | Processing time | Parse time (before play starts) | Runtime (when task executes) | | Tags | Inherited, work with `--tags` | NOT accessible via `--tags` | | Handlers | Work normally | Work normally | | `when` condition | Applied to EVERY task in role | Applied once (include or skip all) | | Loops | ❌ Cannot loop | ✅ Can loop | | Variable files | Loaded at parse time | Loaded at runtime | | Performance | Faster (pre-parsed) | Slightly slower | | `--list-tasks` | Shows role tasks | Shows include statement only | ## import_role (Static) [code example] ### Tags Work with import_role [code example] ### when Applied to Every Task [code example] ## include_role (Dynamic) [code example] ### Looping Over Roles [code example] ### Dynamic Role Names [code example] ## Side-by-Side Examples ### Scenario 1: Tag Filtering [code example] ### Scenario 2: Conditional Execution [code example] ### Scenario 3: Variable Role Name... --- ## Ansible include and import Tasks URL: https://www.ansiblebyexample.com/articles/ansible-include-import-organize-playbooks-tasks Description: Organize Ansible playbooks with import_tasks, include_tasks, import_playbook, and include_role. Static vs dynamic includes with real examples. ## Introduction As playbooks grow, splitting them into reusable files is essential. Ansible provides two mechanisms: **import** (static, parsed at load time) and **include** (dynamic, processed at runtime). Understanding the difference is key to organizing scalable automation. ## import vs include | | import (static) | include (dynamic) | |---|---|---| | **When parsed** | At playbook load time | At runtime when reached | | **Tags** | Inherited by all tasks | Only on the include line | | **Conditionals** | Applied to each task | Applied once to the include | | **Loops** | ❌ Cannot loop | ✅ Can loop | | **Variables** | Resolved at parse time | Resolved at runtime | | **Handlers** | Can be notified by name | Cannot be notified by name | | **Best for** | Predictable, always-run tasks | Conditional or looped includes | ## import_tasks (Static) [code example] [code example] Tags flow through to all imported tasks: [code example] ## include_tasks (Dynamic) [code example] ## import_playbook [code example] [code example] ## include_role / import_role [code example] ## Practical Patterns ### OS-Specific Tasks [code example] [code example] ### Task File Per Component [code example] [code example] ### Reusable Task with Parameters [code example] ### Environment-Specific Playbooks [code example] ### Handlers in Separate File [code example] ## When to Use Which ### Use import_tasks when: - Tasks should always run - You need tags to flow through - You need hand... --- ## Ansible include_tasks vs import_tasks — When to Use Each URL: https://www.ansiblebyexample.com/articles/ansible-include-tasks-vs-import-tasks Description: Understand the difference between include_tasks and import_tasks in Ansible. Learn when to use static imports vs dynamic includes with practical examples. ## Introduction Ansible has two ways to include task files: `import_tasks` (static) and `include_tasks` (dynamic). Choosing the wrong one leads to confusing behavior with tags, handlers, loops, and conditionals. This guide explains exactly when each approach applies, with side-by-side comparisons. ## Quick Comparison | Feature | `import_tasks` (static) | `include_tasks` (dynamic) | |---------|------------------------|--------------------------| | When parsed | At playbook parse time | At runtime when reached | | Tags | Inherited by imported tasks | Applied only to include itself | | Loops | ❌ Cannot use `loop` | ✅ Can use `loop` | | Conditionals | Applied to **each** imported task | Applied to the include **decision** | | `--list-tasks` | ✅ Shows imported tasks | ❌ Not listed | | `--list-tags` | ✅ Shows tags from imports | ❌ Not listed | | Handlers | ✅ Can notify imported handlers | ⚠️ Handlers in includes need special handling | | Variables | File path cannot use variables | ✅ File path can use variables | ## Basic Usage ### import_tasks (Static) [code example] ### include_tasks (Dynamic) [code example] ## When Conditionals Behave Differently This is the most common source of confusion: [code example] [code example] ## Tags Behave Differently [code example] [code example] ## Loops Only Work with include_tasks [code example] ## Variable Filenames Only Work with include_tasks [code example] ## Handlers [code example] [code example] ## Decision Flowchart ... --- ## Ansible include_vars Module — Load Variables from Files Dynamically URL: https://www.ansiblebyexample.com/articles/ansible-include-vars-module-load-variables-from-files-dynamically Description: Load YAML/JSON variable files dynamically based on conditions, OS, or environment. Hands-on, tested examples and best practices for Ansible include_vars Module. # Ansible include_vars Module — Load Variables from Files Dynamically ## Introduction The `ansible.builtin.include_vars` module load YAML/JSON variable files dynamically based on conditions, OS, or environment. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.include_vars` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test... --- ## Ansible infra.mecm_ops Role Example: Emergency Patch Windows Fleet URL: https://www.ansiblebyexample.com/articles/ansible-infra-mecm-ops-role-example-emergency-patch-windows-fleet Description: Runnable Ansible playbook using infra.mecm_ops roles to emergency patch a Windows fleet via Microsoft Endpoint Configuration Manager on AAP 2.7. At Red Hat Tech Day Netherlands 2026 (3 June 2026, Bunnik), the Ansible team announced `infra.mecm_ops` as one of 12 new content collections coming to AAP 2.7. It ships higher-level validated roles on top of `microsoft.mecm`, packaging patch orchestration and health reporting into a single call instead of chaining raw modules. Here's a playbook that triggers an emergency patch cycle across a Windows fleet managed by Microsoft Endpoint Configuration Manager. ## Example playbook [code example] ## What it does and why The play targets the MECM site server (the collection communicates with the ConfigMgr SMS Provider, not each Windows endpoint directly), runs a pre-patch health check, and aborts if too many clients are already unhealthy — patching on top of a broken client base just produces noisy failures. `emergency_patch` then deploys a specific set of KB articles as a high-priority, short-deadline collection instead of waiting for the normal maintenance-window cadence, which is the whole point of an emergency patch role versus the lower-level `microsoft.mecm` modules. The final loop polls `health_report` until compliance clears a threshold, giving you a clean pass/fail signal for a job template rather than a fire-and-forget deployment. This is exactly the "Efficiency and Resilience" pitch Red Hat gave the validated-role collections at Tech Day: wrap the multi-step MECM workflow (health check → deploy → verify) that admins currently script by hand into one supported role i... --- ## Ansible infra.support_assist Collection — Automated Red Hat Support Diagnostics URL: https://www.ansiblebyexample.com/articles/ansible-infra-support-assist-collection-automated-red-hat-support-diagnostics Description: Use infra.support_assist to automate Red Hat support case diagnostics. Gather system reports, create cases, and upload diagnostics to the Support Portal. # Ansible infra.support_assist Collection — Automated Red Hat Support Diagnostics ## Introduction The `infra.support_assist` collection (v1.1.1, May 2026) automates the most tedious part of Red Hat support workflows — gathering diagnostic data. Instead of manually running `sosreport`, collecting logs, and uploading to the Support Portal, this collection handles the entire process: gather system reports, optionally create a support case, and upload diagnostics directly. It's maintained by the Red Hat Community of Practice (redhat-cop). ## Installation [code example] ## Quick Start [code example] ## Common Use Cases ### Gather All Diagnostics [code example] ### Create and Upload to Support Case [code example] ### Proactive Health Checks [code example] ## What It Collects | Category | Data Gathered | |----------|--------------| | System | OS version, kernel, hardware, uptime | | Network | Interfaces, routes, firewall rules, DNS | | Storage | Disk usage, LVM, mount points, fstab | | Services | systemd unit status, failed services | | Packages | Installed RPMs, pending updates | | Subscription | RHSM status, repositories, entitlements | | Logs | journalctl excerpts, /var/log key files | | Performance | CPU, memory, I/O statistics | ## Integration with AAP [code example] ## Comparison with Manual Process | Step | Manual | With infra.support_assist | |------|--------|--------------------------| | SSH to each server | ✅ Required | ❌ Not needed | | Run sosreport | ✅... --- ## Ansible infra.windows_ops Role Example: Enforce CIS Benchmark Baseline URL: https://www.ansiblebyexample.com/articles/ansible-infra-windows-ops-role-example-enforce-cis-benchmark-baseline Description: Runnable Ansible playbook example using the infra.windows_ops collection to audit and remediate CIS benchmark drift on Windows Server fleets. `infra.windows_ops` is one of 12 new content collections announced for Ansible Automation Platform 2.7 at Red Hat Tech Day Netherlands 2026 in Bunnik. It ships higher-level, validated roles for Windows security baseline enforcement — covering DISA STIG, CIS benchmarks, and drift remediation — so you don't have to hand-roll registry and policy checks module by module. Below is a runnable playbook that audits a Windows Server fleet against a CIS benchmark level and remediates any drift it finds. ## Example playbook [code example] Run it against your Windows inventory group with: [code example] ## What it does and why The `infra.windows_ops.cis_baseline` role wraps the collection's lower-level Windows modules (registry keys, local security policy, audit policy, service state) into a single idempotent pass: it audits the target hosts against the CIS Microsoft Windows Server benchmark, records which rules pass or fail, and — because `windows_ops_remediate: true` — applies the safe, scripted fixes for anything out of compliance. Results land in `windows_ops_baseline_result`, a structured fact the role sets on each host, which the `post_tasks` block inspects to fail the run loudly if drift survives remediation (useful as an AAP job template gate before a change window closes). The `windows_ops_exceptions` list lets you document and suppress specific rule IDs with a stated reason instead of silently failing or hardcoding skips in your own tasks — handy for the CIS rules that l... --- ## Ansible ini_file Module — Manage INI Configuration Files URL: https://www.ansiblebyexample.com/articles/ansible-ini-file-module-manage-ini-configuration-files Description: Ansible ini_file Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible ini_file Module — Manage INI Configuration Files ## Introduction Manage INI Configuration Files. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible ini_file Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ... --- ## Ansible Install Docker on Linux URL: https://www.ansiblebyexample.com/articles/install-docker-in-redhat-like-systems-ansible-module-rpm-key-yum-repository-and-yum Description: Learn how to install Docker on Linux systems using an Ansible playbook. Follow our guide for a seamless Docker setup and start process. ## How to Install Docker in RedHat-like systems with Ansible? ## Ansible install Docker in RedHat-like systems - Add Docker key => `ansible.builtin.rpm_key` - Add Docker repository => `ansible.builtin.yum_repository` - Update yum cache and install Docker => `ansible.builtin.yum` In order to install Docker on a RedHat-like system we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.rpm_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Docker releases. The second step is to add the add Docker repository to the distribution. It's an extra website where `yum/DNF`, your distribution package manager looks like for software. You are going to use the `ansible.builtin.yum_repository` Ansible module. The third step is to update the yum cache for the available packages and install Docker using the `ansible.builtin.yum` Ansible module. ## Parameters - `rpm_key` `key` string - URL - `rpm_key` `state` string - present/absent - `yum_repository` `name` string - repository - `yum_repository` `baseurl` string - URL - `yum_repository` `gpgcheck` boolean gpgkey string - GPG check and key URL - `yum` `name` string - name or package specific - `yum` `state` string - latest/present/absent - `yum` `update_cache` boolean - no/yes For the `ansible.builtin.rpm_key` Ansible module I'm going to use two ... --- ## Ansible Install from Source — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-install-from-source-complete-guide Description: Compile and install software from source code using git clone, make, configure with Ansible automation. With clear, copy-paste, step-by-step examples. # Ansible Install from Source — Complete Guide ## Introduction Compile and install software from source code using git clone, make, configure with Ansible automation. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use `block/rescue/always` for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked before action | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Compile and install software from source code using git clone, make, configure with Ansible automation. Use check mode for validation, handle errors gracefully, and always test in a non-production environment first. --- ## Ansible Install from Source Code — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-install-from-source-code-complete-guide Description: Compile and install software from source using git, make, configure. Hands-on, tested examples and best practices for Ansible Install from Source Code. # Ansible Install from Source Code — Complete Guide ## Introduction Compile and install software from source using git, make, configure. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Compile and install software from source using git, make, configure. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Install Multiple Packages — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-install-multiple-packages-complete-guide Description: Install multiple packages in a single task with apt, yum, dnf, and package modules. With clear, copy-paste, step-by-step examples. # Ansible Install Multiple Packages — Complete Guide ## Introduction Install multiple packages in a single task with apt, yum, dnf, and package modules. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Install multiple packages in a single task with apt, yum, dnf, and package modules. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Intelligent Assistant Example: Configure Azure OpenAI as the Backend URL: https://www.ansiblebyexample.com/articles/ansible-intelligent-assistant-example-configure-azure-openai-as-the-backend Description: Configure the AAP 2.7 Intelligent Assistant to use Azure OpenAI as its BYOM backend, with a real settings playbook and gotchas. The Intelligent Assistant is the chatbot embedded in the AAP UI, and starting with AAP 2.6 it supports Bring Your Own Model (BYOM) backends beyond Red Hat AI — including Azure OpenAI. This example shows how to point the Intelligent Assistant at an Azure OpenAI deployment using an Ansible playbook against the AAP Gateway API. ## Example playbook [code example] ## What it does The first task creates a dedicated credential in AAP holding the Azure OpenAI endpoint URL, API key, and API version — kept separate from other credentials so access can be audited and rotated independently. The second task updates the platform-wide settings that tell the Intelligent Assistant which provider, deployment name, and credential to use when answering chatbot queries in the AAP UI. Once applied, every Intelligent Assistant conversation in that AAP instance routes its completions through your Azure OpenAI deployment instead of (or in addition to) Red Hat AI. This is BYOM in practice: AAP 2.7's provider compatibility matrix, presented at Red Hat Tech Day Netherlands 2026, confirms Azure OpenAI as a supported Intelligent Assistant backend from AAP 2.6 onward, alongside Red Hat AI and OpenAI. Note this differs from the Coding Assistant (the Ansible VS Code extension), where Azure OpenAI support is still listed as "Coming Soon" — the two AI surfaces have independent rollout timelines even though they share the BYOM concept. ## Notes / Gotchas - **Module and field names are illustrative.** `an... --- ## Ansible Intelligent Assistant Example: Configure OpenAI as the Backend URL: https://www.ansiblebyexample.com/articles/ansible-intelligent-assistant-example-configure-openai-as-the-backend Description: Configure the Ansible Automation Platform 2.7 Intelligent Assistant to use OpenAI as a BYOM backend, with a working credential and settings example. The Intelligent Assistant is the chatbot embedded in the Ansible Automation Platform UI, and starting with AAP 2.6 it supports a BYOM (Bring Your Own Model) model, meaning you are not locked into Red Hat AI. OpenAI is one of the supported backends, alongside Azure OpenAI. Below is a minimal example of wiring an OpenAI credential into AAP so the Intelligent Assistant uses it. [code example] ## What it does and why The first task creates a credential of type "OpenAI API Token" in AAP's credential store, holding the API key (pulled from an Ansible Vault–encrypted variable, `vault_openai_api_key`) and the model identifier. The second task updates the platform-wide Intelligent Assistant settings so the chatbot routes its requests through that credential instead of the default Red Hat AI backend. Once applied, users chatting with the Intelligent Assistant inside the AAP UI — asking it to explain a failed job, draft a playbook snippet, or summarize an inventory — have their requests forwarded to OpenAI's API using the configured model. This BYOM pattern, presented at Red Hat Tech Day Netherlands 2026, is specific to the Intelligent Assistant. The separate Coding Assistant (the Ansible VS Code extension) has a different provider compatibility matrix: OpenAI support there is still listed as "Coming Soon," while IBM watsonx was actually the first external provider it supported, back in AAP 2.5. Don't assume parity between the two AI features just because they share an underlying BY... --- ## Ansible Intelligent Assistant Example: Configure Red Hat AI as the Backend URL: https://www.ansiblebyexample.com/articles/ansible-intelligent-assistant-example-configure-red-hat-ai-as-the-backend Description: Configure the AAP 2.7 Intelligent Assistant with Red Hat AI as its model backend using an Ansible playbook and the AAP Gateway API. The Intelligent Assistant is the chatbot embedded in the AAP UI, and as of AAP 2.7 it supports a BYOM (Bring Your Own Model) provider matrix — Red Hat AI, OpenAI, and Azure OpenAI can all serve as its backend. This example wires the Intelligent Assistant to Red Hat AI using the AAP Gateway configuration API. ## Example Playbook [code example] ## What This Does The play calls the AAP Gateway API to register a Red Hat AI endpoint as an `ai_providers` entry, then patches the `intelligent_assistant` setting to point at that provider ID and enable it. A final GET confirms the assistant can reach the model. Red Hat AI is supported as an Intelligent Assistant backend from AAP 2.6 onward, alongside OpenAI and Azure OpenAI — this was reaffirmed in Red Hat's BYOM provider compatibility matrix presented at Red Hat Tech Day Netherlands 2026 in Bunnik. Note that this is a different matrix than the one for the Coding Assistant (the Ansible VS Code extension), which has its own provider support timeline. ## Notes / Gotchas - **IBM watsonx is not supported** as an Intelligent Assistant backend at all — it only shows up on the Coding Assistant side of the matrix, where it was actually the first external provider supported (AAP 2.5+). Don't assume parity between the two assistants' provider lists. - **Google Gemini/Vertex is "Coming Soon"** for the Intelligent Assistant as of this writing — plan a fallback provider if your organization standardizes on Gemini. - Store `aap_gateway_token` ... --- ## Ansible Inventory File — Host Setup URL: https://www.ansiblebyexample.com/articles/ansible-inventory-file-hosts-guide Description: Write Ansible inventory files in INI and YAML format. Groups, variables, patterns, dynamic inventory, and host ranges with practical examples. ## Introduction The inventory file tells Ansible which hosts to manage. It lists your servers, organizes them into groups, and assigns variables. You can write it in INI or YAML format, and it scales from a single server to thousands of hosts with dynamic inventory scripts. ## INI Format The most common format — simple and readable: [code example] ## YAML Format More structured, supports complex data better: [code example] ## Host Variables [code example] [code example] ## Group Variables [code example] [code example] ## Groups of Groups [code example] [code example] ## Host Ranges [code example] ## Common Connection Variables | Variable | Description | Example | |----------|-------------|---------| | `ansible_host` | IP or hostname to connect to | `10.0.1.10` | | `ansible_port` | SSH port | `2222` | | `ansible_user` | SSH username | `deploy` | | `ansible_ssh_private_key_file` | Path to SSH key | `~/.ssh/deploy_key` | | `ansible_python_interpreter` | Python path on remote | `/usr/bin/python3` | | `ansible_connection` | Connection type | `ssh`, `local`, `winrm` | | `ansible_become` | Enable privilege escalation | `true` | | `ansible_become_user` | User to become | `root` | ## Inventory Directory Structure For larger setups, use a directory with separate files: [code example] [code example] ## Multiple Inventories [code example] ## Host Patterns Target specific hosts or groups in commands: [code example] ## Dynamic Inventory For cloud environments... --- ## Ansible Inventory for Dev, Staging, Production URL: https://www.ansiblebyexample.com/articles/ansible-multi-environment-dev-staging-production Description: Set up Ansible inventory for dev, staging, and production environments. Learn multi-environment host groups, variables, and configuration patterns. # Ansible Multi-Environment — Dev Staging Production ## Introduction Managing Ansible inventory across dev, staging, and production environments requires a clear structure for hosts, groups, and environment-specific variables. This guide shows you how to organize your Ansible inventory to deploy consistently across multiple environments while keeping configurations separate and maintainable. ## Overview Effective multi-environment Ansible deployments depend on proper inventory organization. You'll learn to structure host groups by environment, manage environment-specific variables, validate deployments across environments, and implement best practices for consistency and reliability. ## Inventory Structure Define dev, staging, and production as separate groups in your inventory file, then keep each environment's variables in its own `group_vars` file: [code example] [code example] With this layout, `ansible-playbook -i inventory/hosts.ini site.yml --limit staging` targets only the staging hosts, while `group_vars/.yml` supplies the variables specific to that group. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validat... --- ## Ansible Inventory Groups — Organize Hosts for Targeted Automation URL: https://www.ansiblebyexample.com/articles/ansible-inventory-groups-organize-hosts-for-targeted-automation Description: Organize Ansible inventory into groups and nested groups. Target specific hosts with patterns, use group variables, and build dynamic inventory structures. # Ansible Inventory Groups — Organize Hosts for Targeted Automation ## Introduction Inventory groups let you target specific sets of hosts — run a playbook on all web servers, or just the production database tier. This guide covers static group definitions, nested groups, host patterns, group variables, and common organizational patterns for real infrastructure. ## Basic Group Structure [code example] ## YAML Format [code example] ## Nested Groups (Children) [code example] ## Environment-Based Organization [code example] [code example] ## Host Patterns [code example] ## Group Variables [code example] [code example] ## Host Variables [code example] [code example] ## Variable Precedence (Group Level) [code example] ## Real-World Patterns ### Functional Grouping [code example] ### Geographic Grouping [code example] ### Combined Pattern [code example] ## Playbook Targeting [code example] ## Magic Groups Ansible automatically creates two groups: [code example] ## List and Debug Groups [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "No hosts matched" | Check group name spelling, verify with `--list-hosts` | | Variable not applying | Check precedence — `host_vars` > `child group_vars` > `parent group_vars` | | Host in wrong group | Run `ansible-inventory --graph` to visualize | | Duplicate host warnings | Same host listed in multiple places — use `:children` instead | | Group vars file ignored | Filename must match ... --- ## Ansible Inventory Guide — Static, Dynamic, and Advanced Patterns URL: https://www.ansiblebyexample.com/articles/ansible-inventory-guide-static-dynamic-patterns Description: Master Ansible inventory from basics to advanced. Cover INI and YAML formats, dynamic inventory plugins, host patterns, groups, variables. ## Introduction The inventory is Ansible's source of truth — it defines which hosts to manage, how to group them, and what variables apply. Whether you use a simple INI file with 5 servers or dynamic inventory pulling thousands of hosts from AWS, understanding inventory is fundamental to every Ansible workflow. ## INI Format (Simple) [code example] ## YAML Format (Recommended) [code example] ## Host and Group Variables ### Inline Variables [code example] ### Variable Files (Best Practice) [code example] [code example] [code example] ### Variable Precedence [code example] ## Host Patterns [code example] ## Dynamic Inventory ### AWS EC2 [code example] [code example] ### Azure [code example] ### GCP [code example] ### ServiceNow CMDB [code example] ## Multiple Inventory Sources [code example] [code example] ## Multi-Environment Setup [code example] [code example] ## Inventory Plugins [code example] ## Verify Inventory [code example] ## Inventory Best Practices [code example] ## Complete Example [code example] ## Related Articles - Ansible Playbook Guide - Ansible Variables Guide - Ansible Vault Guide - Ansible ServiceNow Integration ## Conclusion Ansible inventory ranges from simple INI files to multi-cloud dynamic discovery. Master these patterns: use YAML format for readability, `group_vars/` and `host_vars/` directories for clean variable management, dynamic inventory plugins for cloud environments, and host patterns for flexible ta... --- ## Ansible Inventory Parse Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-inventory-parse-error-fix-and-solutions Description: Fix inventory file parsing errors from YAML syntax and plugin config issues. Tested on real machines with clear, copy-paste examples. # Ansible Inventory Parse Error — Fix and Solutions ## Introduction Fix inventory file parsing errors from YAML syntax and plugin config issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix inventory file parsing errors from YAML syntax and plugin config issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Inventory Patterns: Target Groups, Hosts & Access groups Variable URL: https://www.ansiblebyexample.com/articles/ansible-inventory-patterns-target-hosts-and-groups Description: Master inventory patterns to target Ansible hosts and groups. Learn unions, intersections, exclusions, wildcards, regex, and the groups variable. # Ansible Inventory Patterns — Target Hosts and Groups ## Introduction Inventory patterns control which hosts Ansible targets. Instead of running against all hosts, you can target specific groups, use wildcards, combine groups with AND/OR/NOT logic, and use regex — all from the command line or in playbooks. ## Basic Patterns [code example] ## Wildcard Patterns [code example] ## Group Operations ### Union (OR) — hosts in either group [code example] ### Intersection (AND) — hosts in BOTH groups [code example] ### Exclusion (NOT) — hosts NOT in a group [code example] ### Complex Patterns [code example] ## Regex Patterns [code example] ## Numeric Ranges [code example] ## Playbook Targeting [code example] [code example] ## --limit Flag Restrict targets at runtime without editing playbooks: [code example] ## Inventory Listing [code example] Output: [code example] ## Special Groups | Group | Contains | |-------|----------| | `all` | Every host in inventory | | `ungrouped` | Hosts not in any group (except `all`) | | `localhost` | The control machine | [code example] ## Nested Groups [code example] [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "No hosts matched" | Check pattern syntax and inventory: `ansible-inventory --list` | | Wrong hosts selected | Use `--list-hosts` to preview: `ansible-playbook site.yml --list-hosts` | | Host in wrong group | Check inventory structure: `ansible-inventory --graph` | | Pattern not... --- ## Ansible Inventory Plugin Development — Custom Sources URL: https://www.ansiblebyexample.com/articles/ansible-inventory-plugin-development-custom-sources Description: Ansible Inventory Plugin Development guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Inventory Plugin Development — Custom Sources ## Introduction Custom Sources. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Inventory Plugin Development requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible Inventory with Podman URL: https://www.ansiblebyexample.com/articles/using-ansible-inventory-with-podman-containers Description: Discover how to assign Podman containers in an Ansible inventory.ini file and execute automation playbooks. Tested, copy-paste examples included. ## Introduction Ansible provides powerful automation capabilities for managing containerized workloads, including those running on **Podman**. One crucial step in automating Podman containers with Ansible is defining the **inventory**, which tells Ansible how to interact with managed hosts. In this guide, we'll cover how to properly define a **Podman container in Ansible inventory**, using both **static and dynamic inventory approaches**. ## Setting Up Ansible Inventory for Podman By default, Ansible uses SSH to connect to remote machines. However, when dealing with **Podman containers**, a more efficient way is to use the **`podman` connection plugin** instead of SSH. ### 1. Define a Static Inventory (`inventory.ini`) The easiest way to specify a Podman container in the inventory is by directly listing it inside the `inventory.ini` file: [code example] - `my_container` is the **name** of the running Podman container. - `ansible_connection=podman` tells Ansible to use the Podman connection plugin instead of SSH. You can then run Ansible commands against the Podman container: [code example] ### 2. Using a Dynamic Inventory Script If you have multiple Podman containers and want to dynamically fetch their names and IPs, you can use a **custom dynamic inventory script**. #### Example: Dynamic Inventory with Python Create a script `podman_inventory.py`: [code example] Make it executable: [code example] Run it to check the output: [code example] Then, use it as ... --- ## Ansible inventory_hostname vs ansible_hostname Explained URL: https://www.ansiblebyexample.com/articles/ansible-inventory-hostname-vs-ansible-hostname Description: inventory_hostname vs ansible_hostname in Ansible: when to use each. Examples for templates, conditionals, hostvars, and multi-inventory setups. ## Introduction Ansible has two hostname variables that look similar but come from completely different sources. Confusing them is a common source of bugs — especially in templates, conditionals, and when your inventory uses IPs instead of hostnames. ## The Difference | Variable | Source | When Set | Example | |----------|--------|----------|---------| | `inventory_hostname` | Your **inventory file** | Always available | `web-01.example.com` or `10.0.0.5` | | `inventory_hostname_short` | First part of `inventory_hostname` | Always available | `web-01` or `10` | | `ansible_hostname` | Remote host (`hostname -s`) | After fact gathering | `web-01` | | `ansible_fqdn` | Remote host (`hostname -f`) | After fact gathering | `web-01.example.com` | | `ansible_nodename` | Remote host (`uname -n`) | After fact gathering | `web-01` | **Key insight:** `inventory_hostname` is what **you wrote** in the inventory. `ansible_hostname` is what the **remote machine** thinks its name is. ## When They Differ ### Inventory Uses IP Addresses [code example] [code example] ### Inventory Uses Aliases [code example] [code example] ### Hostname Mismatch [code example] But the server's hostname is just `web-01`: [code example] ## Which One to Use ### Use `inventory_hostname` When: [code example] ### Use `ansible_hostname` When: [code example] ### Use `ansible_fqdn` When: [code example] ## Common Patterns ### Fix Hostname Mismatch [code example] ### Build Host-Specific File Paths ... --- ## Ansible ios_command Module — Run Commands on Cisco IOS Devices URL: https://www.ansiblebyexample.com/articles/ansible-ios-command-module-run-commands-on-cisco-ios-devices Description: Execute show commands and operational commands on Cisco IOS routers/switches. Hands-on, tested examples and best practices for Ansible ios_command Module. # Ansible ios_command Module — Run Commands on Cisco IOS Devices ## Introduction The `cisco.ios.ios_command` module execute show commands and operational commands on Cisco IOS routers/switches. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install cisco.ios` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `cisco.ios.ios_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `-... --- ## Ansible ios_config Module — Manage Cisco IOS Configuration URL: https://www.ansiblebyexample.com/articles/ansible-ios-config-module-manage-cisco-ios-configuration Description: Deploy and manage configuration on Cisco IOS network devices with Ansible. Hands-on, tested examples and best practices for Ansible ios_config Module. # Ansible ios_config Module — Manage Cisco IOS Configuration ## Introduction The `cisco.ios.ios_config` module deploy and manage configuration on Cisco IOS network devices with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install cisco.ios` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `cisco.ios.ios_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` b... --- ## Ansible ios_facts Module — Gather Cisco IOS Device Facts URL: https://www.ansiblebyexample.com/articles/ansible-ios-facts-module-gather-cisco-ios-device-facts Description: Collect hardware, software, and interface facts from Cisco IOS devices. Tested on real machines with clear, copy-paste examples. # Ansible ios_facts Module — Gather Cisco IOS Device Facts ## Introduction The `cisco.ios.ios_facts` module collect hardware, software, and interface facts from Cisco IOS devices. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install cisco.ios` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `cisco.ios.ios_facts` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before a... --- ## Ansible iptables — Firewall Rules URL: https://www.ansiblebyexample.com/articles/ansible-iptables-module-linux-firewall-rules Description: Manage Linux iptables firewall rules with Ansible. Complete guide to ansible.builtin.iptables module — chains, rules, NAT, port forwarding, rate limiting,. ## Introduction `ansible.builtin.iptables` manages Linux firewall rules directly — no firewalld or ufw abstraction layer. It's the module you need when managing servers that use raw iptables (common in containers, minimal installs, legacy systems, and custom network appliances). This guide covers every common pattern: allowing services, blocking traffic, NAT, port forwarding, rate limiting, and persisting rules across reboots. ## Module Parameters | Parameter | Description | Example | |---|---|---| | `chain` | Chain to operate on | `INPUT`, `OUTPUT`, `FORWARD`, `PREROUTING`, `POSTROUTING` | | `table` | Table | `filter` (default), `nat`, `mangle`, `raw` | | `protocol` | Protocol | `tcp`, `udp`, `icmp` | | `source` | Source IP/CIDR | `10.0.0.0/8` | | `destination` | Destination IP/CIDR | `192.168.1.0/24` | | `source_port` | Source port | `1024:65535` | | `destination_port` | Destination port | `80`, `443`, `8080:8090` | | `jump` | Target | `ACCEPT`, `DROP`, `REJECT`, `LOG`, `DNAT`, `SNAT`, `MASQUERADE` | | `state` | Rule state | `present`, `absent` | | `action` | Where to add | `insert` (top), `append` (bottom) | | `in_interface` | Input interface | `eth0` | | `out_interface` | Output interface | `eth1` | | `ctstate` | Connection state | `NEW`, `ESTABLISHED`, `RELATED` | | `comment` | Rule comment | `"Allow SSH"` | | `limit` | Rate limit | `25/minute` | | `limit_burst` | Burst limit | `100` | | `ip_version` | IP version | `ipv4`, `ipv6` | ## Basic Firewall Rules ### Allow ... --- ## Ansible iso_create — Build ISO Images URL: https://www.ansiblebyexample.com/articles/create-iso-image-from-files-and-folders-ansible-module-iso-create Description: Create ISO images from files and folders with the Ansible iso_create module. Build bootable ISOs, custom install media, and automated image pipelines. ## How to Create ISO image from Files and Folders with Ansible? ## Create ISO images from the Files and Folders - `community.general.iso_create` - Generate ISO files with specified files or folders Let's talk about the Ansible module `iso_create`. The full name is `community.general.iso_create`, which means that is part of the collection of modules "community.general" maintained by the Ansible Community. This module requires the extra `pycdlib` Python library. You can easily install the `pycdlib` Python library using PIP, the Python Package Installer. The purpose of the module is to generate ISO files with specified files or folders. ## Parameters - `dest_iso` path - ISO file absolute path - `src_files` list - absolute paths of source files or folder - `interchange_level` integer - ISO9660 standards (1–4) - `joliet` integer - Joliet extension (1–3) - `rock_ridge` string - Rock Ridge extension (1.09, 1.10, 1.12) - `udf` boolean - no/yes UDF support 2.60 Let me summarize the main parameters of the module `iso_create`. The required parameters are "dest_iso" and "src_files". The "dest_iso" parameter contains the generated ISO file absolute path according to the ISO9660 standard. The "src_files" parameter contains the list of absolute paths of source files or folders. You probably would like to set to four the "interchange_level" parameter because it allows you to specify which of the fourth ISO9660 standards to support, default to "1". Level 1 is the most restrictive standa... --- ## Ansible java_cert Module — Manage Java Keystore Certificates URL: https://www.ansiblebyexample.com/articles/ansible-java-cert-module-manage-java-keystore-certificates Description: Import and manage SSL certificates in Java keystores (cacerts) with Ansible. Hands-on, tested examples and best practices for Ansible java_cert Module. # Ansible java_cert Module — Manage Java Keystore Certificates ## Introduction The `community.general.java_cert` module import and manage SSL certificates in Java keystores (cacerts) with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.java_cert` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mod... --- ## Ansible jenkins_job Module — Manage Jenkins Jobs URL: https://www.ansiblebyexample.com/articles/ansible-jenkins-job-module-manage-jenkins-jobs Description: Create, configure, enable, disable, and delete Jenkins CI/CD jobs with Ansible. Hands-on, tested examples and best practices for Ansible jenkins_job Module. # Ansible jenkins_job Module — Manage Jenkins Jobs ## Introduction The `community.general.jenkins_job` module create, configure, enable, disable, and delete Jenkins CI/CD jobs with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.jenkins_job` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** —... --- ## Ansible Jewel — Centralized Auth Proxy for AWX Services URL: https://www.ansiblebyexample.com/articles/ansible-jewel-centralized-auth-proxy-for-awx-services Description: Ansible Jewel is the new authentication and proxy layer for AWX modernization. Learn its architecture, setup, and how it connects Ansible services. # Ansible Jewel — Centralized Auth Proxy for AWX Services ## Introduction Ansible Jewel is a centralized authentication, authorization, and proxy layer announced as part of the AWX modernization effort. It intercepts user requests, authenticates them, and routes traffic to the appropriate Ansible service — replacing the monolithic AWX architecture with a pluggable, microservices-friendly design. This article covers what Jewel is, why it matters, and how it fits into the future of AWX. ## What Is Ansible Jewel? Jewel sits between users and Ansible services as a reverse proxy with built-in auth: [code example] **Key responsibilities:** - **Authentication** — verifies user identity (SSO, tokens, OAuth) - **Authorization** — checks permissions before forwarding requests - **Routing** — directs traffic to the correct backend service - **Service discovery** — connects pluggable Ansible services ## Why Jewel Exists The AWX modernization effort is decomposing AWX from a single Django application into smaller, focused services: | Before (Monolithic AWX) | After (With Jewel) | |------------------------|-------------------| | Single Django app handles everything | Jewel handles auth + routing | | Auth tightly coupled to AWX | Auth is a separate, reusable layer | | Adding services requires modifying AWX | New services plug in via Jewel | | Single point of failure | Services scale independently | ## Architecture [code example] ## Getting Started The Jewel source code is avai... --- ## Ansible Jinja2 Conditionals — Ternary URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-conditional-ternary-service-type-with-expose-service Description: Use Jinja2 ternary, bool, and if-else expressions in Ansible. Inline conditionals for variables, templates, and task parameters with examples. ## Introduction Jinja2 inline conditionals let you set variables dynamically in Ansible — choosing between values based on conditions, all within a single expression. The most common pattern is the ternary (if-else) expression, but there are several approaches depending on your use case. ## The Ternary Pattern ### Basic Syntax [code example] ### Kubernetes Service Type Example [code example] ## The Boolean Trap ### The Problem [code example] When `expose_service` is a **boolean `true`**, comparing it to the string `'true'` fails silently — the condition evaluates to `false`, and you always get `ClusterIP`. ### The Fix: Use `| bool` [code example] The `| bool` filter normalizes any input to a proper boolean: | Input | `| bool` Result | |-------|----------------| | `true` | `True` | | `'true'` | `True` | | `'yes'` | `True` | | `'1'` | `True` | | `1` | `True` | | `false` | `False` | | `'false'` | `False` | | `'no'` | `False` | | `'0'` | `False` | | `0` | `False` | ## The Ternary Filter Ansible provides a dedicated `ternary` filter as an alternative: [code example] ### Ternary vs Inline If-Else [code example] The `ternary` filter is cleaner when chaining with other filters. ## Common Patterns ### Default Values [code example] ### Nested Conditions [code example] ### Conditional List Items [code example] ### String Manipulation with Conditions [code example] ## Practical Examples ### Kubernetes Deployment [code example] ### Platform-Specific Config... --- ## Ansible Jinja2 Filters — Complete Reference Guide URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-filters-complete-reference-guide Description: Ansible Jinja2 Filters guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Jinja2 Filters — Complete Reference Guide ## Introduction Complete Reference Guide. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Jinja2 Filters requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible Jinja2 Filters — map, select, reject, json_query URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-filters-map-select-reject-json-query Description: Master Ansible Jinja2 filters for data transformation. Use map, select, reject, selectattr, json_query, regex_replace, and combine to process complex data. # Ansible Jinja2 Filters — map, select, reject, json_query ## Introduction Jinja2 filters transform data inline — extracting fields from lists, filtering objects by attributes, reformatting strings, and querying nested JSON structures. Ansible adds dozens of custom filters beyond standard Jinja2. This guide covers the filters you'll use most often with practical examples. ## map — Transform Every Item [code example] ## select / reject — Filter Items [code example] ## selectattr / rejectattr — Filter by Attribute [code example] ## json_query (JMESPath) [code example] ## String Filters [code example] ## Collection Filters [code example] ## Type Conversion [code example] ## Chaining Filters (Real Example) [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | `list` not found | Add `\| list` after `map`/`select` (they return generators) | | `json_query` not found | Install `pip install jmespath` | | Regex backslash issues | Double-escape in YAML: `\\d` or use raw strings | | Type error in comparison | Cast first: `\| int` before comparing | | Empty result | Check attribute names; use `default([])` | ## Best Practices 1. **Always `| list`** — after `map`, `select`, `reject` (they return generators) 2. **Use `selectattr` + `map`** — filter then extract in one chain 3. **Prefer `json_query`** — for deeply nested structures 4. **Use `default()`** — prevent undefined variable errors 5. **Keep chains readable** — break long chains across li... --- ## Ansible Jinja2 length Filter — Count Items and String Length URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-length-filter-count-items-string-length Description: How to use the Jinja2 length filter in Ansible to count list items, measure string length, and use it in conditionals. Practical playbook examples. # Ansible Jinja2 length Filter — Count Items and String Length The `length` filter (also aliased as `count`) is one of the most used Jinja2 filters in Ansible. It returns the number of items in a list or the number of characters in a string. ## Basic Syntax [code example] ## Count Items in a List [code example] ## Use length in Conditionals [code example] ## Measure String Length [code example] ## Count Dictionary Keys [code example] ## Combine with Other Filters [code example] ## Full Playbook Example [code example] ## Common Patterns | Pattern | Description | |---------|-------------| | `list \| length` | Count list items | | `string \| length` | String character count | | `dict \| length` | Count dictionary keys | | `list \| length == 0` | Check if empty | | `list \| length > N` | Minimum items check | | `list \| unique \| length` | Count unique items | ## Related Articles - Ansible selectattr Filter — Filter lists by attributes - Ansible Facts — System information for length checks - Ansible assert Module — Validate conditions - Ansible Magic Variables — Built-in variables ## Conclusion The `length` filter is simple but powerful — use it for validation, conditional logic, and reporting in your Ansible playbooks. --- ## Ansible Jinja2 Template Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-template-error-fix-and-solutions Description: Fix Jinja2 template errors from undefined vars, syntax, and filter issues. Hands-on, tested examples and best practices for Ansible Jinja2 Template Error. # Ansible Jinja2 Template Error — Fix and Solutions ## Introduction Fix Jinja2 template errors from undefined vars, syntax, and filter issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix Jinja2 template errors from undefined vars, syntax, and filter issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Jinja2 Templates — Dynamic Configuration Files URL: https://www.ansiblebyexample.com/articles/ansible-jinja2-templates-dynamic-configuration Description: Use Ansible template module with Jinja2 to generate dynamic configuration files. Variables, loops, conditionals, filters, and practical template examples. ## Introduction The `ansible.builtin.template` module processes Jinja2 templates (`.j2` files) and deploys the rendered result to remote hosts. Variables, loops, conditionals, and filters let you generate dynamic configuration files from a single template. ## Basic Usage [code example] ## Template Syntax ### Variables [code example] ### Conditionals [code example] ### Loops [code example] ### Filters [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | Template file path (`.j2`) | | `dest` | (required) | Destination path on remote | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions | | `validate` | — | Validation command (`%s` = temp file) | | `backup` | `false` | Create backup before overwriting | | `force` | `true` | Overwrite if content differs | | `newline_sequence` | `\n` | Line ending style | | `trim_blocks` | `true` | Remove first newline after block tag | | `lstrip_blocks` | `false` | Strip leading whitespace from block lines | ## Practical Templates ### Nginx Virtual Host [code example] ### systemd Service Unit [code example] ### Application Config (YAML) [code example] ### SSH Config [code example] ## Advanced Jinja2 ### Whitespace Control [code example] ### Macros (Reusable Blocks) [code example] ### Include Other Templates [code example] ### Ternary Expressions [code example] ## Template with Validation [code example]... --- ## Ansible JSON Decode Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-json-decode-error-fix-and-solutions Description: Fix JSON parsing errors from invalid output, encoding, and module returns. Hands-on, tested examples and best practices for Ansible JSON Decode Error. # Ansible JSON Decode Error — Fix and Solutions ## Introduction Fix JSON parsing errors from invalid output, encoding, and module returns. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix JSON parsing errors from invalid output, encoding, and module returns. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible JSON Parsing — Filter & Transform URL: https://www.ansiblebyexample.com/articles/transforming-json-data Description: Parse, filter, and transform JSON data in Ansible playbooks. Use json_query, from_json, to_json, and JMESPath expressions with practical examples. ## Introduction Modern IT automation often requires handling complex JSON data, whether from APIs, configuration files, or dynamic inputs. Ansible, with its powerful filters like `from_json` and `json_query`, provides an elegant way to parse and transform JSON data into actionable formats. This guide walks you through parsing JSON data and transforming it into a structured list in an Ansible playbook. --- ## The Scenario You have a JSON string representing a nested structure, such as: [code example] The goal is to transform this JSON into a structured list: [code example] --- ## The Playbook Here’s how you can achieve this transformation: ### Ansible Code [code example] --- ## Explanation ### Key Steps 1. **Define Raw JSON String**: - Use the `set_fact` module to define a raw JSON string. - In real scenarios, this JSON could come from an API, a file, or another source. 2. **Parse JSON String**: - The `from_json` filter converts the JSON string into a Python dictionary, enabling further manipulation. 3. **Transform JSON Data**: - Use the `json_query` filter to extract and restructure the JSON. - Query: `[].{name: item, guestState: instance.guest.guestState}`. - Extracts `item` as `name`. - Extracts `instance.guest.guestState` as `guestState`. 4. **Display Results**: - The `debug` module outputs the transformed list for validation. --- ### Output After running the playbook, the debug task will display: [code example] --- ## H... --- ## Ansible JSON Transform and Search URL: https://www.ansiblebyexample.com/articles/transforming-and-searching-json-data Description: Learn how to parse JSON data in Ansible, transform it into structured lists, and search for specific criteria using filters like `selectattr`. This guide. ## Introduction Handling JSON data is a common task in IT automation workflows. Ansible simplifies this process with filters like `from_json`, `json_query`, and `selectattr`. This guide demonstrates how to: 1. Parse JSON data into a Python dictionary. 2. Transform the data into a structured list. 3. Search for specific criteria (e.g., if a `name` has a `guestState` of `"running"`). --- ## Use Case: Verify If a Guest Is Running Imagine receiving JSON data from an API or file, containing details about virtual machine states. Your task is to: 1. Transform this JSON data into a structured format. 2. Check if a specific `name` has its `guestState` set to `"running"`. 3. Return `true` or `false` based on the search. --- ## The Ansible Playbook Here’s how to achieve this: ### Playbook Example [code example] --- ## Explanation ### Key Sections 1. **Define Raw JSON String**: - A sample JSON string is defined using `set_fact`. In real-world scenarios, this data may come from an API or file. 2. **Parse JSON to Dictionary**: - The `from_json` filter converts the JSON string into a Python dictionary for further processing. 3. **Transform JSON to Formatted List**: - The `json_query` filter restructures the JSON into a list of dictionaries with `name` and `guestState` attributes. 4. **Search in the List**: - The `selectattr` filter dynamically searches for items in the list: - `selectattr('name', 'equalto', search_name)`: Filters items with the specified `na... --- ## Ansible junos_command Module — Run Commands on Juniper Junos Devices URL: https://www.ansiblebyexample.com/articles/ansible-junos-command-module-run-commands-on-juniper-junos-devices Description: Execute operational commands on Juniper routers and switches with Ansible. With clear, copy-paste, step-by-step examples. # Ansible junos_command Module — Run Commands on Juniper Junos Devices ## Introduction The `junipernetworks.junos.junos_command` module execute operational commands on Juniper routers and switches with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install junipernetworks.junos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `junipernetworks.junos.junos_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handl... --- ## Ansible junos_config Module — Manage Juniper Junos Configuration URL: https://www.ansiblebyexample.com/articles/ansible-junos-config-module-manage-juniper-junos-configuration Description: Deploy and manage configuration on Juniper Junos network devices. Follow clear, copy-paste examples and real-world usage notes for Ansible junos_config Module. # Ansible junos_config Module — Manage Juniper Junos Configuration ## Introduction The `junipernetworks.junos.junos_config` module deploy and manage configuration on Juniper Junos network devices. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install junipernetworks.junos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `junipernetworks.junos.junos_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test i... --- ## Ansible Kafka — Deploy Apache Kafka Message Streaming URL: https://www.ansiblebyexample.com/articles/ansible-kafka-message-streaming-cluster Description: Deploy Apache Kafka with Ansible. ZooKeeper and KRaft mode clusters, topic management, producer/consumer configuration, TLS/SASL security, monitoring with. ## Introduction Apache Kafka is the de facto standard for distributed event streaming — handling real-time data pipelines, event sourcing, and log aggregation at scale. Ansible automates the full deployment: ZooKeeper or KRaft mode clusters, broker configuration, topic management, TLS/SASL security, and monitoring via JMX and Prometheus. ## Deploy Kafka with KRaft (No ZooKeeper) [code example] ### KRaft Config Template [code example] ## Manage Topics [code example] ## TLS/SASL Security [code example] Add to server.properties: [code example] ## Monitoring with JMX [code example] ## Health Check [code example] ## Troubleshooting ### Under-Replicated Partitions [code example] ### Consumer Lag [code example] ## Related Articles - Ansible RabbitMQ - Ansible Redis - Ansible Docker Compose - Ansible Event-Driven EDA ## Conclusion Ansible deploys Kafka clusters in KRaft mode (no ZooKeeper dependency), manages topics with partitions and replication, configures TLS/SASL security, and enables JMX monitoring. Template broker configs from inventory — adding a node means adding a host to the group. Use Kafka for event streaming, log aggregation, and real-time data pipelines, all version-controlled as code. --- ## Ansible Keepalived — High Availability with VRRP URL: https://www.ansiblebyexample.com/articles/ansible-keepalived-high-availability-vrrp Description: Deploy Keepalived with Ansible for high availability. VRRP virtual IP failover, HAProxy/Nginx HA pairs, health check scripts, multicast and unicast modes,. ## Introduction Keepalived implements VRRP (Virtual Router Redundancy Protocol) for Linux — it provides virtual IP (VIP) failover between servers, making load balancers, databases, and any service highly available. Ansible automates Keepalived deployment: primary/backup pairs, health check scripts, notification hooks, and integration with HAProxy and Nginx. ## Basic VRRP Setup [code example] ### Config Template [code example] ## HAProxy + Keepalived HA [code example] ## Nginx + Keepalived HA [code example] ## Multiple VIPs [code example] [code example] ## Notification Script [code example] ## Health Check [code example] ## Troubleshooting ### Split-Brain Prevention [code example] ### VIP Not Floating [code example] ## Related Articles - Ansible HAProxy - Ansible Nginx - Ansible Firewall Module - Ansible sysctl Module ## Conclusion Keepalived provides sub-second failover for any service using VRRP virtual IPs. Ansible templates the config from inventory — the first host in the `ha_pair` group becomes MASTER, the rest are BACKUP. Health check scripts track service state and trigger failover automatically. Use unicast mode in cloud environments, multiple VIPs for active-active, and notification scripts for logging state transitions. High availability as code. --- ## Ansible kernel_blacklist Module — Blacklist Kernel Modules URL: https://www.ansiblebyexample.com/articles/ansible-kernel-blacklist-module-blacklist-kernel-modules Description: Prevent Linux kernel modules from loading by managing modprobe blacklist files. Tested on real machines with clear, copy-paste examples. # Ansible kernel_blacklist Module — Blacklist Kernel Modules ## Introduction The `community.general.kernel_blacklist` module prevent Linux kernel modules from loading by managing modprobe blacklist files. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.kernel_blacklist` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Te... --- ## Ansible known_hosts — Manage SSH Host Keys URL: https://www.ansiblebyexample.com/articles/ansible-known-hosts-manage-ssh-host-keys Description: Ansible known_hosts guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible known_hosts — Manage SSH Host Keys ## Introduction Manage SSH Host Keys. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible known_hosts requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective task ex... --- ## Ansible Kubernetes Operators — Deploy and Manage URL: https://www.ansiblebyexample.com/articles/ansible-kubernetes-operators-deploy-and-manage Description: Ansible Kubernetes Operators guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Kubernetes Operators — Deploy and Manage ## Introduction Deploy and Manage. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Kubernetes Operators requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selec... --- ## Ansible KVM Libvirt — Create and Manage Virtual Machines URL: https://www.ansiblebyexample.com/articles/ansible-kvm-libvirt-create-and-manage-virtual-machines Description: Automate KVM/libvirt virtual machines with Ansible. Create VMs, manage networks, storage pools, snapshots, and cloud-init provisioning with. # Ansible KVM Libvirt — Create and Manage Virtual Machines ## Introduction KVM (Kernel-based Virtual Machine) with libvirt is the standard Linux virtualization stack. With the `community.libvirt` Ansible collection, you can automate VM creation, network configuration, storage pools, snapshots, and cloud-init provisioning — treating your hypervisors as cattle, not pets. ## Prerequisites [code example] [code example] ## Create a Virtual Machine [code example] ## VM XML Template [code example] ## Cloud-Init Provisioning [code example] ## Manage VM State [code example] ## Storage Pools [code example] ## Network Management [code example] ## Batch VM Creation [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Permission denied | Add user to `libvirt` group or use `become: true` | | VM won't start | Check `virsh domblklist ` for missing disks | | No network | Verify default network: `virsh net-list --all` | | Python module missing | Install `python3-libvirt` on target host | | QEMU/KVM not available | Check `lsmod | grep kvm` — enable in BIOS | ## Best Practices 1. **Use cloud-init** for VM provisioning — no manual setup 2. **qcow2 backing files** for thin provisioning — save disk space 3. **VirtIO drivers** for best performance — disk and network 4. **Autostart critical VMs** — survive host reboots 5. **Snapshot before changes** — easy rollback 6. **QEMU guest agent** — enables graceful shutdown and IP reporting ## Conclusion The ... --- ## Ansible lambda Module — Manage AWS Lambda Functions URL: https://www.ansiblebyexample.com/articles/ansible-lambda-module-manage-aws-lambda-functions Description: Deploy and configure serverless AWS Lambda functions with Ansible. Hands-on, tested examples and best practices for Ansible lambda Module. # Ansible lambda Module — Manage AWS Lambda Functions ## Introduction The `amazon.aws.lambda` module deploy and configure serverless AWS Lambda functions with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.lambda` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before applying 5. **... --- ## Ansible LDAP — Manage OpenLDAP Users Groups and OUs URL: https://www.ansiblebyexample.com/articles/ansible-ldap-manage-openldap-users-groups-and-ous Description: Ansible LDAP guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible LDAP — Manage OpenLDAP Users Groups and OUs ## Introduction Manage OpenLDAP Users Groups and OUs. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible LDAP requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible LDAP & Active Directory URL: https://www.ansiblebyexample.com/articles/ansible-ldap-active-directory-user-management Description: Manage LDAP and Active Directory with Ansible. User provisioning, group management, OU creation, password resets, SSSD configuration, and bulk operations. ## Introduction LDAP (Lightweight Directory Access Protocol) and Active Directory are the backbone of enterprise identity management. Ansible's `community.general` collection provides modules for managing LDAP entries directly — create OUs, provision users, manage groups, reset passwords, and configure Linux hosts to authenticate against LDAP/AD via SSSD. This guide covers both OpenLDAP and Active Directory operations. ## Prerequisites [code example] ## LDAP Module Reference | Module | Purpose | |---|---| | `community.general.ldap_entry` | Create/delete LDAP entries | | `community.general.ldap_attrs` | Modify attributes on existing entries | | `community.general.ldap_search` | Search LDAP directory | | `community.general.ldap_passwd` | Set LDAP passwords | ## Connection Variables [code example] ## Create Organizational Units [code example] ## Provision Users ### Single User [code example] ### Bulk User Provisioning [code example] [code example] ## Manage Groups [code example] ## Password Management [code example] ## Search LDAP [code example] ## Configure SSSD (Linux → LDAP/AD Auth) [code example] [code example] ## Active Directory Specific [code example] [code example] ## Deprovisioning [code example] ## Troubleshooting ### Test LDAP Connection [code example] ### SSSD Cache Issues [code example] ## Related Articles - Ansible Windows AD Management - Ansible User Module - Ansible Vault Guide - Ansible Compliance Guide ## Conclusion Ansible... --- ## Ansible Learning Path from Beginner to Expert — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-learning-path-from-beginner-to-expert-complete-guide Description: Structured learning path for Ansible: fundamentals, intermediate patterns, advanced techniques, and certification. With tested, real-world examples. # Ansible Learning Path from Beginner to Expert — Complete Guide ## Introduction Structured learning path for Ansible: fundamentals, intermediate patterns, advanced techniques, and certification. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Structured learning path for Ansible: fundamentals, intermediate patterns, advanced techniques, and c... --- ## Ansible Let's Encrypt — Automate Free SSL/TLS Certificates URL: https://www.ansiblebyexample.com/articles/ansible-lets-encrypt-ssl-certificates-acme Description: Automate Let's Encrypt SSL certificates with Ansible. ACME protocol, HTTP-01 and DNS-01 challenges, Certbot and community.crypto modules, wildcard. ## Introduction Let's Encrypt provides free, automated TLS certificates via the ACME protocol. Ansible automates the entire lifecycle: account creation, domain validation (HTTP-01 or DNS-01 challenges), certificate issuance, Nginx/Apache configuration, and automated renewal. No more manual certificate management. ## Using community.crypto ACME Modules [code example] ## DNS-01 Challenge (Wildcard Certificates) [code example] ## Using Certbot [code example] ## Nginx SSL Configuration [code example] [code example] ## Certificate Monitoring [code example] ## Troubleshooting ### Rate Limits Use the staging server for testing: [code example] ### Challenge Validation Failing [code example] ## Related Articles - Ansible OpenSSL Certificates - Ansible Nginx - Ansible Apache HTTPD - Ansible Cron Module ## Conclusion Ansible automates the full Let's Encrypt lifecycle — account creation, challenge validation, certificate issuance, web server configuration, and renewal scheduling. Use `community.crypto.acme_certificate` for full control or Certbot for simplicity. DNS-01 challenges enable wildcard certificates. Set up cron-based renewal and certificate expiry monitoring to never have an expired certificate again. --- ## Ansible Lightspeed Beta Review: Hands-On with IBM Watson AI Code Assistant URL: https://www.ansiblebyexample.com/articles/ansible-lightspeed-with-ibm-watson-code-assistant-project-wisdom-beta Description: Hands-on review of the Ansible Lightspeed (Project Wisdom) closed beta. Real testing results, accuracy analysis, setup walkthrough, strengths,. I tested the early access closed beta of Red Hat's AI code assistant for Ansible — originally announced as **Project Wisdom** at AnsibleFest 2022 and later released as **Ansible Lightspeed with IBM Watson Code Assistant**. Here is my honest review after extensive testing. ## Background: From Project Wisdom to Lightspeed The journey of Ansible's AI assistant: - **AnsibleFest 2022**: Red Hat announces "Project Wisdom" — an AI service to generate Ansible code - **Early 2023**: Closed beta invitations sent to selected community members - **Red Hat Summit 2023**: Official launch as "Ansible Lightspeed with IBM Watson Code Assistant" - **Late 2023**: General availability of the free tier - **2024**: Enterprise tier with model customization via IBM watsonx I received access to the closed beta in early 2023, before the public announcement. ## Setup Experience The setup process was straightforward: ### Requirements - Visual Studio Code (minimum 1.70.1) - Red Hat Ansible VS Code extension - Beta invitation from the Ansible Development Team ### Installation 1. Install the "Ansible" extension by Red Hat in VS Code: 2. Enable Ansible Lightspeed in the extension settings: 3. Authenticate with your GitHub account (the beta required an invitation whitelist) The entire setup took less than 5 minutes — no complex configuration or API keys needed. ## How It Works in Practice The plugin operates seamlessly within VS Code. When writing a playbook, each time you type a task name in t... --- ## Ansible Lightspeed Complete Guide: AI-Powered Automation with IBM watsonx URL: https://www.ansiblebyexample.com/articles/ansible-lightspeed-with-ibm-watson-code-assistant Description: Complete guide to Ansible Lightspeed with IBM watsonx Code Assistant. Learn setup, features, model customization, prompt engineering, and how it. Ansible Lightspeed with IBM watsonx Code Assistant is Red Hat's purpose-built AI service that generates Ansible automation code from plain English task descriptions. Unlike general-purpose AI tools like ChatGPT or GitHub Copilot, Lightspeed is specifically trained on Ansible content and understands playbook structure, module parameters, and automation best practices. ## What Is Ansible Lightspeed? Ansible Lightspeed is an AI-powered code assistant integrated into Visual Studio Code through the official Red Hat Ansible extension. When you write a task name in a playbook, Lightspeed generates the corresponding Ansible code — module name, parameters, and values — based on your natural language description. The service was originally announced as **Project Wisdom** at AnsibleFest 2022 and launched as Ansible Lightspeed at Red Hat Summit 2023. It uses IBM's watsonx foundation models, specifically trained on Ansible Galaxy content, documentation, and curated automation examples. ### Key Capabilities - **Task generation**: Write a task name in English, get complete Ansible task code - **Context awareness**: Understands your playbook structure, variables, and previous tasks - **Content source attribution**: Shows which Ansible Galaxy collection or role influenced the suggestion - **Multi-task generation**: Generate entire task sequences from descriptions - **Model customization**: Organizations can tune the model on their own Ansible content (paid tier) ## How Ansible Lightspee... --- ## Ansible lineinfile — Change IP Address in Config URL: https://www.ansiblebyexample.com/articles/edit-single-line-text-ansible-playbook-for-changing-ip-address-of-remote-hosts Description: This playbook uses the ansible.builtin.lineinfile and ansible.builtin.service modules to automate the process of updating the IP address and netmask. Automating the process of updating the IP address and netmask values in the network configuration file of multiple remote hosts can be a time-consuming and tedious task. However, with Ansible, it's possible to automate this process and save time and effort. Ansible is an open-source automation tool that allows users to automate IT infrastructure tasks, including configuration management, application deployment, and orchestration. One of the key features of Ansible is its ability to manage multiple remote hosts simultaneously, making it an ideal choice for managing large-scale IT infrastructure. In this article, we will explore how to use Ansible to automate the process of updating the IP address and netmask values in the network configuration file of remote hosts. ## Ansible module lineinfile Today we're talking about the Ansible module lineinfile. The full name is `ansible.builtin.lineinfile`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years and it supports a large variety of operating systems. You are able to insert, update and remove a single line of text in a file. ### Main Parameters - path _string_ - file path - line _string_ - text - insertafter/insertbefore _string_ - EOF/regular expression - validate _string_ - validation command - create _boolean_ - create if not exist - state _string_ - present/absent - owner/group/mode - permission - setype/seuser/selevel - SELinux... --- ## Ansible lineinfile Module — Add, Replace, Remove Lines URL: https://www.ansiblebyexample.com/articles/ansible-lineinfile-module-add-replace-remove-lines Description: Add, replace, and remove lines in config files with ansible.builtin.lineinfile. Regex patterns, insertafter, insertbefore, backrefs, and validate examples. ## Introduction `ansible.builtin.lineinfile` manages individual lines in text files — add a line, replace a line matching a pattern, or remove lines. It's the go-to module for small, targeted file edits without rewriting the entire file with `template` or `copy`. ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `path` | (required) | File to modify | | `line` | — | Line content to add/ensure | | `regexp` | — | Regex to find existing line | | `state` | `present` | `present` to add/ensure, `absent` to remove | | `insertafter` | `EOF` | Insert after matching line/`EOF`/`BOF` | | `insertbefore` | — | Insert before matching line/`BOF` | | `backrefs` | `false` | Use regex backreferences in `line` | | `create` | `false` | Create file if it doesn't exist | | `backup` | `false` | Create backup before editing | | `mode` | — | File permissions | | `owner` | — | File owner | | `validate` | — | Validation command | | `firstmatch` | `false` | Replace only the first match | ## Add a Line [code example] ## Ensure a Line Exists (Idempotent) [code example] ## Replace a Line (regexp + line) When you specify both `regexp` and `line`: - If a line matches `regexp` → **replace** it with `line` - If no line matches → **add** `line` at end of file [code example] ## Remove a Line [code example] ## Insert After/Before [code example] ## Backreferences Capture groups from `regexp` and use them in `line`: [code example] ⚠️ With `backrefs: true`, ... --- ## Ansible lineinfile Module: Edit Lines in Config Files URL: https://www.ansiblebyexample.com/articles/ansible-lineinfile-module-edit-lines-in-config-files Description: Master the Ansible lineinfile module — add, replace, and remove lines in configuration files. Practical examples for sshd_config, sysctl, hosts file. ## The ansible.builtin.lineinfile Module The `lineinfile` module ensures a specific line exists (or doesn't exist) in a file. It's the Ansible equivalent of `sed -i` — but idempotent. ## Add a Line to a File [code example] ## Replace a Line (Using Regex) [code example] ## Remove a Line [code example] ## Insert After or Before a Line [code example] ## Practical Examples ### Secure sshd_config [code example] ### Set Kernel Parameters in sysctl.conf [code example] ### Manage /etc/hosts [code example] ### Set Environment Variables [code example] ## lineinfile vs blockinfile | Module | Use case | |--------|----------| | `lineinfile` | Single line changes | | `blockinfile` | Multi-line blocks | | `template` | Entire file generation | [code example] ## Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `path` | Target file | `/etc/ssh/sshd_config` | | `line` | Line content | `"Port 2222"` | | `regexp` | Match pattern | `'^Port\s+'` | | `state` | present/absent | `present` | | `insertafter` | Insert after match | `'^\[section\]'` | | `insertbefore` | Insert before match | `'^# End'` | | `create` | Create file if missing | `true` | | `backup` | Backup before change | `true` | | `validate` | Validation command | `'visudo -cf %s'` | --- *Browse 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible Linode — Deploy Cloud Instances URL: https://www.ansiblebyexample.com/articles/ansible-linode-deploy-cloud-instances Description: Ansible Linode guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Linode — Deploy Cloud Instances ## Introduction Deploy Cloud Instances. Automate Linode infrastructure with Ansible using the `linode.cloud` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches Linode naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/produc... --- ## Ansible Lint — Check Playbooks for Errors and Best Practices URL: https://www.ansiblebyexample.com/articles/ansible-lint-check-playbooks-errors-best-practices Description: Use ansible-lint to catch mistakes, enforce best practices, and improve playbook quality. Rules, configuration, CI integration, and fixing common warnings. ## Introduction `ansible-lint` checks playbooks, roles, and task files for errors, anti-patterns, and best practice violations. It catches problems before you run anything — missing names, deprecated syntax, command modules used instead of proper modules, and more. ## Install [code example] ## Basic Usage [code example] ## Common Rules | Rule | Description | |------|-------------| | `name[missing]` | Task is missing a name | | `fqcn[action-core]` | Use FQCN for builtin modules | | `yaml[truthy]` | Use `true`/`false` not `yes`/`no` | | `no-changed-when` | Command/shell missing `changed_when` | | `command-instead-of-module` | Use module instead of command | | `risky-shell-pipe` | Shell pipe without `pipefail` | | `no-jinja-when` | Don't use `{{ }}` in `when` | | `var-naming` | Variable name doesn't match pattern | | `role-name` | Role name doesn't match pattern | | `schema` | YAML doesn't match Ansible schema | ## Fix Common Issues ### name[missing] — Add Task Names [code example] ### fqcn — Use Fully Qualified Names [code example] ### yaml[truthy] — Use true/false [code example] ### no-changed-when — Mark Command Tasks [code example] ### command-instead-of-module [code example] ### no-jinja-when [code example] ## Configuration [code example] ### Profiles | Profile | Strictness | Best For | |---------|-----------|----------| | `null` | No rules | Disabled | | `min` | Minimal | Getting started | | `basic` | Standard | Most projects | | `moderate` | Strict... --- ## Ansible lint — Validate Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-lint-validate-improve-playbooks Description: Use ansible-lint to find errors, enforce best practices, and improve playbook quality. Install, configure, and fix common lint warnings. ## Introduction `ansible-lint` checks playbooks, roles, and collections against best practices and known anti-patterns. It catches errors before they hit production: deprecated syntax, missing FQCN, unsafe shell commands, missing `changed_when`, and more. ## Install [code example] ## Basic Usage [code example] ## Common Rules and Fixes ### name[missing] — Tasks Need Names [code example] ### fqcn[action-core] — Use Fully Qualified Collection Names [code example] ### command-instead-of-module — Use Modules [code example] ### no-changed-when — shell/command Need changed_when [code example] ### yaml[truthy] — Boolean Values [code example] ### risky-shell-pipe — Pipe Error Handling [code example] ### jinja[spacing] — Jinja2 Whitespace [code example] ## Configuration ### .ansible-lint [code example] ### Profiles | Profile | Strictness | Use Case | |---------|-----------|----------| | `null` | None | Just parse, no rules | | `min` | Minimal | Basic syntax only | | `basic` | Low | Common mistakes | | `moderate` | Medium | Team projects | | `safety` | High | Security-focused | | `shared` | High | Published roles | | `production` | Highest | Production code | [code example] ## Inline Skip [code example] ## CI/CD Integration ### GitHub Actions [code example] ### GitLab CI [code example] ### Pre-commit Hook [code example] ## Fix Automatically [code example] ## Custom Rules [code example] [code example] ## Common Workflow [code example] ## Relate... --- ## Ansible Lint Rule 302: deprecated-command-syntax — Fix Shorthand URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-302-deprecated-command-syntax Description: Fix Ansible Lint rule 302 deprecated-command-syntax by replacing shorthand free-form syntax with structured args. Examples for command, shell, raw. ## Introduction Ansible Lint rule 302, `deprecated-command-syntax`, flags the use of shorthand (free-form) syntax for command-line modules within playbooks. While shorthand is convenient on the command line, it creates hard-to-debug playbooks by mixing commands with module parameters in a single string. This guide shows how to convert shorthand to structured syntax. ## The Rule **Rule ID:** 302 **Name:** `deprecated-command-syntax` **Description:** Using command rather than an ideally suited module is acceptable, but shorthand syntax should not be used inside playbooks **Severity:** Error **Tags:** `command-shell`, `deprecations` ## Problematic Code [code example] In this example, `creates=B` and `chmod 644 A` are mixed in a single free-form string. Ansible must parse this ambiguously — is `creates=B` a parameter or part of the command? More problematic examples: [code example] ## Correct Code Convert shorthand parameters to the `args` block: [code example] Or use the fully structured format: [code example] ### More Corrections [code example] [code example] [code example] ## Affected Modules This rule applies to all command-line modules that support free-form syntax: | Module | Common Shorthand Parameters | |--------|----------------------------| | `ansible.builtin.command` | `creates`, `removes`, `chdir`, `stdin` | | `ansible.builtin.shell` | `creates`, `removes`, `chdir`, `executable` | | `ansible.builtin.raw` | `executable` | | `ansible.builtin.script` ... --- ## Ansible Lint Rule 402: latest[hg] — Pin Mercurial Revisions URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-402-latest-hg Description: Fix Ansible Lint rule 402 latest[hg] by pinning Mercurial repository revisions. Learn why HEAD is risky, how to pin commits, and when to skip the rule. ## Introduction Ansible Lint rule 402, `latest[hg]`, flags playbook tasks that use unpinned Mercurial (hg) repository checkouts. Using `HEAD` or leaving the revision unspecified means your playbook's behavior depends on whatever happens to be the latest commit — making it non-reproducible and potentially breaking. This rule is part of the broader `latest` family that also covers Git repositories (`latest[git]`). ## The Rule **Rule ID:** 402 **Name:** `latest[hg]` **Description:** Ensures that `community.general.hg` module calls specify a pinned revision **Severity:** Warning **Tags:** `idempotency` The rule triggers when: - `revision: HEAD` is specified - No `revision` is specified (defaults to tip/HEAD) ## Problematic Code [code example] **Why this is problematic:** - `HEAD` (or tip) changes with every commit - Running the same playbook today and tomorrow may produce different results - No way to trace which version is deployed - Rollbacks become impossible ## Correct Code [code example] ### Other Valid Pinning Methods [code example] **Best practice ranking:** 1. **Changeset hash** (most reproducible) — `a1b2c3d4e5f6` 2. **Tag** (good for releases) — `v2.1.0` 3. **Branch name** (least reproducible — still moves) — `stable` ## When to Skip the Rule If you intentionally want the latest code (e.g., development environments), suppress the warning: [code example] Or in `.ansible-lint` configuration: [code example] Or skip all `latest` rules: [code example] ##... --- ## Ansible Lint Rule parser-error — Fix YAML Syntax Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-parser-error Description: Fix Ansible Lint parser-error by correcting YAML syntax — indentation, spacing, quoting, and structure. Complete guide with common patterns. ## Introduction The `parser-error` rule in ansible-lint fires when your playbook has YAML syntax problems that prevent Ansible from parsing the file at all. Unlike other lint rules that check best practices, parser errors mean the playbook **cannot run** — they must be fixed before anything else. ## The Rule **Rule name:** `parser-error` **Severity:** Fatal **Tags:** `core`, `unskippable` This rule **cannot be skipped** — it represents genuine syntax errors that make the playbook unparseable. ## Common Causes and Fixes ### 1. Missing Space After Colon The most frequent YAML mistake: [code example] ### 2. Inconsistent Indentation YAML requires consistent spaces (never tabs): [code example] ### 3. Tabs Instead of Spaces YAML forbids tabs entirely: [code example] Detect tabs: [code example] ### 4. Unquoted Special Characters Colons, brackets, and other YAML special characters in values need quoting: [code example] [code example] ### 5. Wrong List Format [code example] ### 6. Duplicate Keys [code example] ### 7. Incorrect Boolean/String Mixing [code example] ### 8. Missing Document Start [code example] ## Debugging Parser Errors ### Check Syntax Before Running [code example] ### Find the Exact Error Location ansible-lint output shows the file and line: [code example] This means line 8, column 5 has the issue. ### VS Code Integration Install the Ansible extension for VS Code — it highlights parser errors in real-time: [code example] The extens... --- ## Ansible Lint sanity — Ignore Files URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-sanity Description: Fix Ansible Lint sanity rule errors. Learn about ignore-x.x.txt validation, allowed ignores, cannot-ignore and bad-ignore errors, and Red Hat. ## Introduction The Ansible Lint `sanity` rule validates the `ignore-x.x.txt` files used in Ansible collections. These files define exemptions from sanity tests — but not all exemptions are allowed. This rule enforces that only approved ignores are used, maintaining code quality standards required for Red Hat Certification and Ansible Galaxy publishing. ## The Rule **Rule name:** `sanity` **Tags:** `idiom` **Scope:** Ansible collections (not standalone playbooks) The rule checks `tests/sanity/ignore-*.txt` files in your collection to ensure: 1. Only permitted ignores are used 2. Ignore entries follow the correct format ## Error Messages ### sanity[cannot-ignore] Triggered when an ignore entry uses a test that is **not in the allowed list**: [code example] **Fix:** Remove the ignore entry and fix the underlying issue instead. ### sanity[bad-ignore] Triggered when an ignore entry has **incorrect formatting**: [code example] **Fix:** Ensure each line follows the format: [code example] ## Allowed Ignores The following ignores are permitted across all Ansible versions: | Ignore | Purpose | |--------|---------| | `validate-modules:missing-gplv3-license` | Module missing GPLv3 license header | | `action-plugin-docs` | Action plugin documentation | | `import-2.6` / `import-2.6!skip` | Python 2.6 import compatibility | | `import-2.7` / `import-2.7!skip` | Python 2.7 import compatibility | | `import-3.5` / `import-3.5!skip` | Python 3.5 import compatibility | | `compile... --- ## Ansible Linux chrt Process Scheduling URL: https://www.ansiblebyexample.com/articles/optimizing-linux-with-chrt-mastering-process-scheduling Description: Explore chrt scheduling policies: SCHED_BATCH, SCHED_DEADLINE, SCHED_FIFO, SCHED_IDLE, SCHED_OTHER, and SCHED_RR. Learn their uses and options. ## Introduction The `chrt` command in Linux is a powerful tool designed for manipulating the real-time attributes of a process. This command allows users to set or retrieve the real-time scheduling attributes of an existing process identified by its PID (Process ID), or to execute a command with specified scheduling attributes. Understanding how to use `chrt` effectively can significantly enhance system performance and responsiveness, especially in environments where real-time processing is critical. Below, we delve into the syntax, options, and practical examples to help you master the `chrt` command. ### Syntax The basic syntax of the `chrt` command is as follows: - To set scheduling attributes for a command: [code example] - To set or get the scheduling attributes for an existing process: [code example] ### Policy Options `chrt` offers several policy options to define the scheduling policy: - `-b, --batch`: Sets the policy to `SCHED_BATCH`, optimized for batch processing. - `-d, --deadline`: Sets the policy to `SCHED_DEADLINE`, for tasks with strict timing requirements. - `-f, --fifo`: Sets the policy to `SCHED_FIFO`, implementing a first-in, first-out scheduling. - `-i, --idle`: Sets the policy to `SCHED_IDLE`, for very low priority jobs. - `-o, --other`: Sets the policy to `SCHED_OTHER`, the default Linux time-sharing scheduling. - `-r, --rr`: Sets the policy to `SCHED_RR`, a round-robin scheduling. ### Scheduling Options - `SCHED_BATCH`: Optimizes for batch... --- ## Ansible Linux User Management Guide URL: https://www.ansiblebyexample.com/articles/ansible-linux-users-and-groups-by-examples Description: Automate Linux user and group management with Ansible. Complete guide covering user creation, group management, SSH keys, password policies, PostgreSQL. ## Introduction Managing users and groups across dozens or hundreds of Linux servers manually is error-prone and time-consuming. Ansible's `user` and `group` modules automate the entire lifecycle — creating accounts, managing group memberships, setting passwords, distributing SSH keys, and enforcing policies consistently across your fleet. ## Core Modules | Module | Purpose | |--------|---------| | `ansible.builtin.user` | Manage user accounts | | `ansible.builtin.group` | Manage groups | | `ansible.posix.authorized_key` | Manage SSH authorized keys | | `ansible.builtin.lineinfile` | Edit sudoers and config files | ## Quick Examples ### Create a User [code example] ### Create a Group [code example] ### Set Password [code example] ### Add SSH Key [code example] ## Complete User Provisioning Playbook [code example] ## Tutorials ### User Management - Create User Account - Add User to Secondary Group - Change User Primary Group - Change User Password - User Password Expiration - Enable User Account - Disable User Account - Remove User Account ### Group Management - Create a Group - Delete a Group ### PostgreSQL Users - Allow md5 Connection for PostgreSQL User - Create PostgreSQL User or Role - Grant PostgreSQL Privileges ### Windows User Management - Create Local User on Windows - Create Local Group on Windows - Change Windows User Password - Remove Windows User - Remove Windows Group ### AWX User Management - Create AWX Superuser in Docker ### Troublesh... --- ## Ansible List — No Attribute Length URL: https://www.ansiblebyexample.com/articles/resolve-list-object-has-no-attribute-length-in-ansible Description: Fix the Ansible error "list object has no attribute length". Learn why Jinja2 uses filters instead of attributes, with examples for length, sort, join. ## Introduction The error `list object has no attribute length` is one of the most common Jinja2 mistakes in Ansible. It occurs when you try to access `length` as a Python attribute (`.length`) instead of using Jinja2's `length` filter (`| length`). This guide explains why, shows the fix, and covers all the essential Jinja2 list operations you should know. ## The Error [code example] Error output: [code example] ## The Fix Use the `| length` Jinja2 filter: [code example] ## Why This Happens Ansible uses **Jinja2** for templating, not raw Python. In Jinja2: - **Attributes** (dot notation) access object properties: `my_dict.key` - **Filters** (pipe notation) transform values: `my_list | length` Python lists have a `len()` function, not a `.length` attribute. Jinja2 provides the `length` filter as the equivalent: | Python | Jinja2 (Ansible) | |--------|-----------------| | `len(my_list)` | `{{ my_list \| length }}` | | `my_list.sort()` | `{{ my_list \| sort }}` | | `", ".join(my_list)` | `{{ my_list \| join(", ") }}` | ## Practical Examples ### Count Items in a List [code example] ### Conditional Based on List Length [code example] ### Check If List Is Empty [code example] ### Use Length in Loops [code example] ## Essential Jinja2 List Filters Beyond `length`, here are the most useful list filters in Ansible: ### Sorting [code example] ### Joining [code example] ### Filtering [code example] ### Extracting [code example] ### Set Operations [code ... --- ## Ansible listen_ports_facts Module — Gather Listening Port Facts URL: https://www.ansiblebyexample.com/articles/ansible-listen-ports-facts-module-gather-listening-port-facts Description: Discover which ports are open and listening on remote hosts with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible listen_ports_facts Module — Gather Listening Port Facts ## Introduction The `community.general.listen_ports_facts` module discover which ports are open and listening on remote hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.listen_ports_facts` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. *... --- ## Ansible Local Connection — Run Tasks on the Controller URL: https://www.ansiblebyexample.com/articles/ansible-local-connection-run-tasks-on-the-controller Description: Use connection: local to run Ansible tasks on the controller machine. Manage localhost, call APIs, run scripts locally, and provision cloud resources. # Ansible Local Connection — Run Tasks on the Controller ## Introduction By default, Ansible connects to remote hosts via SSH. `connection: local` runs tasks directly on the Ansible controller — no SSH, no remote host needed. Use it for API calls, cloud provisioning, local file manipulation, and any task that should execute on the machine running the playbook. ## Three Ways to Run Locally ### 1. Play-Level Connection [code example] ### 2. delegate_to localhost [code example] ### 3. Per-Task Connection Override [code example] ## Common Use Cases ### Cloud Provisioning [code example] ### API Orchestration [code example] ### Local File Processing [code example] ### Mixed Local and Remote [code example] ## localhost in Inventory [code example] ## connection: local vs delegate_to | Feature | `connection: local` | `delegate_to: localhost` | |---------|-------------------|------------------------| | Scope | Entire play | Single task | | `inventory_hostname` | `localhost` | Original remote host | | `hostvars` | localhost's vars | Remote host's vars | | Use case | Entire play runs locally | One task runs locally | [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "localhost not in inventory" | Use `hosts: localhost` — it's implicit | | Wrong Python interpreter | Set `ansible_python_interpreter: /usr/bin/python3` | | Facts from wrong host | `delegate_to` keeps original host facts; `connection: local` uses localhost facts | | SSH conn... --- ## Ansible locale_gen — Generate System Locales URL: https://www.ansiblebyexample.com/articles/ansible-locale-gen-generate-system-locales Description: Ansible locale_gen guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible locale_gen — Generate System Locales ## Introduction Generate System Locales. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible locale_gen requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective tas... --- ## Ansible Logrotate — Log Rotation URL: https://www.ansiblebyexample.com/articles/ansible-logrotate-manage-log-rotation Description: Manage logrotate configuration across Linux servers with Ansible. Template-based log rotation for applications, databases, web servers, and custom. ## Introduction logrotate prevents log files from consuming all disk space by rotating, compressing, and deleting old logs on a schedule. While every Linux system ships with logrotate, managing configurations across dozens of servers with different applications requires automation. Ansible templates logrotate configs consistently — ensuring every server has the right rotation policy for each application. ## How logrotate Works [code example] - **Global config**: `/etc/logrotate.conf` - **App configs**: `/etc/logrotate.d/*.conf` - **Runs via**: daily cron or systemd timer ## Basic logrotate with Ansible ### Deploy a logrotate Config [code example] ## Template-Based Configuration ### Variables [code example] ### Template [code example] ### Playbook [code example] ## Common Application Configs ### Nginx [code example] ### Docker Containers [code example] ### PostgreSQL [code example] ### systemd Journal (Size Limit) [code example] ## Global logrotate.conf [code example] [code example] ## Validate and Test [code example] ## Monitor Disk Usage [code example] ## logrotate Directives Reference | Directive | Description | |---|---| | `daily` / `weekly` / `monthly` | Rotation frequency | | `rotate N` | Keep N rotated files | | `compress` | gzip old logs | | `delaycompress` | Compress on next rotation (not current) | | `copytruncate` | Copy then truncate (for apps that can't reopen) | | `create mode owner group` | Create new file with permissions | | `mi... --- ## Ansible lookup — Files & External Data URL: https://www.ansiblebyexample.com/articles/ansible-lookup-plugins-files-env-data Description: Use Ansible lookup plugins to read files, environment variables, passwords, CSV data, and query external sources. Practical examples with file, env, pipe,. ## Introduction Lookup plugins read data from external sources on the **control node** (not the remote host). Read files, environment variables, command output, passwords, and more — then use that data in playbooks and templates. ## Syntax [code example] ## Common Lookup Plugins ### file — Read a File [code example] ### env — Environment Variables [code example] ### pipe — Command Output [code example] ### password — Generate or Read Passwords [code example] ### template — Render a Template [code example] ### fileglob — Find Files by Pattern [code example] ### csvfile — Read CSV Data [code example] [code example] ### ini — Read INI Files [code example] [code example] ### url — Fetch from URL [code example] ### subelements — Nested Loops [code example] ### dict — Iterate Dictionaries [code example] ## lookup vs query [code example] Use `query()` or `lookup(..., wantlist=True)` when looping. ## Practical Patterns ### Load Secrets from Environment [code example] ### Dynamic Inventory Data [code example] ### Generate and Store Credentials [code example] ## Troubleshooting ### "File not found" Lookups run on the **control node**, not the remote host. The path is relative to the playbook or role: [code example] ### lookup vs Fetching Remote Files [code example] ## Related Articles - Ansible Variables Guide - Ansible Vault for Secrets - Ansible Jinja2 Templates - Ansible Playbook Guide ## Conclusion Lookup plugins read external data on... --- ## Ansible Lookup Plugins — Complete Guide with Examples URL: https://www.ansiblebyexample.com/articles/ansible-lookup-plugins-complete-guide-with-examples Description: Ansible Lookup Plugins guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Lookup Plugins — Complete Guide with Examples ## Introduction Complete Guide with Examples. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Lookup Plugins requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible Lookup Plugins — Query External Data Sources URL: https://www.ansiblebyexample.com/articles/ansible-lookup-plugins-query-external-data-sources Description: Use Ansible lookup plugins to read files, environment variables, passwords, URLs, and external data. Complete guide to file, env, pipe, url, and custom. # Ansible Lookup Plugins — Query External Data Sources ## Introduction Lookup plugins fetch data from outside Ansible — files, environment variables, command output, URLs, password stores, and more. They run on the **controller** (not remote hosts) and return data that you can use in variables, templates, and task parameters. This guide covers the most useful built-in lookups with practical examples. ## Syntax [code example] ## file — Read File Contents [code example] ## env — Environment Variables [code example] ## pipe — Command Output [code example] ## url — Fetch from URLs [code example] ## password — Generate and Store Passwords [code example] ## template — Render Jinja2 Templates [code example] ## csvfile — Read CSV Data [code example] ## ini — Read INI Files [code example] ## sequence — Generate Number Sequences [code example] ## together and zip — Combine Lists [code example] ## lookup vs query [code example] ## Error Handling [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "file not found" | Lookup runs on controller; path is relative to playbook | | `env` returns empty | Variable not set on controller machine | | `pipe` fails silently | Check command works manually on controller | | `url` timeout | Add `timeout=30` parameter | | Wrong data type | Use `query()` for lists, `lookup()` for strings | ## Best Practices 1. **Use `query()` over `lookup()`** — returns lists, fails on errors 2. **Use `env` sparingl... --- ## Ansible Loop — Lists Dicts Files URL: https://www.ansiblebyexample.com/articles/ansible-loop-iterate-lists-dicts-files Description: Use Ansible loop to repeat tasks over lists, dictionaries, nested items, and file globs. Replace with_items, with_dict, and with_fileglob with modern loop. ## Introduction `loop` repeats a task for each item in a list. It replaces the older `with_items`, `with_dict`, and `with_fileglob` keywords with a single, consistent syntax. Each iteration, the current item is available as `{{ item }}`. ## Basic Loop [code example] ## Loop Over Dictionaries [code example] ## Loop Over a Variable [code example] ## Loop Index Access the loop index and other metadata with `loop_var` attributes: [code example] Available variables with `extended: true`: | Variable | Description | |----------|-------------| | `ansible_loop.index` | Current iteration (1-based) | | `ansible_loop.index0` | Current iteration (0-based) | | `ansible_loop.first` | True on first iteration | | `ansible_loop.last` | True on last iteration | | `ansible_loop.length` | Total number of items | | `ansible_loop.revindex` | Iterations remaining (1-based) | | `ansible_loop.previtem` | Previous item | | `ansible_loop.nextitem` | Next item | ## Loop with Condition [code example] ## Register with Loop [code example] ## Nested Loops [code example] ## Loop with Fileglob [code example] ## Loop Control [code example] ## until (Retry Loop) [code example] ## Migration from with_* Keywords | Old Syntax | Modern Syntax | |-----------|--------------| | `with_items: list` | `loop: list` | | `with_list: list` | `loop: list` | | `with_dict: dict` | `loop: "{{ dict \| dict2items }}"` | | `with_fileglob: pattern` | `loop: "{{ lookup('fileglob', pattern, wantlist=True) }}"`... --- ## Ansible Loop Variable Conflict — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-loop-variable-conflict-fix-and-solutions Description: Resolve loop variable conflicts with nested loops and loop_var. Tested on real machines with clear, copy-paste examples. # Ansible Loop Variable Conflict — Fix and Solutions ## Introduction Resolve loop variable conflicts with nested loops and loop_var. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve loop variable conflicts with nested loops and loop_var. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible loop vs with_items vs until URL: https://www.ansiblebyexample.com/articles/ansible-loop-vs-with-items-vs-until Description: Compare Ansible loop, with_items, and until. Learn modern loop syntax, migration from with_* to loop, retry patterns, and nested iteration examples. ## Introduction Ansible has two loop syntaxes: the modern `loop` keyword and the legacy `with_*` plugins. It also has `until` for retry loops. Knowing which to use — and how to migrate — keeps your playbooks modern and readable. ## Quick Comparison | Feature | `loop` (modern) | `with_items` (legacy) | `until` (retry) | |---------|-----------------|----------------------|-----------------| | Introduced | Ansible 2.5 | Ansible 1.x | Ansible 1.4 | | Status | ✅ Recommended | ⚠️ Still works, not deprecated | ✅ Active | | Purpose | Iterate over a list | Iterate over a list | Retry until condition met | | Flattening | ❌ No auto-flatten | ✅ Auto-flattens nested lists | N/A | | Filters | ✅ Full Jinja2 filter support | Limited | N/A | | `loop_control` | ✅ Full support | ✅ Works | N/A | ## loop — Modern Syntax [code example] ### loop_control [code example] ## with_items — Legacy Syntax [code example] ### Migration from with_* to loop [code example] ## until — Retry Loop [code example] ## Common Patterns ### Batch Processing [code example] ### Conditional Loop [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Loop Guide - Ansible map vs selectattr vs json_query - Ansible Jinja2 Templates - Ansible Strategies Guide ## Conclusion **loop** is the modern standard — use it for all new playbooks. **with_items** still works but offers no advantage over `loop`. **until** is for retry patterns (health checks, waiting for services). When migrati... --- ## Ansible loop_control — Avoid Collisions URL: https://www.ansiblebyexample.com/articles/avoid-variable-collisions-in-ansible-with-loop-control Description: Master Ansible loop_control — rename loop variables with loop_var, add labels for cleaner output, use index_var for counters, and enable extended loop. ## Introduction When Ansible runs a `loop`, it assigns each element to the variable `item`. This works fine for simple tasks — but breaks when you have nested loops, included tasks with their own loops, or roles that also use `item`. The `loop_control` directive solves this by letting you rename the loop variable and control loop output. ## The Problem: Variable Collisions ### Nested Include with Loop [code example] The inner loop's `item` overwrites the outer loop's `item`, causing unexpected behavior. ## The Fix: loop_control ### loop_var — Rename the Loop Variable [code example] Now `server_type` holds the outer loop value, and `item` works normally in the inner loop. ## loop_control Options | Option | Type | Description | |--------|------|-------------| | `loop_var` | string | Rename the loop variable (default: `item`) | | `label` | string | Custom label in task output (hides verbose data) | | `index_var` | string | Variable name for the loop index (0-based) | | `extended` | bool | Enable extended loop info (`ansible_loop.*`) | | `extended_allitems` | bool | Include all items in extended info (default: true) | | `pause` | float | Seconds to pause between iterations | ## Practical Examples ### label — Clean Output for Complex Data Without label, Ansible prints the entire object on each iteration: [code example] Output: `TASK [Create users] => (item={'name': 'alice', 'groups': ['sudo', 'docker'], 'shell': '/bin/bash', 'comment': 'Alice Smith - Engineering'})... --- ## Ansible Loops — loop, with_items, with_dict & Migration Guide (2026) URL: https://www.ansiblebyexample.com/articles/ansible-loops-with-items-loop-migration-guide Description: Master Ansible loops with practical examples. Migrate from with_items to loop, use filters, handle nested loops, and optimize loop performance. # Ansible Loops — Complete Guide (2026) ## Modern Loop Syntax [code example] ## Migration from with_items [code example] ## Loop with Dictionaries [code example] ## Loop Control [code example] ## Conditional Loops [code example] ## Loop with Register [code example] ## Flatten & Subelements [code example] ## Performance: until + retries [code example] ## Conclusion Use `loop` for all new playbooks. Migrate `with_*` gradually. Use `loop_control` for labels and nested loop variables. Pass lists directly to modules when possible — it's faster than looping. --- ## Ansible lvg and lvol — Manage LVM Logical Volumes URL: https://www.ansiblebyexample.com/articles/ansible-lvg-and-lvol-manage-lvm-logical-volumes Description: Ansible lvg and lvol guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible lvg and lvol — Manage LVM Logical Volumes ## Introduction Manage LVM Logical Volumes. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible lvg and lvol requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible lxd_container Module — Manage LXD Containers URL: https://www.ansiblebyexample.com/articles/ansible-lxd-container-module-manage-lxd-containers Description: Create, start, stop, and configure LXD system containers with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible lxd_container Module — Manage LXD Containers ## Introduction The `community.general.lxd_container` module create, start, stop, and configure LXD system containers with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.lxd_container` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — ... --- ## Ansible Magic Variables — Special Built-in Variables Reference URL: https://www.ansiblebyexample.com/articles/ansible-magic-variables-special-built-in-reference Description: Complete reference for Ansible magic variables: inventory_hostname, hostvars, groups, playbook_dir, role_path, and all special variables with examples. ## Introduction Ansible magic variables are special built-in variables automatically set by Ansible during execution. They provide information about the current host, play, inventory, and execution environment — no need to define them yourself. ## Host Variables ### inventory_hostname The name of the current host as defined in inventory (not the actual hostname): [code example] ### inventory_hostname_short Short version (everything before the first dot): [code example] ### ansible_host The actual IP or hostname to connect to: [code example] ### hostvars Access variables from ANY host in the inventory: [code example] ## Group Variables ### groups Dictionary of all groups and their hosts: [code example] ### group_names List of groups the current host belongs to: [code example] ## Play Variables ### ansible_play_hosts All hosts in the current play (after limits/filters): [code example] ### ansible_play_hosts_all All hosts targeted by the play (before any failures): [code example] ### play_hosts (deprecated) Use `ansible_play_hosts` instead. ### ansible_play_batch Current batch of hosts in serial execution: [code example] ## Path Variables ### playbook_dir Directory of the playbook being executed: [code example] ### inventory_dir / inventory_file Path to the inventory: [code example] ### role_path Current role's directory (only available inside a role): [code example] ### ansible_search_path List of paths Ansible searches for files/tem... --- ## Ansible Magic Variables Reference URL: https://www.ansiblebyexample.com/articles/ansible-magic-variables-complete-reference-guide Description: Complete reference for Ansible magic variables — inventory_hostname, hostvars, groups, group_names, playbook_dir, role_path, and ansible_facts. Practical. ## What Are Magic Variables? Ansible automatically defines **magic variables** (also called special variables) that you can use in any playbook. These provide information about hosts, groups, the play environment, and execution context. ## Host Variables ### inventory_hostname The name of the current host as defined in inventory: [code example] ### inventory_hostname_short The first part of `inventory_hostname` (before the first dot): [code example] ### ansible_host The actual IP/hostname Ansible connects to: [code example] ### ansible_facts Dictionary of all gathered facts about the current host: [code example] Common facts: - `ansible_facts['os_family']` — Debian, RedHat, etc. - `ansible_facts['distribution']` — Ubuntu, CentOS, etc. - `ansible_facts['memtotal_mb']` (also `ansible_memtotal_mb`) - `ansible_facts['processor_vcpus']` - `ansible_facts['default_ipv4']['address']` ## Group Variables ### groups Dictionary of all groups and their hosts: [code example] ### group_names List of groups the current host belongs to: [code example] ### hostvars Access variables from any host: [code example] ## Play and Execution Variables ### playbook_dir The directory where the playbook file lives: [code example] ### role_path The directory of the current role: [code example] ### ansible_play_hosts List of hosts active in the current play: [code example] ### ansible_play_batch Hosts in the current batch (when using `serial`): [code example] ### play_... --- ## Ansible Manage AWS Infrastructure End to End — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-aws-infrastructure-end-to-end-complete-guide Description: Complete AWS automation with VPC, EC2, RDS, S3, and IAM. Hands-on, tested examples and best practices for Ansible Manage AWS Infrastructure End to End. # Ansible Manage AWS Infrastructure End to End — Complete Guide ## Introduction Complete AWS automation with VPC, EC2, RDS, S3, and IAM. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Complete AWS automation with VPC, EC2, RDS, S3, and IAM. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage Container Registry — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-container-registry-complete-guide Description: Deploy Harbor or private Docker registries with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Manage Container Registry. # Ansible Manage Container Registry — Complete Guide ## Introduction Deploy Harbor or private Docker registries with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy Harbor or private Docker registries with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage Kubernetes Resources — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-kubernetes-resources-complete-guide Description: Deploy pods, services, and deployments with Ansible k8s module. Tested on real machines with clear, copy-paste examples. # Ansible Manage Kubernetes Resources — Complete Guide ## Introduction Deploy pods, services, and deployments with Ansible k8s module. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy pods, services, and deployments with Ansible k8s module. Use check mode for validation, handle errors gracefully, and always test in non-production first. ## Further reading To go deeper, managing Kubernetes with Ansible playbooks expands on these patterns in production. --- ## Ansible Manage Multiple Environments — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-multiple-environments-complete-guide Description: Organize inventories and variables for dev, staging, and production. Hands-on, tested examples and best practices for Ansible Manage Multiple Environments. # Ansible Manage Multiple Environments — Complete Guide ## Introduction Organize inventories and variables for dev, staging, and production. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Organize inventories and variables for dev, staging, and production. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage Network VLANs — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-network-vlans-complete-guide Description: Configure VLANs on Cisco, Arista, and Juniper with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Manage Network VLANs. # Ansible Manage Network VLANs — Complete Guide ## Introduction Configure VLANs on Cisco, Arista, and Juniper with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Configure VLANs on Cisco, Arista, and Juniper with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage Python Virtual Environments — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-python-virtual-environments-complete-guide Description: Create Python virtualenvs and install packages with Ansible. Hands-on, tested examples and best practices for Ansible Manage Python Virtual Environments. # Ansible Manage Python Virtual Environments — Complete Guide ## Introduction Create Python virtualenvs and install packages with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Create Python virtualenvs and install packages with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage SELinux Policies — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-selinux-policies-complete-guide Description: Configure SELinux modes, booleans, and file contexts with Ansible. Hands-on, tested examples and best practices for Ansible Manage SELinux Policies. # Ansible Manage SELinux Policies — Complete Guide ## Introduction Configure SELinux modes, booleans, and file contexts with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Configure SELinux modes, booleans, and file contexts with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage SSL Certificates — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-ssl-certificates-complete-guide Description: Deploy and renew SSL TLS certificates with Ansible automation. Follow clear, copy-paste examples and real-world usage notes for Ansible Manage SSL Certificates. # Ansible Manage SSL Certificates — Complete Guide ## Introduction Deploy and renew SSL TLS certificates with Ansible automation. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy and renew SSL TLS certificates with Ansible automation. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Manage Systemd Services — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-manage-systemd-services-complete-guide Description: Create systemd unit files and manage service states with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible Manage Systemd Services — Complete Guide ## Introduction Create systemd unit files and manage service states with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Create systemd unit files and manage service states with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible map Filter — Transform Lists and Extract Attributes URL: https://www.ansiblebyexample.com/articles/ansible-map-filter-transform-lists-and-extract-attributes Description: Use Ansible map filter to extract attributes from lists, apply filters to each element, and transform data structures in playbooks and templates. # Ansible map Filter — Transform Lists and Extract Attributes ## Introduction The `map` filter applies a transformation to every element in a list — extract an attribute, apply another filter, or call a test. It's how you go from a list of dictionaries to a list of specific values, or transform all strings in a list at once. ## Extract Attribute from List of Dicts [code example] ## Apply Filter to Each Element [code example] ## Common map Patterns ### Extract Nested Attributes [code example] ### Map with int/string Conversion [code example] ### Map + Join (Build Strings) [code example] ### Map + Select (Filter + Transform) [code example] ### Map + Flatten [code example] ## map vs selectattr vs reject | Filter | Purpose | Example | |--------|---------|---------| | `map` | Transform each element | Extract attribute, apply filter | | `selectattr` | Filter by attribute value | Keep items where `active == true` | | `rejectattr` | Exclude by attribute | Remove items where `disabled == true` | | `select` | Filter by test | Keep items matching a test | [code example] ## Real-World Examples ### Generate /etc/hosts Entries [code example] ### Install Packages from Structured Data [code example] ### Build Docker Compose Ports [code example] ### Extract from Registered Output [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | `map` returns generator, not list | Add `\| list` at the end | | `undefined attribute` error | Use `default` filter: ... --- ## Ansible map vs selectattr vs json_query — Data Filtering Compared URL: https://www.ansiblebyexample.com/articles/ansible-map-vs-selectattr-vs-json-query Description: Compare Ansible map, selectattr, and json_query filters. Learn when to use each for transforming and filtering complex data structures with practical. ## Introduction Ansible provides three powerful filters for working with complex data: `map` for transforming lists, `selectattr` for filtering objects by attribute, and `json_query` for JMESPath queries on nested structures. Choosing the right one depends on your data shape and what you need to extract. This guide compares all three with practical examples. ## Quick Decision Guide [code example] ## Sample Data [code example] ## map Filter Transforms every item in a list. Think "apply function to each element." [code example] ## selectattr Filter Filters a list of objects by attribute value. Think SQL WHERE clause. [code example] ## json_query Filter JMESPath expressions for complex nested data. Think XPath for JSON. [code example] ## Comparison Table [code example] ## Common Patterns [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Filter Plugins - Ansible Variables - Ansible Jinja2 Templates - Ansible loop Module - Ansible regex_replace vs replace ## Conclusion Use **map** to transform or extract from simple lists — it's built-in and fast. Use **selectattr** to filter lists of dictionaries by field values — combine with map for filter-then-extract patterns. Use **json_query** for deeply nested structures or complex multi-condition queries, especially when working with cloud API responses. For most playbook tasks, `selectattr` + `map` cover 90% of needs without external dependencies. --- ## Ansible maven_artifact Module — Download Maven Artifacts URL: https://www.ansiblebyexample.com/articles/ansible-maven-artifact-module-download-maven-artifacts Description: Download JAR files and artifacts from Maven repositories with Ansible. Hands-on, tested examples and best practices for Ansible maven_artifact Module. # Ansible maven_artifact Module — Download Maven Artifacts ## Introduction The `community.general.maven_artifact` module download JAR files and artifacts from Maven repositories with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.maven_artifact` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mod... --- ## Ansible max_fail_percentage — Control Failure Tolerance URL: https://www.ansiblebyexample.com/articles/ansible-max-fail-percentage-control-failure-tolerance Description: Use max_fail_percentage to set failure thresholds in Ansible rolling deployments. Stop bad deploys early and protect your fleet from cascading failures. # Ansible max_fail_percentage — Control Failure Tolerance ## Introduction `max_fail_percentage` sets the maximum percentage of hosts that can fail before Ansible aborts the entire play. Combined with `serial`, it creates a safety valve for rolling deployments: if too many hosts fail in a batch, the play stops before the bad deploy reaches your entire fleet. ## Basic Usage [code example] With 100 hosts, `serial: "25%"`, and `max_fail_percentage: 10`: - Each batch = 25 hosts - If >2 hosts (10% of 25) fail in a batch → entire play aborts - Remaining batches won't run ## How It Works [code example] The percentage is calculated **per batch**, not across the entire play. ## Common Settings | Setting | Effect | Use Case | |---------|--------|----------| | `max_fail_percentage: 0` | Any failure aborts | Critical infrastructure | | `max_fail_percentage: 10` | 10% tolerance | Standard deployments | | `max_fail_percentage: 25` | 25% tolerance | Flaky environments | | `max_fail_percentage: 49` | Nearly half can fail | Non-critical updates | | `max_fail_percentage: 100` | Never aborts (default) | Fire-and-forget | ## Zero Tolerance [code example] ## Canary with Failure Gates [code example] If the canary (first host) fails, the entire deploy stops. ## any_errors_fatal vs max_fail_percentage [code example] | Feature | `any_errors_fatal` | `max_fail_percentage: 0` | |---------|-------------------|-------------------------| | Scope | All hosts immediately | Per batch with se... --- ## Ansible MCP Inventory Management Example: Query Hosts with Natural Language URL: https://www.ansiblebyexample.com/articles/ansible-mcp-inventory-management-example-query-hosts-with-natural-language Description: See how AAP's MCP Server exposes inventory management as 7 declarative tools, letting LLM agents query hosts, groups, and variables in plain English. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform is currently a Tech Preview. It maps AAP's REST API to 107 declarative tools across six tool sets, and one of those sets — inventory management — is built specifically so an LLM agent can answer "what hosts do I have?" without you writing a single API call. Here's a runnable example plus the natural-language flow behind it. [code example] ## What the MCP inventory tools actually do The playbook above is the plain-Ansible equivalent of a single sentence typed into an MCP-connected client such as Cursor: "list the hosts in the production inventory." Behind that sentence, the MCP Server's inventory management tool set (7 tools total) handles: - Querying hosts by inventory or group - Listing groups and their host membership - Reading host and group variables (including inherited vars) - Filtering hosts by status, facts, or custom fields At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten demoed this live from Cursor IDE, connected to the MCP Server over plain HTTP with Bearer-token authentication. The equivalent of the query above returned a structured, chat-native answer — no dashboard click-through, no manual `curl` against `/api/v2/`. A representative transcript from that class of query looks like this: [code example] The point isn't that this saves typing — it's that the MCP Server enforces AAP's own permission model and validation on every call. The same demo showed the ... --- ## Ansible MCP Job Management Example: Launch and Monitor Jobs via AI Chat URL: https://www.ansiblebyexample.com/articles/ansible-mcp-job-management-example-launch-and-monitor-jobs-via-ai-chat Description: See how AAP's hosted MCP Server exposes 25 job management tools so an AI chat client can launch, monitor, and cancel Ansible jobs safely. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform, a Tech Preview shown at Red Hat Tech Day Netherlands 2026 in Bunnik, exposes AAP as 107 declarative tools across six sets. The Job management set alone carries 25 tools for launching, monitoring, and cancelling jobs — enough for an AI chat client to run real operations against AAP without a human touching the UI. ## Connecting a client to the Job management tools [code example] [code example] ## What happens when you chat with it This isn't a playbook you run with `ansible-playbook` — it's a natural-language session against the MCP server, which then calls AAP's REST API on your behalf using the Job management tool set. A transcript from the kind demoed live: [code example] The first turn uses a read-only tool (`list_jobs`) to return a structured table straight from AAP's job list — no screen-scraping, just a declarative call. The second turn tries to launch a job with a bad survey answer; because validation lives in AAP itself, not in the LLM, the MCP server rejects it the same way the AAP UI would. The AI cannot talk its way past a guardrail it doesn't control. The third turn chains two more tools — pulling stdout and job events — to do real root-cause analysis, spotting both a typo and a concurrency bug from raw job output. ## Notes - The Job management tool set (25 of the 107 total tools) covers launch, monitor, and cancel — it does not expose inventory editing or credential man... --- ## Ansible MCP Platform Configuration Example: Manage Credentials via AI Agent URL: https://www.ansiblebyexample.com/articles/ansible-mcp-platform-configuration-example-manage-credentials-via-ai-agent Description: See how the AAP MCP Server's 18 Platform configuration tools let an AI agent query settings, credentials, and integrations over natural language. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform exposes AAP as a set of declarative tools an LLM agent can call directly. Demoed live at Red Hat Tech Day Netherlands 2026 by Fred van Zwieten via Cursor IDE, the server ships six tool sets totaling 107 tools; the **Platform configuration** set (18 tools) covers settings, credentials, and integrations — the surface you'd normally reach through the AAP UI or `awx.awx` modules. ## Example: connecting to the MCP server [code example] ## What the tool set actually does The 18 Platform configuration tools wrap read/write operations that already exist in AAP's own RBAC and credential model — the MCP server does not add new privileges, it just makes them agent-callable. In practice that means tools like `platform_configuration_list_credentials`, `platform_configuration_get_credential_type`, `platform_configuration_update_setting`, and `platform_configuration_list_integrations`. A natural-language session against these tools looks like this: [code example] That last exchange isn't a scripted refusal — it mirrors the guardrail behavior Fred van Zwieten showed live: when he launched a "Paint" job template with an invalid survey value ("Purple"), the MCP server rejected it because it enforces AAP's own survey validation server-side. The AI agent can query and reason, but it cannot bypass controls AAP itself enforces — credential secret values are a good example of a boundary the tool set respects... --- ## Ansible MCP Security and Compliance Example: Audit Trail Queries via AI URL: https://www.ansiblebyexample.com/articles/ansible-mcp-security-and-compliance-example-audit-trail-queries-via-ai Description: Query AAP audit trails and policy checks in plain English using Red Hat's MCP Server, with a YAML example and real transcript from Tech Day NL 2026. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform is a Tech Preview that exposes AAP as declarative tools for any LLM or agentic client. Of its 107 tools spread across six tool sets, 12 belong to the **Security and compliance** set — audit trails and policy checks — which is what lets an AI assistant answer "who changed what, and was it allowed?" without you writing a single API call. ## Example: connecting Cursor to the MCP Security and Compliance tools [code example] [code example] ## What this does The client config is what a tool like Cursor loads to speak MCP to AAP over plain HTTP with Bearer-token auth — exactly the setup Fred van Zwieten used in the live demo at Red Hat Tech Day Netherlands 2026 in Bunnik. Once connected, the `security_and_compliance` toolset gives the LLM 12 declarative endpoints for audit trails and policy checks; the model never touches the AAP database directly, it calls tools the server exposes, so the request/response shape is fixed by AAP itself, not by the model's imagination. ## Natural-language example transcript This is the kind of exchange the Security and compliance tools were built for — an auditor or platform engineer asking in plain English instead of building a report: [code example] The same guardrail behavior Red Hat demoed elsewhere in the session applies here too: the agent can only ask questions the MCP tools allow, it cannot silently rewrite an audit record or waive a policy check — th... --- ## Ansible MCP Server — AI-Driven Automation with LLM Integration URL: https://www.ansiblebyexample.com/articles/ansible-mcp-server-ai-driven-automation-with-llm-integration Description: Red Hat's Ansible MCP Server exposes AAP capabilities to LLMs for agentic job management, root cause analysis, and natural language automation. # Ansible MCP Server — AI-Driven Automation with LLM Integration ## Introduction Red Hat's **Ansible MCP Server** (Model Context Protocol) connects large language models directly to Ansible Automation Platform. LLMs can launch jobs, analyze failures, validate surveys, and manage automation — all through natural language interactions. Demonstrated live at Red Hat Tech Day Netherlands 2026. ## What is MCP? The Model Context Protocol (MCP) is an open standard for connecting AI models to external tools and data sources. The Ansible MCP Server exposes AAP as a set of tools that any MCP-compatible AI client can use. ## Architecture [code example] ## MCP Tool Sets (6 Categories) | Tool Set | Capabilities | |----------|-------------| | **Job Management** | Launch, monitor, cancel jobs | | **Inventory** | Query hosts, groups, variables | | **Templates** | List, describe job templates | | **Credentials** | Validate credential access | | **Projects** | Sync, update SCM projects | | **Analytics** | Failed job analysis, trends | ## Live Demo: Cursor IDE Integration [code example] ## Setting Up Ansible MCP Server [code example] ### VS Code Configuration [code example] ## Automation Intelligent Assistant (AIA) The full AIA architecture includes: - **BYOK RAG** — Bring Your Own Knowledge for context-aware responses - **BYOM** — Bring Your Own Model (Red Hat AI, OpenAI, Azure, watsonx, Gemini) - **MCP Server** — Hosted, production-grade tool exposure - **Human-in-the-loop** — ... --- ## Ansible MCP System Monitoring Example: Check Service Health via AI Agent URL: https://www.ansiblebyexample.com/articles/ansible-mcp-system-monitoring-example-check-service-health-via-ai-agent Description: See how the AAP MCP Server's 13 system monitoring tools let an AI agent check service health and resource usage via natural language over HTTP. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform exposes AAP as a set of declarative tools that any LLM or agentic client can call. Among the 107 tools across six tool sets, the System monitoring set (13 tools) covers service health and resource usage — the kind of check you'd otherwise run by hand against `/api/v2/ping/` or the AAP dashboard. ## Example: querying service health with a playbook fallback Even with an AI agent doing the asking, the MCP server still just calls AAP's own API underneath. The equivalent direct automation — useful when you want the same health check without a chat client in the loop — looks like this: [code example] ## What it does The task hits AAP's ping endpoint with the same Bearer-token HTTP auth the hosted MCP Server uses (demoed live via Cursor IDE at Red Hat Tech Day Netherlands 2026 in Bunnik by Fred van Zwieten). It returns node status, instance group capacity, and version info, then flags any instance group reporting zero capacity — a quick signal that a controller node or execution node is down. An AI agent connected to the MCP Server does the same thing conversationally. A transcript from that kind of session: [code example] The agent chains two of the 13 system monitoring tools — one for aggregate instance group health, one for per-node status — without the operator needing to know the underlying API paths. This mirrors the demo's other live examples, like returning a structured table for "sh... --- ## Ansible MCP User Management Example: Query Permissions via AI Chat URL: https://www.ansiblebyexample.com/articles/ansible-mcp-user-management-example-query-permissions-via-ai-chat Description: Use Red Hat's AAP MCP Server User management tool set to query roles, teams, and permissions in plain English, plus a matching Ansible playbook example. Red Hat's hosted MCP (Model Context Protocol) Server for Ansible Automation Platform is a Tech Preview that exposes AAP as declarative tool sets to any LLM/agentic client. Fred van Zwieten demoed it live at Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026) from Cursor IDE over plain HTTP with Bearer-token auth. The User management tool set (32 tools) lets an AI chat client query permissions, roles, and teams without a human writing a single API call. ## Playbook: audit team role assignments Below is a companion playbook you'd still run through AAP itself for scheduled audits — the MCP chat path (shown after) is for ad hoc, natural-language lookups against the same data. [code example] ## What it does The playbook pulls every team, then walks each team's role assignments, flagging any team with Admin rights on Job Templates. It's the kind of check a security team runs weekly. The MCP User management tool set exposes the same underlying data — roles, teams, permissions — as 32 individually callable tools, so an agent can answer the same question interactively instead of waiting for a scheduled job. ## Natural-language example via MCP This is illustrative of the interaction pattern shown in the Cursor IDE demo, using the same request/response shape as the live "last 5 jobs" and job-launch examples: [code example] The agent chains multiple User management tools (listing role assignments, resolving team names, checking a specific team's permissions) behind one plain... --- ## Ansible Memory vs CPU Bottlenecks URL: https://www.ansiblebyexample.com/articles/why-memory-not-cpu-is-the-critical-bottleneck-in-ansible-automation Description: Ansible's control node bottleneck is memory, not CPU. Learn why inventory, fact gathering, and forks consume RAM, how to measure usage, and 8 strategies. ## Introduction When Ansible playbooks slow down or crash on large inventories, the culprit is almost always **memory**, not CPU. The control node holds inventory, facts, variables, and task state all in RAM simultaneously. Understanding this helps you right-size your control node and optimize playbooks for thousands of hosts. ## Memory vs CPU: Where the Work Happens | Component | Control Node (local) | Managed Nodes (remote) | |-----------|---------------------|----------------------| | Inventory loading | ✅ RAM-heavy | — | | Fact gathering | ✅ Stored in RAM | ✅ Collected via SSH | | Variable resolution | ✅ In-memory | — | | Task coordination | ✅ Per-fork overhead | — | | Module execution | Minimal | ✅ Runs here via SSH | | Template rendering | ✅ Jinja2 in RAM | — | **Key insight:** Ansible is agentless — modules execute on remote nodes via SSH. The control node only coordinates, but coordination requires holding everything in memory. ## Why Memory Is the Bottleneck ### 1. Inventory in Memory Ansible loads the **entire inventory** at startup: [code example] ### 2. Fact Gathering Multiplier Each host's facts consume ~100-300KB: [code example] ### 3. Forks (Parallel Execution) Each fork is a separate Python process: | Forks | Base Memory per Fork | 100 Hosts | 1,000 Hosts | |-------|---------------------|-----------|-------------| | 5 (default) | ~50MB | ~250MB | ~500MB | | 20 | ~50MB | ~1GB | ~2GB | | 50 | ~50MB | ~2.5GB | ~5GB+ | ### 4. Variables and Templates... --- ## Ansible meta Module — Control Play Execution Flow URL: https://www.ansiblebyexample.com/articles/ansible-meta-module-control-play-execution-flow Description: Use ansible.builtin.meta to flush handlers, clear facts, end play, refresh inventory, and control Ansible execution flow during playbook runs. # Ansible meta Module — Control Play Execution Flow ## Introduction `ansible.builtin.meta` provides special actions that control Ansible's execution engine — flushing handlers mid-play, ending execution early, clearing cached facts, refreshing inventory, and resetting connections. These aren't normal tasks; they're directives to the Ansible runtime itself. ## Available Actions | Action | Description | |--------|-------------| | `flush_handlers` | Run all pending handlers immediately | | `end_play` | End the current play (skip remaining tasks) | | `end_host` | Remove current host from play (continue others) | | `end_batch` | End current serial batch | | `clear_facts` | Clear cached facts for current host | | `clear_host_errors` | Clear failure state for a host | | `refresh_inventory` | Re-read inventory (dynamic inventory) | | `noop` | Do nothing (placeholder) | | `reset_connection` | Close and reopen SSH connection | ## flush_handlers Handlers normally run at the end of a play. `flush_handlers` runs them immediately: [code example] ### Why flush_handlers? Without it, this fails: [code example] ## end_play Stop the entire play (all hosts): [code example] ## end_host Remove the current host from the play (other hosts continue): [code example] ## clear_facts Clear cached facts for the host and re-gather: [code example] ## reset_connection Close and reopen the SSH connection: [code example] ## refresh_inventory Re-read dynamic inventory mid-play: [code exa... --- ## Ansible microsoft.mecm Module Example: Patch Orchestration Playbook URL: https://www.ansiblebyexample.com/articles/ansible-microsoft-mecm-module-example-patch-orchestration-playbook Description: Runnable Ansible playbook example for the microsoft.mecm collection covering patch orchestration, client actions, and health checks on MECM. The `microsoft.mecm` collection brings Microsoft Endpoint Configuration Manager (MECM, formerly SCCM) under Ansible control: patch orchestration, client actions, and health checks. It was announced alongside eleven other new content collections for AAP 2.7 at Red Hat Tech Day Netherlands 2026 in Bunnik. Below is a runnable example that deploys a software update group to a device collection and confirms client health before and after. ## Example playbook [code example] ## What it does and why The play runs against a host in the `mecm_site_server` group — typically a Windows host with the MECM console/SMS provider reachable, since `microsoft.mecm` modules talk to the site server rather than to individual endpoints. It first checks client health on the target collection so you don't push updates into a collection that's already in a bad state. The `deployment` task creates the actual deployment of a software update group against a named device collection with a deadline, mirroring how MECM assigns updates natively. Forcing a machine policy retrieval via `client_action` speeds up client pickup instead of waiting for the default polling interval. The `until`/`retries` loop on `deployment_status` gives you a simple orchestration gate — the play won't move on (or a downstream play/role won't run) until compliance crosses a threshold, which is the core of patch orchestration versus a fire-and-forget update push. This pattern is exactly what the companion `infra.mecm_ops` validat... --- ## Ansible microsoft.scom Module Example: Alert Routing to EDA URL: https://www.ansiblebyexample.com/articles/ansible-microsoft-scom-module-example-alert-routing-to-eda Description: Runnable Ansible playbook example for the microsoft.scom collection, routing System Center Operations Manager alerts into Event-Driven Ansible. At Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026), Red Hat announced `microsoft.scom` as one of 12 new content collections landing for AAP 2.7. It covers System Center Operations Manager infrastructure automation plus alert routing into Event-Driven Ansible (EDA), so a SCOM alert can trigger a remediation rulebook instead of just paging a human. ## Example playbook [code example] ## What it does The playbook targets SCOM management servers and builds the full alert path in four steps: create a subscription that filters for critical, unresolved alerts; configure a webhook notification channel pointed at an EDA controller endpoint; check management group health so you don't wire up routing against a degraded SCOM deployment; and finally enable the routing rule that ties the subscription to the channel. On the EDA side, a corresponding rulebook listens on that webhook source and matches on alert fields (severity, monitoring object, alert name) to fire remediation actions — restart a service, run a validated role from `infra.windows_ops`, or open an incident in `splunk.itsi` for closed-loop tracking. The pattern mirrors what Red Hat showed for `hashicorp.vault` and `splunk.itsi` EDA integrations in the same announcement: SCOM stays the source of truth for monitoring, EDA becomes the decision engine. ## Notes - `microsoft.scom` was announced at Red Hat Tech Day Netherlands 2026 alongside `microsoft.mecm` as the two new Microsoft-focused collections for AAP 2.7; tre... --- ## Ansible Mikrotik RouterOS Backups URL: https://www.ansiblebyexample.com/articles/backup-config-on-mikrotik-routeros-ansible-network-community-routeros Description: Learn how to automate configuration backups for Mikrotik RouterOS with Ansible. This guide includes a step-by-step Playbook example for seamless backups. ## How to Backup Config on Mikrotik RouterOS with Ansible? Maintaining a backup copy of your network appliance configuration is a good practice for all IT Professionals. You could automate this process for Mikrotik RouterOS appliances using Ansible. ## Ansible Backup Config on Mikrotik RouterOS > `community.routeros`: Modules for MikroTik RouterOS Let's talk about the Ansible collection `community.routeros`. The full name is `community.routeros`, which means that is an Ansible Network Collection designed to interact with Mikrotik RouterOS devices. It contains modules for MikroTik RouterOS. ## Links - Community.Routeros ## Playbook How to Backup Config on Mikrotik RouterOS with Ansible Playbook. I'm going to show how to back up the current configuration of a Mikrotik RouterOS connecting via SSH protocol using the username and password credentials and save it to a file with the device name and timestamp. ### code - inventory [code example] - backup_mikrotik.yml [code example] - requirements.yml [code example] ### requirements setup [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Backup Config on Mikrotik RouterOS with Ansible. --- ## Ansible MinIO — Deploy S3-Compatible Object Storage URL: https://www.ansiblebyexample.com/articles/ansible-minio-s3-object-storage Description: Deploy MinIO S3-compatible object storage with Ansible. Single-node and distributed cluster setup, TLS, bucket policies, lifecycle rules, replication. ## Introduction MinIO is a high-performance S3-compatible object storage system — ideal for backups, artifacts, data lakes, and any workload needing an S3 API. Ansible automates the full deployment: single-node or distributed cluster, TLS encryption, bucket policies, lifecycle rules, site replication, and Prometheus monitoring. ## Single-Node Deployment [code example] ### Environment Template [code example] ## Distributed Cluster [code example] [code example] ## Install MinIO Client (mc) [code example] ## Manage Buckets [code example] ## TLS Configuration [code example] ## Nginx Reverse Proxy [code example] [code example] ## Health Check [code example] ## Troubleshooting ### Disk Space [code example] ### Connection Issues [code example] ## Related Articles - Ansible Ceph Storage - Ansible Docker Compose - Ansible Nginx - Ansible OpenSSL Certificates ## Conclusion MinIO gives you an S3-compatible API anywhere — on-premises, edge, or cloud. Ansible deploys single-node instances for dev and distributed clusters for production, manages TLS, creates buckets with versioning and lifecycle policies, and monitors health. Object storage as code means reproducible, version-controlled storage infrastructure. --- ## Ansible Mitogen — 10x Faster Playbook Execution URL: https://www.ansiblebyexample.com/articles/ansible-mitogen-speed-up-playbooks Description: Speed up Ansible playbooks with Mitogen — a connection plugin that replaces SSH+SFTP with a single Python-to-Python channel. Installation, benchmarks,. ## Introduction Mitogen is a Python library that replaces Ansible's default SSH + SFTP module execution with a single persistent Python-to-Python channel. Instead of opening multiple SSH connections per task (upload module, execute, download result), Mitogen sends pure Python bytecode over one connection. The result: **2x to 10x faster playbook execution** with zero changes to your playbooks. The trade-off: compatibility limitations with some Ansible features. ## How Default Ansible Works For each task on each host, Ansible's default strategy: [code example] That's **5-7 SSH round trips per task per host**. With 50 tasks on 100 hosts, that's up to 35,000 SSH operations. ## How Mitogen Works [code example] **One connection per host for the entire playbook run.** Modules execute as pure Python functions — no temp files, no SFTP, no repeated SSH handshakes. [code example] ## Install [code example] ## Configure ### ansible.cfg [code example] Or with environment variable: [code example] ### Dynamic Configuration [code example] ### Per-Environment Configuration [code example] ## Benchmarks Typical results on a 50-host fleet running a 30-task playbook: | Metric | Default SSH | Mitogen | Improvement | |---|---|---|---| | **Wall time** | 12 min | 2 min | **6x faster** | | **SSH connections** | ~1,500 | 50 | **97% fewer** | | **Network bytes** | ~200 MB | ~15 MB | **93% less** | | **CPU (controller)** | Low | Moderate | Expected | | **Temp files created** | ~1,50... --- ## Ansible Mitogen — Accelerate 3-7x URL: https://www.ansiblebyexample.com/articles/ansible-mitogen-plugin-accelerate-playbooks Description: Speed up Ansible playbooks 3-7x with the Mitogen connection plugin. Installation, configuration, benchmarks, compatibility notes, and when to use Mitogen. # Ansible Mitogen — Accelerate Playbooks 3-7x Faster ## Introduction Mitogen is a Python library that replaces Ansible's default SSH-based task execution with a more efficient mechanism. Instead of transferring module files over SSH for every task, Mitogen bootstraps a persistent Python interpreter on the remote host and streams module code directly — eliminating the overhead of repeated SSH sessions, temp file creation, and shell invocations. The result: **3-7x faster playbook execution** with zero changes to your playbooks. ## How Mitogen Works [code example] ## Installation [code example] ## Configuration [code example] [code example] ### Minimal ansible.cfg [code example] ## Available Strategies | Strategy | Description | |----------|-------------| | `mitogen_linear` | Drop-in replacement for `linear` (default) | | `mitogen_free` | Drop-in replacement for `free` | | `mitogen_host_pinned` | Drop-in replacement for `host_pinned` | ## Benchmarks Tested with 50 hosts, 20 tasks each: | Configuration | Time | Speedup | |--------------|------|---------| | Default SSH (forks=5) | 12m 30s | 1x | | SSH + pipelining (forks=50) | 4m 10s | 3x | | Mitogen linear (forks=50) | 1m 45s | 7.1x | | Mitogen free (forks=50) | 1m 20s | 9.4x | ### Where Mitogen Helps Most - **Many small tasks**: Module file transfer overhead dominates - **Large inventories**: Connection reuse saves massive time - **Repeated runs**: Fact gathering + small changes ### Where Mitogen Helps Less ... --- ## Ansible modprobe — Load Kernel Modules URL: https://www.ansiblebyexample.com/articles/load-and-unload-kernel-modules-in-linux-ansible-module-modprobe Description: How to automate the Linux Kernel module loading of the "dummy" module with parameters on an example machine with Ansible. ## How to Load and Unload Kernel Modules in Linux with Ansible? ## Ansible Load and Unload Kernel Modules in Linux - community.general.modprobe - Load or unload kernel modules Today we're talking about the Ansible module modprobe. The full name is `community.general.modprobe`, which means that is part of the collection of modules "community.general" maintained by the Ansible Community. The purpose of the module is to Load or unload kernel modules. ## Parameters - name string - Name of kernel module - params string - Modules parameters - state string - present/absent - Load / Unload The parameters of the module modprobe. The only required parameter is "name", with the full Linux kernel module name. The parameter "params" allows you to specify some module parameters. Default is an empty string. The parameter "state" specifies the status of the Linux Kernel module. The option "present" means that the module must be loaded. The option "absent" means that the module must be unloaded. ## Links - https://docs.ansible.com/ansible/latest/collections/community/general/modprobe_module.html ## Playbook Load and Unload Kernel Modules in Linux with Ansible Playbook. ### code [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Load and Unload Kernel Modules in Linux with Ansible. --- ## Ansible modprobe Module — Load Kernel Modules URL: https://www.ansiblebyexample.com/articles/ansible-modprobe-module-load-kernel-modules Description: Ansible modprobe Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible modprobe Module — Load Kernel Modules ## Introduction Load Kernel Modules. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible modprobe Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective t... --- ## Ansible Module Not Found Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-module-not-found-error-fix-and-solutions Description: Resolve module not found errors from missing collections, paths, and Python deps. With clear, copy-paste, step-by-step examples. # Ansible Module Not Found Error — Fix and Solutions ## Introduction Resolve module not found errors from missing collections, paths, and Python deps. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve module not found errors from missing collections, paths, and Python deps. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible module_defaults — Set Default Parameters for Modules URL: https://www.ansiblebyexample.com/articles/ansible-module-defaults-set-default-parameters-for-modules Description: Use module_defaults to set default parameters for Ansible modules at play or block level. Reduce repetition for URI headers, connection settings. # Ansible module_defaults — Set Default Parameters for Modules ## Introduction When multiple tasks use the same module with identical parameters — API headers, connection strings, become settings — `module_defaults` sets those values once at the play or block level. Tasks inherit the defaults automatically, reducing repetition and making playbooks easier to maintain. ## Basic Usage [code example] Without `module_defaults`, you'd repeat the headers block in every task. ## Block-Level Defaults [code example] ## Multiple Modules [code example] ## Group Defaults (Action Groups) [code example] ## Override Defaults Per Task [code example] ## Package Management [code example] ## File Operations [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Defaults not applied | Check FQCN matches exactly (`ansible.builtin.uri` not `uri`) | | Override not working | Task params always win over defaults | | Group defaults not found | Use `group/collection.name` format | | Defaults leak between blocks | Block-level defaults scope to that block only | | Wrong module gets defaults | Each module key is independent; check module name spelling | ## Best Practices 1. **Use FQCNs** — `ansible.builtin.uri` not `uri` 2. **API credentials at play level** — avoid repeating auth headers 3. **Cloud region/profile at play level** — consistent across all resources 4. **Block-level for different APIs** — separate auth for internal vs external 5. **Don't over-default... --- ## Ansible Modules Cheat Sheet — 50 Most Used Modules with Examples (2026) URL: https://www.ansiblebyexample.com/articles/ansible-modules-cheat-sheet-50-most-used Description: Quick reference for the 50 most used Ansible modules with copy-paste examples covering file management, packages, services, users, templates, and cloud. # Ansible Modules Cheat Sheet — 50 Most Used Modules ## File Management ### ansible.builtin.copy [code example] ### ansible.builtin.template [code example] ### ansible.builtin.file [code example] ### ansible.builtin.lineinfile [code example] ### ansible.builtin.blockinfile [code example] ### ansible.builtin.fetch [code example] ### ansible.builtin.stat [code example] ### ansible.builtin.find [code example] ### ansible.builtin.unarchive [code example] ### ansible.builtin.synchronize [code example] ## Package Management ### ansible.builtin.apt (Debian/Ubuntu) [code example] ### ansible.builtin.yum (RHEL/CentOS) [code example] ### ansible.builtin.dnf (Fedora/RHEL 8+) [code example] ### ansible.builtin.pip [code example] ### ansible.builtin.package (OS-agnostic) [code example] ## Service Management ### ansible.builtin.service [code example] ### ansible.builtin.systemd [code example] ## User & Group Management ### ansible.builtin.user [code example] ### ansible.builtin.group [code example] ### ansible.posix.authorized_key [code example] ## Command Execution ### ansible.builtin.command [code example] ### ansible.builtin.shell [code example] ### ansible.builtin.raw [code example] ### ansible.builtin.script [code example] ### ansible.builtin.expect [code example] ## System ### ansible.builtin.cron [code example] ### ansible.builtin.hostname [code example] ### ansible.builtin.reboot [code example] ### ansible.builtin.sysctl [code example] ### ansibl... --- ## Ansible Molecule — Docker Testing URL: https://www.ansiblebyexample.com/articles/using-docker-containers-with-molecule-for-ansible-testing Description: Explore how to configure Molecule with Docker for testing Ansible roles, ensuring reliable and efficient infrastructure as code with reproducible. ## Introduction In the realm of DevOps and infrastructure as code (IaC), testing automation is a critical component to ensure the reliability and efficiency of configurations. Ansible, a powerful open-source automation tool, allows users to define and manage infrastructure as code through playbooks. Molecule, an extension of Ansible, facilitates the testing of Ansible roles in an isolated environment, providing a consistent and reproducible testing workflow. One common scenario involves using Docker containers as test hosts within Molecule. Docker containers offer lightweight, portable environments that can be easily spun up and torn down, making them ideal for testing purposes. In this article, we will explore a Molecule setup utilizing Docker containers for the create, converge, and destroy steps. ## Molecule Configuration The Molecule configuration is defined in the `molecule.yml` file. This configuration specifies the test platforms and dependencies. In this example, the dependency is set to the Galaxy role, and the platforms include a Docker container based on the Ubuntu 22.04 image. [code example] The `requirements.yml` file lists the necessary Ansible collections, in this case, the community.docker collection. [code example] ## Create Playbook The `create.yml` playbook is responsible for creating Docker containers based on the defined platforms. It uses the community.docker.docker_container Ansible module to start containers with a specified image and other para... --- ## Ansible Molecule — Test Roles and Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-molecule-test-roles-playbooks Description: Use Ansible Molecule to test roles with Docker and Podman. Write tests, verify idempotency, lint playbooks, and integrate with CI/CD pipelines. ## Introduction Molecule is the standard testing framework for Ansible roles. It creates ephemeral instances (Docker, Podman, Vagrant, cloud), runs your role, verifies the result, and tears everything down. Essential for CI/CD and ensuring roles work before production deployment. ## Install Molecule [code example] ## Initialize a Role with Molecule [code example] Directory structure: [code example] ## molecule.yml Configuration [code example] ## converge.yml — The Test Playbook [code example] ## verify.yml — Verification Tests [code example] ## Run Tests [code example] ## Test Sequence The default `molecule test` runs: 1. **dependency** — Install Galaxy requirements 2. **lint** — Lint playbooks (yamllint, ansible-lint) 3. **cleanup** — Pre-test cleanup 4. **destroy** — Remove old instances 5. **syntax** — Check syntax 6. **create** — Create test instances 7. **prepare** — Run prepare.yml (pre-test setup) 8. **converge** — Run converge.yml (your role) 9. **idempotence** — Run converge again (zero changes expected) 10. **verify** — Run verify.yml (assertions) 11. **cleanup** — Post-test cleanup 12. **destroy** — Remove instances ## prepare.yml — Pre-Test Setup [code example] ## Multiple Scenarios [code example] [code example] ## CI/CD Integration ### GitHub Actions [code example] ### GitLab CI [code example] ## Testing with Ansible Verify [code example] ## Troubleshooting ### Docker Permission Denied [code example] ### systemd Not Available in C... --- ## Ansible Molecule Scenarios — Testing URL: https://www.ansiblebyexample.com/articles/ansible-role-and-collection-testing-with-molecule Description: Explore Molecule scenarios for testing Ansible roles and playbooks. Learn how to configure and use scenarios for effective development and testing in. ## Introduction Molecule, the testing framework for Ansible roles and playbooks, introduces powerful functionality through its concept of scenarios. Think of a scenario as a test suite for roles or playbooks within an Ansible collection. This article delves into Molecule scenarios, their layout, and how to harness their capabilities for efficient testing and development. ## Ansible Collection Adding Molecule to your Ansible collection is a straightforward process that enhances your development and testing workflow. Start by creating a new directory within your collection named "`extensions`." Navigate to this newly created directory using the command line and then initialize a new default Molecule scenario with the following: [code example] This step sets the foundation for incorporating Molecule into your collection, allowing you to seamlessly integrate testing and development practices. The newly created scenario within the "extensions" directory becomes a pivotal component in orchestrating Molecule's testing lifecycle for your Ansible roles and playbooks. ## Understanding the Scenario Layout The scenario layout is crucial for organizing Molecule's testing components. Within the `molecule/default` folder, several key files play distinct roles: - `create.yml`: This playbook file creates instances and stores data in the instance-config. - `destroy.yml`: Contains Ansible code for destroying instances and removing them from the instance-config. - `molecule.yml`: The cen... --- ## Ansible Molecule Testing — Write and Run Role Tests URL: https://www.ansiblebyexample.com/articles/ansible-molecule-testing-write-and-run-role-tests Description: Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. Lint, converge, verify, and integrate with CI/CD pipelines. # Ansible Molecule Testing — Write and Run Role Tests ## Introduction Molecule is the standard testing framework for Ansible roles. It creates temporary instances (Docker containers, VMs, or cloud instances), runs your role against them, verifies the result, and tears everything down. This guide covers setup, writing tests, multiple scenarios, and CI/CD integration. ## Installation [code example] ## Initialize a Role with Molecule [code example] Directory structure: [code example] ## molecule.yml Configuration [code example] ## converge.yml — The Playbook [code example] ## verify.yml — Assertions [code example] ## prepare.yml — Pre-Test Setup [code example] ## Running Molecule [code example] ## Multiple Scenarios [code example] [code example] ## CI/CD Integration [code example] ## Testinfra Verifier (Alternative) [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Docker permission denied | Add user to `docker` group or use `sudo` | | Container won't start | Use `privileged: true` and proper `command` | | Python not found | Add prepare step to install python3 | | Idempotence fails | Check for tasks that always report `changed` | | Slow tests | Use `pre_build_image: true` to skip building | ## Best Practices 1. **Test idempotence** — run converge twice, second should have 0 changes 2. **Test multiple OS** — Ubuntu + Rocky/RHEL at minimum 3. **Keep tests fast** — use pre-built images, minimize prepare steps 4. **Test in CI**... --- ## Ansible Monitor Disk Space — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-monitor-disk-space-complete-guide Description: Check disk usage and alert when low using Ansible facts and assertions. Hands-on, tested examples and best practices for Ansible Monitor Disk Space. # Ansible Monitor Disk Space — Complete Guide ## Introduction Check disk usage and alert when low using Ansible facts and assertions. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Check disk usage and alert when low using Ansible facts and assertions. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Monitoring Stack — Prometheus Grafana Alertmanager URL: https://www.ansiblebyexample.com/articles/ansible-monitoring-stack-prometheus-grafana-alertmanager Description: Ansible Monitoring Stack guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Monitoring Stack — Prometheus Grafana Alertmanager ## Introduction Prometheus Grafana Alertmanager. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Monitoring Stack requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **... --- ## Ansible Mount CIFS/SMB: Mount Windows Shares on Linux URL: https://www.ansiblebyexample.com/articles/mount-a-windows-share-in-linux-smb-or-cifs-ansible-module-mount Description: How to Mount a Windows share in Linux SMB/CIFS. The Ansible Playbook code is going to check the required packages, create the mount-point and setup the. How to mount a Windows share in Linux SMB/CIFS with Ansible? ## Ansible mount an SMB/CIFS filesystem - ansible.posix.mount - Control active and configured mount points Today we're talking about the Ansible module mount. The full name is `ansible.posix.mount`, which means that is part of the collection of modules "ansible.posix" to interact with POSIX platforms. The purpose of the module is to Control active and configured mount points. For Windows, use the `community.windows.win_mapped_drive` module instead. ## Parameters - path string - mount point (e.g. /mnt) - state string - mounted / unmounted / present / absent / remounted - src string - device or network volume - fstype string - ext4, xfs, iso9660, nfs, cifs, etc. - opts string - mount options This module has many parameters to perform any task. The only required are "path" and "state". The parameter "path" specifies the path to the mount point (e.g. /mnt/). The parameter "state" allows us to verify a specific state of the mount point. The options "mounted", "unmounted" and "remounted" change the device status. The "present" and "absent" options only change the `/etc/fstab` file. The `src` parameter specifies the device or network volume for NFS or SMB/CIFS. The `fstype` parameter specifies the filesystem type. For example: ext4, xfs, iso9660, nfs, cifs, etc. The `opts` parameter allows us to specify some mount options, that vary for each filesystem type. ## Playbook Let's jump in a real-life Ansible Playbook t... --- ## Ansible mount Module — Manage Filesystems and fstab URL: https://www.ansiblebyexample.com/articles/ansible-mount-module-manage-filesystems-and-fstab Description: Use ansible.posix.mount to mount, unmount, and manage filesystem entries in /etc/fstab. NFS, CIFS, ext4, XFS, tmpfs, and bind mounts with Ansible. # Ansible mount Module — Manage Filesystems and fstab ## Introduction The `ansible.posix.mount` module manages filesystem mount points and `/etc/fstab` entries. It can mount, unmount, remount, and configure persistent mounts for NFS shares, CIFS/SMB mounts, local disks, and special filesystems like tmpfs. ## Install the Collection [code example] ## Basic Mount [code example] ## Parameters Reference | Parameter | Required | Description | |-----------|----------|-------------| | `path` | yes | Mount point path | | `src` | yes* | Device or remote share | | `fstype` | yes* | Filesystem type (nfs, ext4, xfs, cifs, tmpfs) | | `opts` | no | Mount options (default: `defaults`) | | `state` | yes | `mounted`, `unmounted`, `present`, `absent`, `remounted` | | `backup` | no | Backup fstab before modifying | | `dump` | no | Dump flag for fstab (default: 0) | | `passno` | no | Pass number for fsck (default: 0) | | `fstab` | no | Path to fstab file (default: `/etc/fstab`) | ## State Options Explained | State | Mounts now? | Adds to fstab? | |-------|-------------|----------------| | `mounted` | ✅ Yes | ✅ Yes | | `unmounted` | ❌ Unmounts | fstab unchanged | | `present` | ❌ No | ✅ Yes | | `absent` | ❌ Unmounts | ❌ Removes entry | | `remounted` | ✅ Remounts | fstab unchanged | ## NFS Mounts [code example] ## CIFS/SMB Mounts [code example] ## Local Disk Mounts [code example] ## tmpfs and Special Filesystems [code example] ## Multiple Mounts with Loop [code example] ## Unmou... --- ## Ansible mount Module — NFS CIFS fstab URL: https://www.ansiblebyexample.com/articles/mount-an-nfs-share-in-linux-ansible-module-mount Description: Mount NFS, CIFS, and SMB shares on Linux with ansible.posix.mount. Playbook examples with fstab persistence, mount options, and unmount automation. ## How to mount an NFS share in Linux with Ansible? ## Ansible mounts an NFS Share in Linux - ansible.posix.mount - Control active and configured mount points Today we're talking about the Ansible module mount. The full name is `ansible.posix.mount`, which means that is part of the collection of modules "ansible.posix" to interact with POSIX platforms. The purpose of the module is to control active and configured mount points. For Windows, use the `community.windows.win_mapped_drive` module instead. ## Parameters - path string - mount point (e.g. /mnt) - state string - mounted / unmounted / present / absent / remounted - src string - device or network volume - fstype string - ext4, xfs, iso9660, nfs, cifs, etc. - opts string- mount options This module has many parameters to perform any task. The only required are "path" and "state". The parameter "path" specifies the path to the mount point (e.g. /mnt/). The parameter "state" allows us to verify a specific state of the mount point. The options "mounted", "unmounted" and "remounted" change the device status. The "present" and "absent" options only change the `/etc/fstab` file. The `src` parameter specifies the device or network volume for NFS or SMB/CIFS. The `fstype` parameter specifies the filesystem type. For example ext4, XFS, iso9660, NFS, CIFS, etc. The `opts` parameter allows us to specify some mount options, that vary for each filesystem type. ## Playbook Let's jump in a real-life Ansible Playbook to mount an ... --- ## Ansible multiline String: YAML Block Scalars Explained URL: https://www.ansiblebyexample.com/articles/ansible-multiline-string-yaml-block-scalars-explained Description: Learn how to write multiline strings in Ansible playbooks using YAML literal (|) and folded (>) block scalars. Practical examples for shell commands,. ## YAML Multiline String Syntax YAML provides two block scalar styles for multiline strings: | Style | Symbol | Newlines | Best for | |-------|--------|----------|----------| | **Literal** | `|` | Preserved | Scripts, config files | | **Folded** | `>` | Replaced with spaces | Long descriptions | ## Literal Block (`|`) — Preserves Newlines Each line break is kept exactly as written: [code example] ### Create a Config File [code example] ### Create a Shell Script [code example] ## Folded Block (`>`) — Joins Lines Line breaks become spaces (one long line). Blank lines create actual newlines: [code example] ### Long Description [code example] ## Chomp Modifiers Control the trailing newline: | Modifier | Meaning | Example | |----------|---------|---------| | `|` or `>` | Keep final newline | `|` (default) | | `|-` or `>-` | Strip final newline | `|-` | | `|+` or `>+` | Keep all trailing newlines | `|+` | [code example] ### When It Matters [code example] ## Common Use Cases ### Inline Jinja2 Template [code example] ### Complex Shell with Variables [code example] ### Multiline when Condition [code example] ## Quick Reference [code example] --- *Find more YAML tips in our 800+ Ansible tutorials.* --- ## Ansible Multiline Strings — YAML Block Scalars Guide URL: https://www.ansiblebyexample.com/articles/ansible-multiline-strings-yaml-block-scalars Description: Master multiline strings in Ansible with YAML literal and folded block scalars. Use |, >, |-, >- for shell commands, templates, and config content. ## Introduction YAML provides four block scalar styles for multiline strings in Ansible. Choosing the right one controls whether newlines are preserved or folded, and whether a trailing newline is kept or stripped. ## The Four Styles | Style | Newlines | Trailing Newline | Use For | |-------|----------|-----------------|---------| | `\|` (literal) | Preserved | Yes | Shell scripts, config files | | `\|−` (literal strip) | Preserved | No | Inline content, templates | | `>` (folded) | Folded to spaces | Yes | Long descriptions | | `>−` (folded strip) | Folded to spaces | No | Single-line from multiline | ## Literal Block ( | ) — Preserves Newlines Each line break in YAML becomes a newline in the string: [code example] Output preserves line breaks exactly: [code example] (Plus a trailing newline) ## Literal Strip ( |- ) — No Trailing Newline Same as `|` but removes the final newline: [code example] Useful when the trailing newline would cause issues: [code example] ## Folded Block ( > ) — Folds Newlines to Spaces Newlines become spaces (like word wrapping): [code example] **Blank lines create real newlines:** [code example] ## Folded Strip ( >- ) — Folds + No Trailing Newline [code example] ## Shell Commands [code example] ## Debug Messages [code example] ## Copy Content [code example] ## Indentation The content must be indented more than the key: [code example] ## Common Patterns ### Heredoc Alternative [code example] ### Long when Conditions [c... --- ## Ansible MySQL — Databases Users Replication Backup URL: https://www.ansiblebyexample.com/articles/ansible-mysql-databases-users-replication-backup Description: Ansible MySQL guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible MySQL — Databases Users Replication Backup ## Introduction Databases Users Replication Backup. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible MySQL requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible MySQL and PostgreSQL Database Automation URL: https://www.ansiblebyexample.com/articles/ansible-mysql-postgresql-database-automation Description: Automate MySQL and PostgreSQL database management with Ansible. Create databases, users, grants, backups, replication setup, and schema migrations using. ## Introduction Ansible manages MySQL/MariaDB through the `community.mysql` collection and PostgreSQL through `community.postgresql`. Both collections provide modules for database creation, user management, privileges, configuration, backups, and replication. This guide covers the most common database automation tasks for both engines. ## Prerequisites [code example] ## MySQL / MariaDB ### Install MySQL [code example] ### Create Databases [code example] ### Manage Users and Privileges [code example] ### MySQL Configuration [code example] ### Import SQL File [code example] ### Backup MySQL [code example] ### MySQL Replication [code example] ## PostgreSQL ### Install PostgreSQL [code example] ### Create Databases [code example] ### Manage Users (Roles) [code example] ### Manage Privileges [code example] ### PostgreSQL Extensions [code example] ### PostgreSQL Configuration [code example] ### Configure pg_hba.conf [code example] ### Backup PostgreSQL [code example] ### Run SQL Queries [code example] ## Troubleshooting ### MySQL: "Access denied" [code example] ### PostgreSQL: "Peer authentication failed" [code example] ## Related Articles - Ansible Template Module - Ansible Vault Guide - Ansible Handlers Guide - Ansible Docker Compose ## Conclusion The `community.mysql` and `community.postgresql` collections provide complete database lifecycle management — create databases, manage users and privileges, configure settings, run queries, ... --- ## Ansible mysql_db Module — Manage MySQL Databases URL: https://www.ansiblebyexample.com/articles/ansible-mysql-db-module-manage-mysql-databases Description: Create, drop, dump, and import MySQL/MariaDB databases with Ansible automation. Tested on real machines with clear, copy-paste examples. # Ansible mysql_db Module — Manage MySQL Databases ## Introduction The `community.mysql.mysql_db` module create, drop, dump, and import MySQL/MariaDB databases with Ansible automation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.mysql` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.mysql.mysql_db` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `-... --- ## Ansible mysql_user Module — Manage MySQL Users and Privileges URL: https://www.ansiblebyexample.com/articles/ansible-mysql-user-module-manage-mysql-users-and-privileges Description: Create MySQL/MariaDB users, set passwords, and manage database privileges. Hands-on, tested examples and best practices for Ansible mysql_user Module. # Ansible mysql_user Module — Manage MySQL Users and Privileges ## Introduction The `community.mysql.mysql_user` module create MySQL/MariaDB users, set passwords, and manage database privileges. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.mysql` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.mysql.mysql_user` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** —... --- ## Ansible Nagios — Deploy and Configure Infrastructure Monitoring URL: https://www.ansiblebyexample.com/articles/ansible-nagios-infrastructure-monitoring Description: Deploy Nagios Core with Ansible. Install Nagios server and NRPE agents, configure hosts, services, contacts, check commands, custom plugins, and alerting.. ## Introduction Nagios Core is the industry-standard infrastructure monitoring system — tracks host availability, service health, and performance metrics with alerting. Ansible automates the entire stack: Nagios server installation, NRPE agent deployment on all hosts, host/service configuration from inventory, custom check plugins, and contact/escalation management. ## Deploy Nagios Server [code example] ### Host Configuration Template [code example] ## Deploy NRPE Agents [code example] ### NRPE Config Template [code example] ## Contacts and Alerting [code example] ## Monitoring Check [code example] ## Troubleshooting ### Config Verification [code example] ### NRPE Connection Refused [code example] ## Related Articles - Ansible Prometheus Grafana - Ansible Grafana Loki - Ansible Service Module - Ansible Firewall Module ## Conclusion Ansible generates Nagios host and service configurations directly from inventory — adding a server to a group automatically creates the monitoring config. Deploy NRPE agents with group-specific checks (web servers get HTTP checks, databases get PostgreSQL checks), manage contacts and escalations as code, and validate config before every restart. Monitoring infrastructure becomes as reproducible as the infrastructure it monitors. --- ## Ansible Navigator — Modern CLI for Playbooks and EEs URL: https://www.ansiblebyexample.com/articles/ansible-navigator-modern-cli-interface Description: Use ansible-navigator as a modern replacement for ansible-playbook. Run playbooks in Execution Environments, explore inventory, browse docs, and replay. # Ansible Navigator — Modern CLI for Playbooks and EEs ## Introduction `ansible-navigator` is a text-based user interface (TUI) for Ansible that replaces `ansible-playbook`, `ansible-doc`, `ansible-inventory`, and `ansible-config` with a single tool. It runs playbooks inside Execution Environments (EEs) by default and provides interactive exploration of runs, inventory, and documentation. ## Install [code example] ## Run Playbooks [code example] ## Interactive Mode The TUI provides real-time navigation through playbook execution: [code example] ## Key Subcommands [code example] ## Configuration File [code example] ## Stdout vs Interactive Mode | Feature | `--mode stdout` | `--mode interactive` | |---------|-----------------|---------------------| | Output | Like ansible-playbook | TUI with navigation | | CI/CD | ✅ Ideal | ❌ Needs terminal | | Debugging | Scroll through output | Drill into tasks | | Artifacts | Optional | Always saved | ## Artifacts and Replay Every interactive run saves an artifact JSON file. Replay it later: [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Builder — Build Custom EEs - Ansible Execution Environments - Ansible at Scale - Ansible Automation Platform ## Conclusion `ansible-navigator` modernizes the Ansible CLI experience — run playbooks in EEs for consistency, drill into task results interactively, and replay past runs for debugging. For CI/CD, use `--mode stdout`. For development, the intera... --- ## Ansible Nested List Optimization URL: https://www.ansiblebyexample.com/articles/nested-list-optimization-in-ansible-playbooks Description: Learn how to handle and optimize nested lists in Ansible using powerful filters like `flatten` and `unique`. Simplify your playbooks and enhance. ## Optimizing Nested Lists in Ansible Ansible, a powerful IT automation tool, often deals with complex data structures. Nested lists are a common challenge, requiring flattening and optimization for effective use. In this article, we explore how to handle and optimize nested lists using Ansible’s powerful filters. --- ### The Challenge: Nested List Structures Imagine this input structure: [code example] This structure contains nested lists, including empty elements. For streamlined automation, we need to: 1. Flatten the structure into a single list. 2. Remove empty elements. 3. Optionally remove duplicates. --- ### Solution: Flattening and Optimizing Lists Ansible’s `flatten` filter is a simple and effective tool for flattening nested lists. Let’s dive into an example playbook: #### Playbook Example [code example] --- ### Resulting Output After running the playbook, the `optimized_list` will look like this: [code example] --- ### Removing Duplicates To remove duplicates from the flattened list, use the `unique` filter: [code example] This ensures the list contains only unique elements. --- ### Real-World Use Cases 1. **Dynamic Inventories**: Combine nested inventory groups into a single, manageable list. 2. **Configuration Management**: Normalize and optimize data structures before applying configurations. 3. **Data Processing**: Clean up API responses or aggregated data for streamlined automation workflows. --- ### Conclusion With Ansible’s `flatten... --- ## Ansible NetBox Integration — Network Source of Truth URL: https://www.ansiblebyexample.com/articles/ansible-netbox-integration-network-source-of-truth Description: Integrate Ansible with NetBox for dynamic inventory, DCIM automation, and IPAM management. Complete guide to netbox.netbox collection — devices, IPs,. ## Introduction NetBox is the leading open-source platform for network infrastructure modeling — DCIM (data center infrastructure management) and IPAM (IP address management). The `netbox.netbox` Ansible collection provides a dynamic inventory plugin that pulls device and VM data directly from NetBox, plus modules to manage every NetBox object. This makes NetBox your single source of truth and Ansible your automation engine. ## Prerequisites [code example] ### NetBox API Token 1. In NetBox: **Admin → API Tokens → Add Token** 2. Set permissions (read-only for inventory, read-write for modules) 3. Save the token ## Dynamic Inventory from NetBox ### Basic Configuration [code example] [code example] ### Advanced Inventory Configuration [code example] ### Test Inventory Groups [code example] ## Manage NetBox Objects with Ansible ### Create Sites [code example] ### Create Devices [code example] ### Manage IP Addresses [code example] ### Manage VLANs [code example] ## Full Workflow: NetBox → Ansible → Network [code example] ## Lookup Plugin Query NetBox from within playbooks: [code example] ## Troubleshooting ### "pynetbox" Not Found [code example] ### Empty Inventory - Check `query_filters` — `has_primary_ip: true` excludes devices without IPs - Verify API token permissions - Check device `status: active` in NetBox ### SSL Certificate Errors [code example] ## Best Practices 1. **NetBox is the source of truth** — never hardcode IPs or device lists... --- ## Ansible netconf_config Module — Manage Device Config via NETCONF URL: https://www.ansiblebyexample.com/articles/ansible-netconf-config-module-manage-device-config-via-netconf Description: Push and manage XML configuration via NETCONF protocol with Ansible. Hands-on, tested examples and best practices for Ansible netconf_config Module. # Ansible netconf_config Module — Manage Device Config via NETCONF ## Introduction The `ansible.netcommon.netconf_config` module push and manage XML configuration via NETCONF protocol with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.netcommon` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.netcommon.netconf_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in che... --- ## Ansible netconf_get Module — Retrieve Data via NETCONF URL: https://www.ansiblebyexample.com/articles/ansible-netconf-get-module-retrieve-data-via-netconf Description: Query operational and configuration data from NETCONF-enabled devices. Tested on real machines with clear, copy-paste examples. # Ansible netconf_get Module — Retrieve Data via NETCONF ## Introduction The `ansible.netcommon.netconf_get` module query operational and configuration data from NETCONF-enabled devices. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.netcommon` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.netcommon.netconf_get` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — ru... --- ## Ansible Network — Cisco Juniper Arista URL: https://www.ansiblebyexample.com/articles/ansible-enterprise-network-automation-cisco-juniper-arista Description: Automate enterprise networks with Ansible. Configure Cisco IOS/NX-OS, Juniper Junos, and Arista EOS using standardized playbooks and network modules. ## Introduction Enterprise networks span thousands of switches, routers, firewalls, and load balancers across multiple vendors. Managing configuration changes manually — SSH into each device, paste commands, hope nothing breaks — doesn't scale. Ansible's agentless architecture and vendor-specific collections make it the de facto tool for multi-vendor network automation: same playbook structure, same inventory, same CI/CD pipeline, regardless of whether the target is a Cisco Nexus, Juniper QFX, or Arista 7050X. This guide covers practical patterns for enterprise network automation across the three major vendors, from initial setup through production workflows. ## Network Collections | Vendor | Collection | Connection | Platforms | |--------|-----------|------------|-----------| | Cisco IOS/IOS-XE | `cisco.ios` | `network_cli` | Catalyst, ISR, ASR | | Cisco NX-OS | `cisco.nxos` | `network_cli` / `httpapi` | Nexus 3K/5K/7K/9K | | Juniper Junos | `junipernetworks.junos` | `netconf` | QFX, EX, MX, SRX | | Arista EOS | `arista.eos` | `network_cli` / `httpapi` | 7050X, 7280R, 720XP | | Multi-vendor | `ansible.netcommon` | Various | Resource modules base | [code example] ## Inventory Structure [code example] ## Pattern 1: Configuration Backup The first automation win — backup every device before any change. [code example] ## Pattern 2: VLAN Management with Resource Modules Resource modules provide a vendor-agnostic approach — same data structure, different platforms. [co... --- ## Ansible Network Automation — Cisco Juniper Arista URL: https://www.ansiblebyexample.com/articles/ansible-network-automation-cisco-juniper-arista Description: Ansible Network Automation guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Network Automation — Cisco Juniper Arista ## Introduction Cisco Juniper Arista. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted deviations ## Con... --- ## Ansible NFS Server Setup — Red Hat URL: https://www.ansiblebyexample.com/articles/export-an-nfs-share-in-redhat-like-systems-ansible-modules-yum-file-lineinfile-command-firewalld-service Description: Learn to automate the installation and configuration of an NFS server on Red Hat using an Ansible playbook. Enhance your system's efficiency now. ## How to export NFS Share in RedHat-like Linux systems with Ansible? ## Export an NFS Share in RedHat-like systems - install packages => `ansible.builtin.yum` - create directory => `ansible.builtin.file` - share in config => `ansible.builtin.lineinfile` - export shares => `ansible.builtin.command` - restart service => `ansible.builtin.service` - open firewall => `ansible.posix.firewalld` Today we're talking about how to export an NFS Share in RedHat-like Linux systems. The full process requires six steps that you could automate with six different Ansible modules. Firstly you need to install the `nfs-utils` package and dependency using the `ansible.builtin.yum` Ansible module. Secondly, you need to create the share directory and assign the permission using the `ansible.builtin.file` Ansible module. Thirdly you need to add the share in the `/etc/exports` config file using the `ansible.builtin.lineinfile` Ansible module to add text lines in files. Fourthly you need to export shares executing the `exportfs` command line utility via `ansible.builtin.command` Ansible module, unfortunately there is not a specific module, yet. Fifthly you need to restart the `nfs-server` service and all the dependant using the `ansible.builtin.service` Ansible module. Sixthly you need to open the relevant firewall service-related ports using the `ansible.posix.firewalld` Ansible module. ## Playbook Export NFS Share in RedHat-like systems with Ansible Playbook. ### code - nfs_server_redhat.ym... --- ## Ansible Nginx — Install, Configure, and Deploy Web Servers URL: https://www.ansiblebyexample.com/articles/ansible-nginx-install-configure-deploy Description: Use Ansible to install Nginx, configure virtual hosts, deploy SSL certificates, set up reverse proxy, and manage load balancing. ## Introduction Nginx is the most popular web server and reverse proxy. Ansible automates the full lifecycle — install, configure virtual hosts, deploy SSL certificates, set up reverse proxy, and manage load balancing across your fleet. ## Install Nginx [code example] ## Basic Configuration [code example] ### nginx.conf.j2 [code example] ## Virtual Host (Server Block) [code example] ### vhost.conf.j2 [code example] ## SSL/TLS with Let's Encrypt [code example] ### SSL Virtual Host Template [code example] ## Reverse Proxy [code example] [code example] ## Load Balancing [code example] ## Complete Web Server Playbook [code example] ## Troubleshooting ### "nginx: [emerg] bind() to 0.0.0.0:80 failed" Port 80 already in use: [code example] ### Config Validation Always validate before applying: [code example] ## Related Articles - Ansible Jinja2 Templates - Ansible service Module - Ansible Firewall Guide - Ansible cron Module ## Conclusion Ansible + Nginx is a powerful combination for web server automation. Use Jinja2 templates for dynamic configs that scale across hosts. Always use `validate` to catch config errors before they cause downtime. Use handlers for reload (not restart) to avoid dropping connections. Automate SSL with Certbot. For reverse proxy and load balancing, build upstream blocks dynamically from inventory groups. --- ## Ansible Nginx Reverse Proxy — Flask URL: https://www.ansiblebyexample.com/articles/automating-nginx-reverse-proxy-setup-for-flask-on-rhel Description: Learn how to configure Nginx as a reverse proxy for a Flask application running on RHEL 8. Secure the setup with a custom SSL certificate and automate the. ## 🔍 Introduction When deploying a **Flask web application**, it's best practice to place it behind a **reverse proxy** to enhance security, enable **SSL encryption**, and optimize traffic handling. **Nginx** is a powerful web server that efficiently handles these tasks. In this guide, we will: - Configure **Nginx as a reverse proxy** for a **Flask application** running on **port 5000**. - Secure the setup with a **custom SSL certificate**. - Automate the installation and configuration using **Ansible** on **RHEL 8**. By the end, you’ll have a fully automated solution that ensures your Flask app is securely accessible over **HTTPS**. --- ## 🚀 Steps to Automate Installation Using Ansible ### 1️⃣ Install Nginx on RHEL 8 We need to install **Nginx** to act as a **reverse proxy** for our Flask app. ### 2️⃣ Copy SSL Certificates The **SSL certificate** and **private key** must be placed in the correct directory. ### 3️⃣ Configure Nginx Reverse Proxy We will create an **Nginx configuration file** to route traffic to our Flask application. ### 4️⃣ Enable and Start Nginx Ensure that **Nginx starts on boot** and is running. --- ## 📝 Ansible Playbook Create a new **Ansible playbook** named `nginx_reverse_proxy.yml`: [code example] --- ## 🔧 Nginx Configuration Template Create a **Jinja2 template** file named `templates/flask_nginx.conf.j2`: [code example] --- ## 📂 Directory Structure Ensure your **Ansible project** has the following structure: [code exam... --- ## Ansible nmcli Module — Configure Network Connections URL: https://www.ansiblebyexample.com/articles/ansible-nmcli-module-configure-network-connections Description: Ansible nmcli Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible nmcli Module — Configure Network Connections ## Introduction Configure Network Connections. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible nmcli Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** f... --- ## Ansible No Hosts Matched Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-no-hosts-matched-error-fix-and-solutions Description: Fix no hosts matched pattern from inventory issues and wrong group names. With clear, copy-paste, step-by-step examples. # Ansible No Hosts Matched Error — Fix and Solutions ## Introduction Fix no hosts matched pattern from inventory issues and wrong group names. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix no hosts matched pattern from inventory issues and wrong group names. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible no_log — Hide Sensitive Data URL: https://www.ansiblebyexample.com/articles/protecting-sensitive-information-with-the-no-log-statement-in-ansible Description: Complete guide to Ansible no_log directive. Learn how to hide passwords, API keys, and secrets from playbook output. Includes examples, debugging tips,. The `no_log: true` directive in Ansible prevents sensitive data — passwords, API keys, tokens, and certificates — from appearing in playbook output and log files. Without it, Ansible logs every task's input and output in plain text, which can expose secrets in CI/CD logs, terminal output, and callback plugin data. ## How no_log Works When you add `no_log: true` to a task, Ansible replaces the task output with `"censored"` in all logging destinations: [code example] **Without `no_log`**, the output shows: [code example] **With `no_log: true`**, the output shows: [code example] ## When to Use no_log ### Always Use no_log For - **Password and credential tasks**: Creating users, database accounts, service credentials - **API key operations**: Registering tokens, setting up integrations - **Certificate and private key handling**: Deploying TLS certificates - **Cloud provider credentials**: AWS access keys, Azure service principals - **Vault-encrypted variable usage**: Any task that decrypts and uses vault secrets ### Common Examples #### User Management with Passwords [code example] #### API Token Registration [code example] #### Deploying TLS Certificates [code example] #### Cloud Provider Credentials [code example] ## Applying no_log at Different Levels ### Task Level (Most Common) [code example] ### Block Level Apply to multiple tasks at once: [code example] ### Play Level Hide all tasks in an entire play: [code example] ### Role Level (via Role Def... --- ## Ansible no_log — Output Visibility URL: https://www.ansiblebyexample.com/articles/ansible-no-log-hide-sensitive-data-from-output Description: Use no_log to prevent Ansible from displaying passwords, API keys, and tokens in task output, logs, and callback plugins. Protect secrets in automation. # Ansible no_log — Hide Sensitive Data from Output ## Introduction Ansible displays task results in terminal output, log files, and callback plugins. When tasks handle passwords, API keys, or tokens, this data appears in plain text. `no_log: true` suppresses the output for sensitive tasks, replacing it with `"censored"` — preventing secret leakage in CI/CD logs, terminal history, and centralized logging systems. ## Basic Usage [code example] ## Common Use Cases ### Database Credentials [code example] ### API Keys and Tokens [code example] ### SSL Certificates and Private Keys [code example] ## Conditional no_log [code example] ## no_log with Loops [code example] ## no_log with register [code example] ## Global no_log Setting [code example] [code example] ## What no_log Hides | Hidden | Not Hidden | |--------|-----------| | Task arguments (module params) | Task name | | Return values (stdout, result) | Task status (ok/changed/failed) | | Loop item values | Host name | | Registered variable content | Task duration | | Debug output of no_log vars | Error messages (partially) | ## Troubleshooting | Issue | Solution | |-------|----------| | Can't debug a failing no_log task | Temporarily set `no_log: false`, fix, re-enable | | CI/CD logs show secrets | Add `no_log: true` to ALL tasks handling secrets | | Ansible Lint warning `no-log-password` | Lint correctly detected missing `no_log` — add it | | `no_log` on `debug` task | Pointless — debug exists to show ... --- ## Ansible no_log — Playbook Secrets URL: https://www.ansiblebyexample.com/articles/ansible-no-log-hide-sensitive-data-from-playbook-output Description: Learn how to use no_log in Ansible to hide sensitive data like passwords and API keys from task output. Includes examples, debugging tips, and best. ## What is no_log? The `no_log: true` directive tells Ansible to suppress all output for a task — preventing sensitive data like passwords, API keys, and tokens from appearing in logs. Without `no_log`, Ansible prints task results including all variables: [code example] With `no_log: true`: [code example] ## Basic Usage [code example] ## Common Use Cases ### API Tokens [code example] ### Database Credentials [code example] ### SSH Keys and Certificates [code example] ### Environment Variables with Secrets [code example] ## Conditional no_log Use a variable to toggle logging during debugging: [code example] Set `hide_sensitive: false` when debugging, `true` in production. ## Debugging no_log Tasks When a `no_log` task fails, the error is also hidden. Temporarily disable it: [code example] Better approach — use a conditional: [code example] ## Play-Level no_log Apply to all tasks in a play: [code example] ## Best Practices 1. **Always use no_log** with passwords, tokens, API keys, and certificates 2. **Combine with Ansible Vault** — encrypt at rest, hide in output 3. **Use conditional no_log** for easier debugging 4. **Don't put no_log on every task** — only sensitive ones. Over-using it makes troubleshooting painful 5. **Check CI/CD logs** — ensure your pipeline doesn't capture sensitive output before `no_log` is processed ## no_log vs Ansible Vault | Feature | no_log | Vault | |---------|--------|-------| | Purpose | Hide from runtime output | ... --- ## Ansible no_log: Hide Passwords & Secrets URL: https://www.ansiblebyexample.com/articles/ansible-no-log-hide-sensitive-output Description: Ansible no_log prevents passwords, API keys, and secrets from appearing in playbook output and logs. Learn when and how to use it. ## What is Ansible no_log? `no_log: true` prevents Ansible from displaying task input and output in the console and logs. Use it whenever a task handles passwords, API keys, tokens, or any sensitive data that shouldn't appear in plain text. ## Basic Usage [code example] ## When to Use no_log [code example] ## Conditional no_log [code example] ## no_log on Variables [code example] ## Block-Level no_log [code example] ## Debug with no_log When `no_log: true` hides errors, temporarily disable it: [code example] ## What no_log Hides | Hidden | Not Hidden | |--------|-----------| | Task arguments (input) | Task name | | Task output (stdout/stderr) | Host name | | Registered variables | Changed/OK status | | Loop items | Task duration | | Callback plugin data | Play name | [code example] ## Common Mistakes ### Forgetting no_log on Debug [code example] ### Loop Items Visible [code example] ### Registered Result Leaks [code example] ## ansible-lint Rule ansible-lint warns when `no_log` is missing on tasks that appear to handle secrets: [code example] Fix: add `no_log: true` to any task with password parameters. ## Related Articles - Ansible Vault Guide - Ansible Best Practices - Ansible Error Handling - Ansible debug Module ## Conclusion Use `no_log: true` on every task that handles passwords, tokens, API keys, or sensitive data. Apply it to blocks for groups of sensitive tasks. Use conditional `no_log` to enable logging in dev but hide in production. ... --- ## Ansible no-changed-when — Lint Rule Fix URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-301-no-changed-when Description: Fix Ansible Lint Error 301 no-changed-when — ensure command/shell tasks report changes correctly with changed_when. Tested, copy-paste examples included. ## Introduction Ansible Lint rule 301 (`no-changed-when`) flags tasks that execute commands without defining when the task should be considered "changed." This primarily affects the `command`, `shell`, `raw`, and `script` modules, which always report `changed: true` by default — even when they perform read-only operations. This article explains why this matters, every strategy for fixing it, and how `changed_when` enables truly idempotent playbooks. ## Why This Matters Ansible's change tracking is fundamental to: - **Handlers**: Only triggered when a notifying task reports `changed` - **`--check` mode**: Accurate dry-run behavior - **Audit logs**: Know what actually changed during a run - **Idempotency**: Running a playbook twice should produce the same result When `command`/`shell` tasks always report `changed`, you get false positives that: 1. Trigger handlers unnecessarily (restarting services when nothing changed) 2. Make `--check` output unreliable 3. Hide real changes in noisy output 4. Break idempotency assumptions ## The Error ### Problematic Code [code example] ### Lint Output [code example] ## Solution 1: changed_when with Return Code The most common pattern — use the command's return code: [code example] ## Solution 2: changed_when: false for Read-Only Commands When a command never changes anything: [code example] ## Solution 3: changed_when Based on Output Check command output to determine if something actually changed: [code example] ## Solut... --- ## Ansible no-log-password — Lint Rule Fix URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-no-log-password Description: Fix ansible-lint no-log-password warnings. When to use no_log: true for passwords, tokens, and secrets in Ansible tasks. Examples and best practices. ## Introduction The `no-log-password` ansible-lint rule warns when tasks that handle passwords or secrets don't have `no_log: true` set. Without it, sensitive data appears in plaintext in Ansible's output, log files, and callback plugins — a security risk in CI/CD pipelines and shared terminals. ## The Problem [code example] Ansible output **exposes the password** in the loop item: [code example] Lint output: [code example] ## The Fix: Add no_log: true [code example] Now Ansible output shows: [code example] ## Modules That Trigger This Rule The rule checks tasks using these parameters: | Module | Parameter | |--------|-----------| | `ansible.builtin.user` | `password` | | `ansible.builtin.lineinfile` | `line` (when contains password) | | `ansible.builtin.uri` | `body`, `url_password` | | `ansible.builtin.command` / `shell` | Arguments containing secrets | | `community.mysql.mysql_user` | `password` | | `community.postgresql.postgresql_user` | `password` | | `community.general.ldap_passwd` | `passwd` | ## Best Practices ### 1. Use Ansible Vault for Secrets Never hardcode passwords. Store them encrypted: [code example] [code example] Reference in playbooks: [code example] ### 2. Use no_log Conditionally for Debugging [code example] This hides output normally but shows it with `-vvv` for debugging. ### 3. Use no_log at Block Level [code example] ### 4. Register Variables Carefully [code example] ### 5. Environment Variables for CI/CD [code example] ... --- ## Ansible Nomad — Deploy HashiCorp Workload Orchestrator URL: https://www.ansiblebyexample.com/articles/ansible-nomad-workload-orchestrator Description: Deploy HashiCorp Nomad with Ansible. Server and client setup, job scheduling, Docker driver, Consul integration, Vault secrets, ACLs, and multi-datacenter. ## Introduction HashiCorp Nomad is a lightweight workload orchestrator that schedules containers, VMs, binaries, and batch jobs. Unlike Kubernetes, Nomad has a simple architecture (single binary) and integrates natively with Consul for service discovery and Vault for secrets. Ansible automates the full deployment: server cluster, client agents, job submissions, ACLs, and monitoring. ## Deploy Nomad Server Cluster [code example] ### Server Config [code example] ## Deploy Client Agents [code example] [code example] ## Submit Jobs [code example] ### Job from HCL File [code example] ## ACL Bootstrap [code example] ## Health Check [code example] ## Troubleshooting ### Allocation Failures [code example] ### Client Not Joining [code example] ## Related Articles - Ansible HashiCorp Vault - Ansible Docker Compose - Ansible Kubernetes - Ansible Consul ## Conclusion Nomad is the simpler alternative to Kubernetes — a single binary that schedules containers, VMs, and raw binaries. Ansible deploys the server cluster and client agents, configures Consul integration for service discovery, and submits jobs via API or CLI. Use Nomad when you need orchestration without Kubernetes complexity: smaller teams, mixed workloads (containers + legacy), and multi-datacenter federation. --- ## Ansible Non-Compliant Variable Names URL: https://www.ansiblebyexample.com/articles/handling-non-compliant-variable-names-in-ansible-easily Description: A guide to managing non-compliant variable names in Ansible, offering tips on aliasing, linter rule adjustments, and using dictionary structures. ## Handling Variable Naming Constraints in Ansible: Workarounds for Compliance When working with automation tools like Ansible, adhering to variable naming conventions is essential for maintainability, readability, and avoiding conflicts. Some setups, however, enforce specific naming patterns for variables, such as `^[a-z_][a-z0-9_]*$`, which only allows lowercase letters, numbers, and underscores, and requires the variable name to start with a letter or underscore. If you’re using a variable name that doesn’t comply—such as `vcenter.account`—changing it outright might not always be feasible. This article explores effective workarounds that let you keep the original variable name intact while ensuring compliance with naming standards. --- ### 1. Define an Alias Variable One of the simplest ways to handle non-compliant variable names is to define an alias that adheres to the required pattern and assign it the value of the original variable. This approach allows the original variable name to stay unchanged while you use the alias wherever compliance is required. #### Example Suppose you’re using the variable `cloud.config`, which doesn’t meet the required pattern due to the dot (`.`) separator. You can create an alias like this: [code example] Now, instead of using `cloud.config` directly, you can use `cloud_config` in parts of your code that require a compliant variable name. #### How to Use It [code example] This approach is especially useful if you have multiple ... --- ## Ansible npm Module — Manage Node.js Packages with npm URL: https://www.ansiblebyexample.com/articles/ansible-npm-module-manage-node-js-packages-with-npm Description: Install, update, and manage Node.js packages globally or per-project with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible npm Module — Manage Node.js Packages with npm ## Introduction The `community.general.npm` module install, update, and manage Node.js packages globally or per-project with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.npm` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run wit... --- ## Ansible nsupdate Module — Manage DNS Records Dynamically URL: https://www.ansiblebyexample.com/articles/ansible-nsupdate-module-manage-dns-records-dynamically Description: Add, modify, and delete DNS records using dynamic DNS updates (RFC 2136). With clear, copy-paste, step-by-step examples. # Ansible nsupdate Module — Manage DNS Records Dynamically ## Introduction The `community.general.nsupdate` module add, modify, and delete DNS records using dynamic DNS updates (RFC 2136). This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.nsupdate` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run... --- ## Ansible NTP Chrony — Time Synchronization at Scale URL: https://www.ansiblebyexample.com/articles/ansible-ntp-chrony-time-synchronization-at-scale Description: Ansible NTP Chrony guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible NTP Chrony — Time Synchronization at Scale ## Introduction Time Synchronization at Scale. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible NTP Chrony requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible nxos_command Module — Run Commands on Cisco NX-OS Devices URL: https://www.ansiblebyexample.com/articles/ansible-nxos-command-module-run-commands-on-cisco-nx-os-devices Description: Execute commands on Cisco Nexus switches running NX-OS with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible nxos_command Module — Run Commands on Cisco NX-OS Devices ## Introduction The `cisco.nxos.nxos_command` module execute commands on Cisco Nexus switches running NX-OS with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install cisco.nxos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `cisco.nxos.nxos_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--... --- ## Ansible nxos_config Module — Manage Cisco NX-OS Configuration URL: https://www.ansiblebyexample.com/articles/ansible-nxos-config-module-manage-cisco-nx-os-configuration Description: Deploy configuration to Cisco Nexus data center switches with Ansible. Hands-on, tested examples and best practices for Ansible nxos_config Module. # Ansible nxos_config Module — Manage Cisco NX-OS Configuration ## Introduction The `cisco.nxos.nxos_config` module deploy configuration to Cisco Nexus data center switches with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install cisco.nxos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `cisco.nxos.nxos_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--chec... --- ## Ansible on Raspberry Pi — Automate Your Homelab URL: https://www.ansiblebyexample.com/articles/ansible-raspberry-pi-homelab-automation Description: Install Ansible on Raspberry Pi and automate homelab tasks — Pi-hole, Docker, monitoring, cluster management, k3s, backups, and fleet management for. ## Introduction Raspberry Pi is the most popular homelab platform — affordable, low-power, and capable of running everything from Pi-hole to Kubernetes clusters. Ansible automates the entire lifecycle: initial setup, package management, service configuration, monitoring, backups, and fleet management across multiple Pis. This guide covers everything from installing Ansible on a Pi to managing a full homelab cluster. ## Install Ansible ### On Raspberry Pi OS (Debian-based) [code example] ### On Ubuntu Server for Pi [code example] ### Use a Separate Controller For best results, run Ansible from a laptop/desktop and manage Pis remotely: [code example] ## Bootstrap New Raspberry Pi [code example] ## Deploy Pi-hole [code example] ## Deploy Docker on Pi [code example] ## Deploy Monitoring Stack [code example] ## K3s Cluster on Raspberry Pi [code example] ## Automated Backups [code example] ## Performance Tips for Pi | Tip | Why | |---|---| | Use `gather_subset: min` | Full fact gathering is slow on Pi | | Use `pipelining = true` | Reduces SSH round trips | | Use `forks = 5` | Don't overwhelm a Pi controller | | Avoid `shell` module | `apt`, `copy`, `template` are faster | | Use `async` for long tasks | Don't block on updates | [code example] ## Related Articles - How to Install Ansible on Ubuntu - Ansible Docker Guide - Ansible Firewall Module - Ansible Cron Module ## Conclusion Ansible turns a collection of Raspberry Pis into a managed homelab — consist... --- ## Ansible on RHEL 10 — Migration Guide URL: https://www.ansiblebyexample.com/articles/ansible-rhel-10-migration-guide Description: Guide to running Ansible on RHEL 10 — Python 3.12 default, new package names, systemd changes, firewalld updates, and playbook migration from RHEL 9 to. ## Introduction Red Hat Enterprise Linux 10 ships with Python 3.12 as the system Python, updated package names, and systemd/firewalld changes that affect Ansible playbooks. If you're managing RHEL 9 hosts and planning to add RHEL 10, this guide covers what changed, what breaks, and how to update your playbooks for both versions. ## What Changed in RHEL 10 | Area | RHEL 9 | RHEL 10 | |---|---|---| | Python | 3.9 (default), 3.11/3.12 optional | **3.12 (default)** | | Kernel | 5.14 | **6.12** | | systemd | 252 | **256** | | Firewalld | 1.x | **2.x** | | Podman | 4.x | **5.x** | | OpenSSL | 3.0 | **3.2** | | GCC | 11 | **14** | | ansible-core (AppStream) | 2.14 | **2.17** | | Network config | NetworkManager | **NetworkManager** (nmstate default) | | Default editor | vi | **vi** (nano available) | | Crypto policy | DEFAULT | **DEFAULT** (stricter TLS defaults) | | Support | Until 2032 | **Until 2035** | ## Install Ansible on RHEL 10 ### As Controller (Run Ansible From RHEL 10) [code example] ### As Managed Node (Target Host) RHEL 10 targets need Python 3.12 (installed by default): [code example] ### Inventory Configuration [code example] ## Python Changes ### Python 3.12 as Default RHEL 10's system Python is 3.12. Key impacts for Ansible: [code example] ### Removed Python 2 Python 2 is completely removed. If your playbooks or custom modules use Python 2 syntax, they will fail: [code example] ### pip and Virtual Environments [code example] ## Package Name Chang... --- ## Ansible on Ubuntu 26.04 — What Changed URL: https://www.ansiblebyexample.com/articles/ansible-on-ubuntu-26-04-lts-sudo-rs-apt-rollback Description: Guide to running Ansible on Ubuntu 26.04 LTS — sudo-rs replaces sudo, APT 3.2 rollback, Wayland-only, Kernel 7.0, ROCm. Updated playbooks, privilege. ## Introduction Ubuntu 26.04 LTS "Resolute Raccoon" ships changes that directly affect how Ansible manages Ubuntu hosts. The headline: **sudo-rs is now the default sudo provider** — a full Rust rewrite of the binary that handles every privilege escalation on your fleet. If you run Ansible with `become: true` (and you do), this matters. This article covers what changed, what breaks, what doesn't, and how to update your playbooks and base images. ## What Changed in Ubuntu 26.04 LTS | Change | Impact on Ansible | |---|---| | **sudo-rs** replaces sudo (C) | `become_method: sudo` works unchanged — same `/etc/sudoers` format | | **Kernel 7.0** | Intel TDX confidential computing, broader hardware support | | **APT 3.2** with transaction rollback | New `apt history-rollback` command; `ansible.builtin.apt` works as before | | **Wayland-only** (X11 removed) | No impact on headless servers; affects desktop automation | | **ROCm in official repos** | `apt install rocm` — AMD GPU compute is a one-liner | | **Ptyxis replaces GNOME Terminal** | Desktop only — no server impact | | **LTS until 2031** | 5 years standard, 10 years with Ubuntu Pro | ## sudo-rs: Why It Matters `sudo` is the binary that runs as root on every Linux machine you manage. The original C implementation dates to 1980 and has had critical CVEs — most notably **Baron Samedit (CVE-2021-3156)** in 2021, which allowed local privilege escalation and had been exploitable for over 10 years across most Linux distros. sudo-r... --- ## Ansible OPA Policy Validation URL: https://www.ansiblebyexample.com/articles/project-policy-validation-with-opa-and-ansible-policy Description: A comprehensive guide to setting up and using the Ansible Policy tool for managing policies in your Ansible projects and create effective Rolebook. ## Introduction There's a new Ansible feature in town, and I'm thrilled to announce the Ansible Policy utility, which can directly interact with the Open Policy Agent (OPA). If you're familiar with Kubernetes, you might already know OPA's popularity for specifying rules and validating projects against them. This utility is particularly beneficial for organizations that need to ensure their projects comply with specific policies. For instance, in this example, I'll validate my playbook against a policy that restricts AWS EC2 machine allocation to the US East 1 and US East 2 regions. As you'll see, my playbook isn't compliant, as specified on lines 15 and 29, because it attempts to allocate machines in different regions. By flagging non-compliance, we prevent the execution of configurations that don't meet our standards. So, why haven't you heard about Ansible Policy? Because it's a new prototype implementation that allows you to define and set OPA rules within your application using the Ansible Policy utility. ### Architectural Diagram Here's an architectural diagram illustrating the interaction between the Ansible Policy engine, the Ansible repository, the rules, and how you can validate your project. Everything is integrated, relying on the API command by the Ansible Policy command line utility, which ultimately provides a validated or not validated result. ### Installation Guide To install the Ansible Policy command, follow these steps: 1. **Set Up a Python Virtual ... --- ## Ansible OpenLDAP — Deploy Directory Services URL: https://www.ansiblebyexample.com/articles/ansible-openldap-directory-services Description: Deploy OpenLDAP with Ansible. Server installation, DIT structure, user and group management, TLS encryption, replication, SSSD client integration. ## Introduction OpenLDAP is the standard open-source LDAP directory server for centralized authentication and user management. Ansible automates the full stack: install OpenLDAP, configure the DIT (Directory Information Tree), manage users and groups, set up TLS, configure replication, and deploy SSSD clients for Linux authentication. ## Deploy OpenLDAP Server [code example] ## Manage Users [code example] ### User Variables [code example] ## TLS Configuration [code example] ## SSSD Client Configuration [code example] [code example] ## Password Policy [code example] ## Search and Verify [code example] ## Troubleshooting ### Check slapd Status [code example] ## Related Articles - Ansible User Module - Ansible SSH Key Management - Ansible Compliance Guide - Ansible OpenSSL Certificates ## Conclusion OpenLDAP provides centralized identity management for Linux infrastructure — Ansible automates the server deployment, DIT structure, user/group creation, TLS encryption, and SSSD client configuration. Use `community.general.ldap_entry` and `ldap_attrs` modules for declarative directory management. Users defined in YAML variables, password policies enforced centrally, and every client configured from inventory. Identity as code. --- ## Ansible openssh_keypair — Generate SSH Key Pairs URL: https://www.ansiblebyexample.com/articles/ansible-openssh-keypair-generate-ssh-key-pairs Description: Ansible openssh_keypair guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible openssh_keypair — Generate SSH Key Pairs ## Introduction Generate SSH Key Pairs. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible openssh_keypair requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selec... --- ## Ansible OpenSSL — Manage Certificates, Keys, and PKI URL: https://www.ansiblebyexample.com/articles/ansible-openssl-certificates-keys-pki Description: Manage OpenSSL certificates and keys with Ansible. Generate private keys, CSRs, self-signed certificates, CA infrastructure, certificate chains. ## Introduction The `community.crypto` collection provides Ansible modules for complete PKI management — generate private keys, create CSRs, sign certificates, build certificate authorities, manage certificate chains, and check expiry. No need for manual `openssl` commands; everything is declarative and idempotent. ## Prerequisites [code example] ## Module Reference | Module | Purpose | |---|---| | `openssl_privatekey` | Generate RSA/EC private keys | | `openssl_csr` | Create Certificate Signing Requests | | `x509_certificate` | Generate/sign certificates | | `x509_certificate_info` | Read certificate details | | `certificate_complete_chain` | Build certificate chains | | `openssl_pkcs12` | Create PKCS12 keystores | ## Generate Private Key [code example] ## Create CSR [code example] ## Self-Signed Certificate [code example] ## Build a Certificate Authority ### Root CA [code example] ### Sign Server Certificates [code example] ## Distribute CA Certificate [code example] ## Check Certificate Expiry [code example] ### Fleet-Wide Certificate Audit [code example] ## PKCS12 Keystore (Java/Tomcat) [code example] ## Certificate Chain [code example] ## Troubleshooting ### Verify Certificate Matches Key [code example] ## Related Articles - Ansible Let's Encrypt SSL - Ansible HashiCorp Vault - Ansible Nginx SSL - Ansible Vault Encrypt ## Conclusion The `community.crypto` collection makes PKI management fully declarative — generate keys, create CSRs, buil... --- ## Ansible OpenStack — Manage Cloud Infrastructure URL: https://www.ansiblebyexample.com/articles/ansible-openstack-manage-cloud-infrastructure Description: Ansible OpenStack guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible OpenStack — Manage Cloud Infrastructure ## Introduction Manage Cloud Infrastructure. Automate OpenStack infrastructure with Ansible using the `openstack.cloud` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches OpenStack naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories ... --- ## Ansible Orchestrator Example: Adding a Human Approval Step to a Workflow URL: https://www.ansiblebyexample.com/articles/ansible-orchestrator-example-adding-a-human-approval-step-to-a-workflow Description: Configure a human approval gate in Ansible Automation Orchestrator with usernames, custom message, timeout, and on-timeout fail action. Red Hat's upcoming Automation Orchestrator (coming Q3 2026) runs task-based and event-based automation on a single governed canvas, built on the upstream Temporal durable-execution engine. Its 5-step pipeline puts a mandatory human gate at step 4 — "Humans approve" — between AI-generated remediation plans and anything that touches production. Below is a config example for that gate, modeled on the CVE-2024-6387 ("regresshion") remediation workflow demoed at Red Hat Tech Day Netherlands 2026. ## Example: human review gate config [code example] ## What it does This node sits between the AI recommendation step and the automated remediation step in the orchestrator canvas. When the upstream AI analysis step (using an LLM with MCP tools such as Splunk Query, Splunk Alert Search, Splunk Saved Search, and ServiceNow CMDB Lookup) correlates an alert to a host group and matches an existing remediation job template, it hands off a plan — including a rollback strategy — to this gate instead of executing it directly. The `notify_users` list determines who gets paged for sign-off; `message` is the exact text shown to reviewers, customizable per workflow. `timeout` bounds how long the workflow waits (1 day is the default shown at the event), and `on_timeout: fail` means an unanswered request fails the workflow rather than auto-approving it — the whole point of the gate is that nothing reaches production without an explicit human decision. Approval routes to `automated_remediation` (st... --- ## Ansible Orchestrator Example: Closing an ITSM Ticket from a Workflow URL: https://www.ansiblebyexample.com/articles/ansible-orchestrator-example-closing-an-itsm-ticket-from-a-workflow Description: Example config for closing a ServiceNow ITSM ticket at the end of an AAP Automation Orchestrator remediation workflow, with a runnable YAML task. Red Hat's upcoming Automation Orchestrator (announced for Q3 2026 at Red Hat Tech Day Netherlands 2026, Bunnik) runs event-driven, AI-assisted remediation on a single governed canvas, but the last mile is still boring and important: closing the ITSM ticket once the fix is verified. Here's a minimal example of the ServiceNow close step as it would appear inside an AAP job template task, plus the config fields that matter. [code example] ## What this does This is the final task in the 5-step Orchestrator pipeline: alert ingestion, EDA rulebook trigger, AI analysis and recommendation, human approval, and automated remediation at scale. The `servicenow.itsm.incident` task runs after the remediation job template reports success, setting the incident to `closed` with a `close_code` and `close_notes` string that documents exactly what changed — host count, batch strategy, and outcome. In the live CVE-2024-6387 demo at the event, this step ran in 2.1 seconds, closing INC0038291 after the rolling patch across 12 hosts completed with all health checks green. In the Orchestrator's actual workflow, ticket creation and closure are triggered by webhooks rather than static playbook vars: an initial ServiceNow webhook (step 3 in the demo) POSTs to the EDA webhook endpoint using an auto-generated API key, and the close call is fired the same way once remediation finishes — no operator has to touch ServiceNow directly. The credentials shown above as env lookups map to whatever credential o... --- ## Ansible Orchestrator Example: Reading a Workflow Execution Timeline URL: https://www.ansiblebyexample.com/articles/ansible-orchestrator-example-reading-a-workflow-execution-timeline Description: Learn how to read an Ansible Automation Orchestrator workflow execution timeline with a real CVE remediation example from Red Hat Tech Day Netherlands 2026. Red Hat's upcoming Automation Orchestrator (announced for Q3 2026) runs task-based and event-based automation on a single governed canvas, built on the upstream Temporal durable-execution engine. Every workflow run produces an execution timeline — a stage-by-stage record of what happened, when, and how long it took — which is the primary artifact you use to prove that "AI acted through AAP" instead of improvising against production. Below is a worked example based on the CVE-2024-6387 ("regresshion" OpenSSH race condition) remediation workflow demoed at Red Hat Tech Day Netherlands 2026 in Bunnik. ## Example: querying a workflow timeline [code example] ## What this does and why The play hits the orchestrator's timeline API for a specific workflow run and prints each stage with its duration and status. In the Bunnik demo, the regresshion remediation workflow produced this exact sequence: alert ingestion (0s), ITSM ticket creation (1.2s), vulnerability analysis (4.8s), human review (38.4s, manual), remediation execution (0.9s), ticket close (2.1s). Adding those up gives under 10 seconds of *automated* compute time — the 38.4s human review is deliberately excluded from that figure because it's a human approval wait, not machine work. That separation matters operationally. The `automated_seconds` fact in the example strips out the `human_review` stage before summing, mirroring how the orchestrator itself reports "automated time" versus wall-clock time. If you're setting SLAs... --- ## Ansible Orchestrator Example: Rolling Remediation Across Multiple Hosts URL: https://www.ansiblebyexample.com/articles/ansible-orchestrator-example-rolling-remediation-across-multiple-hosts Description: See how Step 5 of Red Hat's Automation Orchestrator pipeline runs governed, rolling CVE remediation across hosts with a concrete AAP config example. Red Hat's upcoming Automation Orchestrator (coming Q3 2026) wraps AI-driven investigation and human governance around Ansible Automation Platform (AAP), so that "AI isn't improvising against production infrastructure, it's acting through AAP." The pipeline runs five stages — alerts, event-driven trigger, AI analysis, human approval, and automated remediation — and this example focuses on that last stage: Step 5, where the approved plan actually touches hosts. ## Step 5 config: rolling remediation job template [code example] ## What it does This step definition tells the orchestrator to launch an existing AAP job template — not an ad-hoc script — against the host group the AI agent correlated from inventory during Step 3. `job_slicing` splits the affected fleet into rolling batches instead of a single big-bang push: with 12 hosts across prod, staging, and dev, that's 3 batches of 4. Each batch patches `openssh-server`, restarts `sshd`, and runs a health check before the orchestrator proceeds to the next batch. `max_fail_percentage: 0` means any failed batch halts the rollout immediately rather than continuing to hammer the rest of the fleet — the deterministic, auditable behavior the platform is built around. The `notifications` and `audit` blocks close the loop back into ITSM: the same ServiceNow ticket that triggered the workflow (`INC0038291`) gets updated and closed automatically, with the execution log attached for compliance review. Step 5 only runs after the gover... --- ## Ansible Orchestrator Example: Wiring Splunk and ServiceNow Alert Triggers URL: https://www.ansiblebyexample.com/articles/ansible-orchestrator-example-wiring-splunk-and-servicenow-alert-triggers Description: Configure Event-Driven Ansible webhooks to ingest Splunk and ServiceNow alerts into an Automation Orchestrator rulebook, step 1-2 of the pipeline. Red Hat's Automation Orchestrator (coming Q3 2026) runs a 5-step pipeline that starts with alerts from multiple sources landing on one canvas, then hands them to Event-Driven Ansible for deterministic handling before any AI ever sees them. This example focuses on those first two steps only: getting an external alert into an EDA webhook, and matching it in a rulebook. ## Step 1-2 config: webhook source plus rulebook [code example] ## What this does Step 1 is the `sources` block: a single `ansible.eda.webhook` listener exposes one HTTP endpoint that both the IBM Instana webhook and the ServiceNow webhook POST to, each with its own auto-generated API key passed as the bearer token. That matches the Tech Day Netherlands 2026 demo, where two independent triggers — an infra-monitoring alert and an ITSM-side confirmation — fed the same EDA endpoint rather than requiring separate listeners per tool. Step 2 is the `rules` block. EDA evaluates every inbound payload against plain conditions — no LLM involved yet. This is the "deterministic automation rulebook" Red Hat describes: given `CVE-2024-6387` and `severity: critical` from Instana, it fires the job template that kicks off the CVE-2024-6387 ("regresshion") remediation workflow. A second rule lets the ServiceNow webhook corroborate the same CVE via its own payload shape, correlating the incident number before the workflow proceeds to inventory correlation and, eventually, the AI analysis and human-approval gates further down t... --- ## Ansible Osmotic Power Blue Energy Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/ansible-osmotic-power-blue-energy-infrastructure Description: Automate osmotic power (blue energy) infrastructure with Ansible. Deploy membrane monitoring, salinity gradient optimization, and coastal plant management. ## Introduction Osmotic power (blue energy) generates electricity from the salinity difference between freshwater and seawater. As membrane technology improves, osmotic power plants are becoming commercially viable — offering predictable, 24/7 baseload renewable energy at river-ocean interfaces. These facilities require infrastructure for membrane performance monitoring, water treatment control, grid integration, and multi-site fleet management. Ansible automates the IT/OT systems supporting osmotic power operations. ## Osmotic Power Plant Architecture [code example] ## Membrane Performance Monitoring [code example] ## Water Treatment and Pretreatment [code example] ## Grid Integration [code example] ## Fleet Management [code example] ## Related Articles - Ansible Advanced Nuclear Technology - Ansible Autonomous Industrial Systems - Ansible at Scale - Ansible Structural Battery Manufacturing ## Conclusion Osmotic power is the only renewable energy source that provides continuous baseload power from a predictable, never-ending resource — the salinity difference between rivers and oceans. Ansible automates the infrastructure that makes these plants viable: membrane performance monitoring with fouling prediction, water pretreatment control, grid integration with market optimization, and multi-site fleet management. As membrane technology costs fall and climate pressure grows, osmotic power infrastructure at every major river delta could contribute significantly to... --- ## Ansible osx_defaults Module — Manage macOS System Preferences URL: https://www.ansiblebyexample.com/articles/ansible-osx-defaults-module-manage-macos-system-preferences Description: Read and write macOS defaults (preferences) for apps and system settings. Tested on real machines with clear, copy-paste examples. # Ansible osx_defaults Module — Manage macOS System Preferences ## Introduction The `community.general.osx_defaults` module read and write macOS defaults (preferences) for apps and system settings. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.osx_defaults` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check... --- ## Ansible package_facts — List Installed Packages URL: https://www.ansiblebyexample.com/articles/ansible-package-facts-list-installed-packages Description: Ansible package_facts guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible package_facts — List Installed Packages ## Introduction List Installed Packages. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible package_facts requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selecti... --- ## Ansible pam_limits — Configure System Resource Limits URL: https://www.ansiblebyexample.com/articles/ansible-pam-limits-configure-system-resource-limits Description: Ansible pam_limits guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible pam_limits — Configure System Resource Limits ## Introduction Configure System Resource Limits. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible pam_limits requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible Parse JSON and YAML — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-parse-json-and-yaml-complete-guide Description: Parse JSON and YAML data in Ansible using from_json, from_yaml, and jq-style queries with json_query. Tested, copy-paste examples included. # Ansible Parse JSON and YAML — Complete Guide ## Introduction Parse JSON and YAML data in Ansible using from_json, from_yaml, and jq-style queries with json_query. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use `block/rescue/always` for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked before action | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Parse JSON and YAML data in Ansible using from_json, from_yaml, and jq-style queries with json_query. Use check mode for validation, handle errors gracefully, and always test in a non-production environment first. --- ## Ansible Parse JSON and YAML Data — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-parse-json-and-yaml-data-complete-guide Description: Parse JSON and YAML in Ansible using from_json, from_yaml, json_query. Hands-on, tested examples and best practices for Ansible Parse JSON and YAML Data. # Ansible Parse JSON and YAML Data — Complete Guide ## Introduction Parse JSON and YAML in Ansible using from_json, from_yaml, json_query. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Parse JSON and YAML in Ansible using from_json, from_yaml, json_query. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible parted Module — Manage Disk Partitions URL: https://www.ansiblebyexample.com/articles/ansible-parted-module-manage-disk-partitions Description: Ansible parted Module guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible parted Module — Manage Disk Partitions ## Introduction Manage Disk Partitions. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible parted Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective... --- ## Ansible Partner Certification Checker GitHub Workflow v2.0.0 URL: https://www.ansiblebyexample.com/articles/ansible-partner-certification-checker-github-workflow-v2 Description: The Partner Certification Checker GitHub workflow v2.0.0 automates Ansible collection certification testing. Run Red Hat certification checks in CI/CD. # Ansible Partner Certification Checker GitHub Workflow v2.0.0 ## Introduction Red Hat released version 2.0.0 of the Partner Certification Checker GitHub workflow in May 2026. This reusable GitHub Actions workflow lets collection maintainers run the same certification tests Red Hat uses — directly in their CI/CD pipeline. Catch certification failures early, before submitting to Automation Hub. ## What It Does The certification checker validates your Ansible collection against Red Hat's partner certification requirements: - **Metadata validation** — `galaxy.yml` completeness and correctness - **Documentation checks** — module/plugin documentation standards - **Sanity tests** — `ansible-test sanity` compliance - **License verification** — acceptable open source licenses - **Import checks** — no banned imports or dependencies - **Runtime compatibility** — works with supported ansible-core versions - **Plugin standards** — return values, option documentation, examples ## Quick Start [code example] That's it — one workflow call runs the full certification suite. ## What's New in v2.0.0 | Feature | v1.x | v2.0.0 | |---------|------|--------| | Ansible-core versions tested | 2.15-2.17 | 2.17-2.20 | | Python versions | 3.9-3.11 | 3.10-3.13 | | Parallel test execution | ❌ | ✅ | | Detailed error reports | Basic | Rich markdown summaries | | Custom config support | Limited | Full `.certification.yml` | | Reusable workflow | ❌ | ✅ (uses: syntax) | ## Configuration [code examp... --- ## Ansible Pass Variables Between Plays — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-pass-variables-between-plays-complete-guide Description: Share variables across plays using set_fact, hostvars, and custom facts. Hands-on, tested examples and best practices for Ansible Pass Variables Between Plays. # Ansible Pass Variables Between Plays — Complete Guide ## Introduction Share variables across plays using set_fact, hostvars, and custom facts. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Share variables across plays using set_fact, hostvars, and custom facts. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Patch Management — OS Updates at Scale URL: https://www.ansiblebyexample.com/articles/ansible-patch-management-os-updates-at-scale Description: Ansible Patch Management guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Patch Management — OS Updates at Scale ## Introduction OS Updates at Scale. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Patch Management requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective... --- ## Ansible pause — Wait for User Input or Time Delay URL: https://www.ansiblebyexample.com/articles/ansible-pause-wait-for-user-input-or-time-delay Description: Use ansible.builtin.pause to wait for user confirmation, add time delays, display messages, and control playbook flow with interactive prompts. # Ansible pause — Wait for User Input or Time Delay ## Introduction `ansible.builtin.pause` stops playbook execution to wait — for user confirmation before destructive operations, for a time delay between steps, or for user input that drives subsequent tasks. It's the simplest way to add human gates and timed waits to automation workflows. ## Time-Based Pause [code example] ## User Confirmation [code example] ## Capture User Input [code example] ## Practical Examples ### Rolling Update with Verification [code example] ### Pre-Destructive Confirmation [code example] ### Timed Delay Between Batches [code example] ## Hidden Input (Passwords) [code example] ## pause vs wait_for | Feature | `pause` | `wait_for` | |---------|---------|-----------| | Wait for time | ✅ | ✅ (timeout) | | Wait for port | ❌ | ✅ | | Wait for file | ❌ | ✅ | | User input | ✅ | ❌ | | Runs on | Controller | Remote host | | Use case | Human gates, simple delays | Service/port readiness | ## Troubleshooting | Issue | Solution | |-------|----------| | Pause hangs in CI/CD | Don't use interactive pauses in automation; use `when: not ci_mode` | | `user_input` is empty | User pressed Enter without typing; add validation | | Pause skipped | Check `when` conditions; pause only runs on controller | | Can't use in AWX/Tower | AWX doesn't support interactive pauses; use Survey instead | | Ctrl+C doesn't work | Press Ctrl+C then choose (A)bort or (C)ontinue | ## Best Practices 1. **Skip pauses in ... --- ## Ansible pause Module — ansible.builtin.pause Guide URL: https://www.ansiblebyexample.com/articles/ansible-pause-module-wait-for-user-input-or-time-delay Description: Complete guide to ansible.builtin.pause — add time delays, wait for user input, prompt for confirmation, and control playbook execution flow with examples. ## The ansible.builtin.pause Module The `pause` module stops playbook execution for a set time or until the user presses Enter. Useful for deployment gates, maintenance windows, and interactive playbooks. ## Timed Pause [code example] ## Wait for User Confirmation [code example] ## Prompt for User Input [code example] ## Deployment Gate Pattern [code example] ## Maintenance Window Pattern [code example] ## Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `seconds` | Pause duration in seconds | `30` | | `minutes` | Pause duration in minutes | `5` | | `prompt` | Message to display | `"Press Enter"` | | `echo` | Show typed input (default: true) | `false` | ## Tips - **Ctrl+C then A** aborts the playbook during a pause - **Ctrl+C then C** continues past the pause - `register` captures `user_input` from prompts - Timed pauses and prompts are mutually exclusive - Use `echo: false` for password-like inputs --- *Browse 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible pause Module — Delays & Prompts URL: https://www.ansiblebyexample.com/articles/pause-execution-ansible-module-pause Description: Pause Ansible playbook execution with time delays or prompts. Examples with seconds, minutes, and interactive user input. ## How to pause a playbook execution for a certain amount of time with Ansible? Use Ansible pause (`ansible.builtin.pause`) to pause playbook execution for a set number of seconds or minutes, or until you press a key to continue. ## Ansible pause execution Today we're talking about the Ansible module `pause`. This module is also supported for Windows targets. The full name is `ansible.builtin.pause`, which means that is part of the collection of modules "builtin" with Ansible and shipped with it. The default behavior is to pause with a prompt. Pauses playbook execution for a set amount of time, or until a prompt is acknowledged. ## Parameters - `minutes` string - a positive number of minutes - `seconds` string - a positive number of seconds - `prompt` string - "Text message" - `echo` boolean - yes/no All parameters are optional. The default behavior is to pause with a prompt. You could specify the amount of time using the parameters "`minutes`" and "`seconds`". Starting in Ansible 2.2, if you specify 0 or negative for minutes or seconds, it will wait for 1 second, previously it would wait indefinitely. When minutes or seconds are specified, user input is not captured or echoed, regardless of the echo setting. I'll cover the user input in another video. ## Playbook Let's jump in a real-life Ansible Playbook to pause a playbook execution. ### code - pause.yml [code example] ### output [code example] output with manual continue (CTRL+C and "C") [code example] output... --- ## Ansible pause Module — Wait for Input or Delay URL: https://www.ansiblebyexample.com/articles/ansible-pause-module-wait-for-input-or-delay Description: Use the ansible.builtin.pause module to add delays, prompt for user input, and create confirmation gates in Ansible playbooks with timeout and echo. # Ansible pause Module — Wait for Input or Delay ## Introduction The `ansible.builtin.pause` module pauses playbook execution for a specified time or until the operator provides input. Use it for timed delays between tasks, manual confirmation gates, and interactive prompts during deployment. ## Basic Delay [code example] ## Prompt for User Input [code example] ## Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `minutes` | integer | — | Minutes to pause | | `seconds` | integer | — | Seconds to pause | | `prompt` | string | — | Message to display when waiting for input | | `echo` | boolean | `true` | Show user input on screen (set `false` for passwords) | ## Collect Sensitive Input [code example] ## Deployment Gates [code example] ## Wait for External Process [code example] ## Conditional Pause [code example] ## Timeout on User Input [code example] ## Common Patterns [code example] ## Troubleshooting [code example] ## Related Articles - Ansible wait_for Module — Wait for Conditions - Ansible async and poll — Background Tasks - Ansible Serial — Rolling Updates - Ansible Playbook Execution Order ## Conclusion The `ansible.builtin.pause` module provides timed delays with `seconds`/`minutes` and interactive prompts with `prompt`. Use it for deployment gates, confirmation checkpoints, and timed waits between tasks. Set `echo: false` for password prompts, and combine with `when` for conditiona... --- ## Ansible PCI DSS — Payment Card Industry Compliance URL: https://www.ansiblebyexample.com/articles/ansible-pci-dss-payment-card-industry-compliance Description: Ansible PCI DSS guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible PCI DSS — Payment Card Industry Compliance ## Introduction Payment Card Industry Compliance. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted devia... --- ## Ansible Performance — Speed Up Playbooks and Scale Automation URL: https://www.ansiblebyexample.com/articles/ansible-performance-speed-up-playbooks-scale Description: Optimize Ansible performance with SSH pipelining, fact caching, forks, async tasks, mitogen, and profiling. Cut playbook execution time in half. ## Introduction Ansible playbooks can be slow when managing hundreds of hosts. The good news: a few configuration changes can cut execution time by 50-75%. This guide covers every optimization technique from quick wins to advanced strategies. ## Quick Wins (ansible.cfg) [code example] ### Impact Benchmarks | Optimization | Typical Speedup | |-------------|----------------| | `pipelining = True` | **40-60%** faster | | `forks = 50` (from 5) | **5-10x** faster on many hosts | | `gathering = smart` | **20-30%** faster (cached facts) | | `ControlPersist=600s` | **10-20%** faster (reuse SSH) | | Disable `gather_facts` | **2-5s** saved per play | ## SSH Pipelining The single biggest improvement. Reduces SSH operations from 5+ per task to 1: [code example] **Requirement**: `requiretty` must be disabled in `/etc/sudoers`: [code example] ## Fact Caching Don't gather facts every run: [code example] Or skip facts entirely when not needed: [code example] ## Optimize Task Design ### Combine Package Installs [code example] ### Use async for Long Tasks [code example] ### Use free Strategy [code example] ## Profile Tasks Find what's slow: [code example] Output: [code example] ## Reduce SSH Round-Trips ### Use Modules Over command/shell [code example] ### Batch template/copy Operations [code example] ## Mitogen (Advanced) Mitogen replaces Ansible's SSH-based execution with an optimized connection strategy — 2-7x faster: [code example] [code example] ⚠️ Chec... --- ## Ansible Performance Tuning — SSH Pipelining and Mitogen URL: https://www.ansiblebyexample.com/articles/ansible-performance-tuning-ssh-pipelining-and-mitogen Description: Ansible Performance Tuning guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Performance Tuning — SSH Pipelining and Mitogen ## Introduction SSH Pipelining and Mitogen. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Performance Tuning requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ta... --- ## Ansible Permission Denied Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-permission-denied-error-fix-and-solutions Description: Fix Ansible permission denied errors from SSH keys, sudo, become, and file access issues. Tested, copy-paste examples included. # Ansible Permission Denied Error — Fix and Solutions ## Introduction Fix Ansible permission denied errors from SSH keys, sudo, become, and file access issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix Ansible permission denied errors from SSH keys, sudo, become, and file access issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible ping Module - Test SSH Connectivity URL: https://www.ansiblebyexample.com/articles/ansible-ping-module-test-connectivity Description: ansible ping tests SSH connectivity and Python availability. Learn ad-hoc commands, playbook syntax, troubleshooting, Windows win_ping, and examples. ## Introduction `ansible.builtin.ping` is the first command you run with Ansible — it verifies that the control node can connect to remote hosts, that SSH (or WinRM) works, and that Python is available. It does **not** send ICMP pings. It's a full Ansible module test. For an ad-hoc connectivity check, run `ansible all -m ping`; a successful host returns `"ping": "pong"`, which means Ansible could connect and execute the module. ## Basic Usage [code example] ## What ping Actually Tests [code example] **Not tested**: ICMP ping, network connectivity, port availability. For ICMP, use `ansible.builtin.command: ping -c 1 hostname`. ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `data` | `pong` | Data to return (instead of "pong") | [code example] ## In a Playbook [code example] ## Windows — win_ping [code example] [code example] ## Troubleshooting ### "UNREACHABLE!" — SSH Connection Failed [code example] ### "MODULE FAILURE" — Python Not Found [code example] [code example] ### "Permission denied" [code example] ### Host Key Verification Failed [code example] Or: [code example] ## Common Patterns ### Connectivity Check Before Deploy [code example] ### Check Specific Hosts [code example] ### Health Dashboard [code example] ## ping vs Other Connectivity Tests | Tool | Tests | Protocol | |------|-------|----------| | `ansible.builtin.ping` | SSH + Python + module exec | SSH | | `ICMP ping` | Network reacha... --- ## Ansible ping Module — Test Host Connectivity and Python URL: https://www.ansiblebyexample.com/articles/ansible-ping-module-test-host-connectivity Description: Use the Ansible ping module to test connectivity to remote hosts and verify Python is working. Troubleshoot SSH, WinRM, and connection issues with. ## Introduction `ansible.builtin.ping` is the simplest Ansible module — it connects to a remote host, verifies Python is working, and returns `pong`. It's the first thing to run when setting up Ansible or troubleshooting connectivity. Despite the name, it's **not** an ICMP ping — it tests the full Ansible connection stack (SSH + Python). ## Basic Usage [code example] ### Successful Output [code example] ### Failed Output [code example] ## What ping Actually Tests [code example] A successful ping confirms: 1. ✅ Network connectivity to the host 2. ✅ SSH (or WinRM) authentication works 3. ✅ Python is installed and functional on the remote 4. ✅ The Ansible user has permission to execute commands 5. ✅ The temporary directory is writable ## In a Playbook [code example] ## Ping Before Deployment [code example] ## Windows Hosts: win_ping For Windows hosts using WinRM or PSRP, use `ansible.windows.win_ping`: [code example] [code example] ### win_ping vs ping | Module | Connection | Tests | |--------|-----------|-------| | `ansible.builtin.ping` | SSH | SSH + Python | | `ansible.windows.win_ping` | WinRM/PSRP | WinRM + PowerShell | [code example] ## Troubleshooting Connection Failures ### "UNREACHABLE" — SSH Can't Connect [code example] Common causes: - Host is down or firewall blocks port 22 - Wrong IP address or hostname in inventory - SSH key not accepted ### "Permission denied" [code example] ### "MODULE FAILURE" — Python Issue [code example] Fix: Inst... --- ## Ansible Ping Module: Test Host Connectivity and Python Availability URL: https://www.ansiblebyexample.com/articles/test-host-availability-ansible-module-ping Description: Complete guide to the Ansible ping module (ansible.builtin.ping). Learn how to test SSH connectivity, verify Python on managed hosts, and troubleshoot. The `ansible.builtin.ping` module is the first command every Ansible user runs. It verifies that Ansible can connect to a managed host via SSH and that a usable Python interpreter exists on the remote system. Despite its name, it has nothing to do with ICMP network pings. ## What Does Ansible Ping Actually Do? The `ansible.builtin.ping` module performs three checks: 1. **SSH connectivity** — Can Ansible establish an SSH session to the host? 2. **Python availability** — Is there a Python interpreter on the remote host? 3. **Module execution** — Can Ansible execute a simple module and return results? If all three succeed, you get `"pong"`. If any fail, you get an error message explaining what went wrong. ### Ansible Ping vs Network Ping | Feature | `ansible.builtin.ping` | `ping` (ICMP) | |---------|----------------------|---------------| | Protocol | SSH (port 22) | ICMP | | Tests Python | ✅ Yes | ❌ No | | Tests SSH auth | ✅ Yes | ❌ No | | Tests module execution | ✅ Yes | ❌ No | | Requires Ansible | ✅ Yes | ❌ No | | Root required | ❌ No | Sometimes | **A host can respond to ICMP ping but fail `ansible.builtin.ping`** if SSH is not configured, the user doesn't have access, or Python isn't installed. ## Basic Usage ### Ad-Hoc Command [code example] ### Successful Output [code example] ### In a Playbook [code example] Setting `gather_facts: false` speeds up the ping test by skipping the `setup` module. ## Parameters | Parameter | Type | Default | Description | |-... --- ## Ansible pip — Manage Python Packages URL: https://www.ansiblebyexample.com/articles/ansible-pip-module-manage-python-packages Description: Use the Ansible pip module to install, update, and remove Python packages. Virtual environments, requirements files, and version pinning for Python. ## Introduction `ansible.builtin.pip` installs Python packages from PyPI, Git repos, or local files. It supports virtual environments, requirements files, and version pinning — everything you need to manage Python dependencies on remote hosts. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | — | Package name(s) with optional version | | `requirements` | — | Path to requirements.txt | | `state` | `present` | `present`, `absent`, `latest`, `forcereinstall` | | `virtualenv` | — | Virtual environment path | | `virtualenv_command` | `virtualenv` | Command to create venv (`python3 -m venv`) | | `virtualenv_python` | — | Python interpreter for venv | | `executable` | — | pip executable path (`pip3`) | | `extra_args` | — | Extra arguments for pip | | `editable` | `false` | Install in editable mode (`-e`) | | `chdir` | — | Change to directory before running | | `umask` | — | umask for install command | ## Virtual Environments [code example] ## Requirements Files [code example] ## Remove Packages [code example] ## Practical Patterns ### Application Deployment [code example] ### Install from Git [code example] ### Use pip3 Explicitly [code example] ### Extra pip Arguments [code example] ## Troubleshooting ### "pip not found" [code example] ### "Permission denied" with System pip Use virtualenv or `--user`: [code example] ### Externally Managed Environment (PEP 668) On newer syst... --- ## Ansible pip_package_info Module — Get Installed pip Package Info URL: https://www.ansiblebyexample.com/articles/ansible-pip-package-info-module-get-installed-pip-package-info Description: Query information about installed Python pip packages on remote hosts. Hands-on, tested examples and best practices for Ansible pip_package_info Module. # Ansible pip_package_info Module — Get Installed pip Package Info ## Introduction The `community.general.pip_package_info` module query information about installed Python pip packages on remote hosts. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.pip_package_info` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test ... --- ## Ansible pkgng Module — Manage FreeBSD Packages URL: https://www.ansiblebyexample.com/articles/ansible-pkgng-module-manage-freebsd-packages Description: Install, remove, and manage packages on FreeBSD using pkg with Ansible. Hands-on, tested examples and best practices for Ansible pkgng Module. # Ansible pkgng Module — Manage FreeBSD Packages ## Introduction The `community.general.pkgng` module install, remove, and manage packages on FreeBSD using pkg with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.pkgng` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` be... --- ## Ansible Playbook — Write Your First Automation Script URL: https://www.ansiblebyexample.com/articles/ansible-playbook-write-first-automation Description: Write Ansible playbooks from scratch. YAML syntax, plays, tasks, variables, handlers, and a complete multi-play example. Beginner guide with best. ## Introduction An Ansible playbook is a YAML file that defines automation tasks — install packages, deploy configs, restart services, create users. It's the core of Ansible: you describe **what** you want (desired state), and Ansible figures out **how** to get there. ## Minimal Playbook [code example] Run it: [code example] ## Anatomy of a Playbook [code example] ## Key Components | Component | Purpose | |-----------|---------| | `name` | Description (shows in output) | | `hosts` | Target hosts/groups from inventory | | `become` | Privilege escalation (sudo) | | `vars` | Variables for this play | | `tasks` | Ordered list of actions | | `handlers` | Tasks triggered by `notify` | | `roles` | Include reusable role packages | | `gather_facts` | Collect host info (default: true) | ## Variables [code example] ## Complete Example: Web Server Setup [code example] ## Run a Playbook [code example] ## Tags Run only specific tasks: [code example] [code example] ## Multi-Play Playbook [code example] ## Error Handling [code example] ## Best Practices 1. **Name every task** — clear names make output readable and debugging easy 2. **Use FQCN** — `ansible.builtin.apt` not just `apt` 3. **Use `become` at play level** — not on every task 4. **Keep playbooks small** — use roles for reusable components 5. **Use `--check` first** — dry run before applying changes 6. **Use handlers** — don't restart services unconditionally 7. **Use variables** — never hardcode values that ... --- ## Ansible Playbook Best Practices — Clean, Maintainable Automation URL: https://www.ansiblebyexample.com/articles/ansible-best-practices-clean-maintainable-automation Description: Follow Ansible best practices for clean, maintainable playbooks. Learn naming conventions, directory structure, idempotency, testing, and production. ## Introduction Well-structured Ansible projects are easier to debug, review, and hand off. Poorly structured ones become unmaintainable fast. This guide covers the practices that matter most — from directory layout to naming to testing — based on real production experience. ## Directory Structure [code example] ## Naming Conventions ### Task Names [code example] ### Use FQCN (Fully Qualified Collection Name) [code example] ### Variables [code example] ## Idempotency [code example] ## Security [code example] ## Error Handling [code example] ## Performance [code example] ## Testing [code example] ### ansible-lint Configuration [code example] ## Documentation [code example] ## Checklist - [ ] Every task has a descriptive `name:` - [ ] All modules use FQCN - [ ] Variables are prefixed (role or app name) - [ ] Secrets are vault-encrypted - [ ] `changed_when` on all command/shell tasks - [ ] `no_log: true` on sensitive tasks - [ ] `validate` on config file deployments - [ ] Handlers for service restarts (not inline restarts) - [ ] `requirements.yml` pins collection versions - [ ] `ansible-lint` passes - [ ] `--check --diff` produces sensible output ## Related Articles - Ansible Roles Guide - Ansible roles vs collections - Ansible check mode vs diff mode - Ansible ansible-lint Guide ## Conclusion Good Ansible projects follow simple principles: name everything, use FQCN, keep it idempotent, encrypt secrets, validate configs, and test before applying. Th... --- ## Ansible Playbook Example: After-Hours Access Report for Branch Offices URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-after-hours-access-report-for-branch-offices Description: Runnable Ansible playbook example for a Branch - After Hours Access Report template, as demoed in AAP 2.7's Automation Portal self-service gallery. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7 — a self-service template gallery where every template has a one-click "Start" button. One of the branch-office templates shown live was **Branch - After Hours Access Report**, which generates a report of access events that occurred outside normal operating hours. Below is a runnable playbook that implements that use case. ## Playbook [code example] ## What it does The play targets a `branch_access_controllers` group — one host per branch badge/door controller, or a jump host that can query them. It exports the day's access log as JSON via a `badge-access-cli` call (a stand-in for whatever access-control vendor CLI or API a given branch runs), then uses `selectattr` to keep only events whose local timestamp falls before `business_hours_start` or after `business_hours_end`. The filtered list is written to a per-host JSON report and a one-line summary is printed for the console or job log. This is exactly the kind of job the Automation Portal's self-service gallery is built for: a branch manager or security analyst clicks **Start** on "Branch - After Hours Access Report," the underlying job template runs against the correct inventory, and the operator never has to know which repo the playbook lives in, which credentials it uses, or how the time-window logic works. The portal handles the surveys and credential injection; the playbook stays a normal,... --- ## Ansible Playbook Example: Automated Branch Network Health Check URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-automated-branch-network-health-check Description: Runnable Ansible playbook example modeling AAP 2.7's Branch - Network Health Check template for automated branch-wide network diagnostics. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7, a self-service template gallery where operators click "Start" without needing to know where a playbook lives or how to configure it. One of the branch-office templates shown was **Branch - Network Health Check**, which runs a general health check across an entire branch. Below is a runnable playbook that models what such a template executes behind that button. ## Example Playbook [code example] ## What It Does The play targets a `branch_network` inventory group covering everything at a site — switches, routers, access points, and firewalls grouped together. It first confirms reachability with `wait_for_connection`, then pulls facts and CPU, interface error, and uplink status via `ansible.netcommon` modules, which work across supported network platforms without needing a vendor-specific collection for basic CLI checks. Results are assembled into a per-host summary, flagged if problems are found, and written locally as a YAML report. In the Automation Portal demo, this logic sits behind a job template with a survey (branch name or site ID) and a single "Start" button — the operator never touches an inventory file or credential. The template gallery pattern from AAP 2.7 exists precisely so that non-Ansible-experts (NOC staff, branch IT) can trigger this without knowing it's a playbook at all. ## Notes / Gotchas - Replace `ansible.netcommon.cli_co... --- ## Ansible Playbook Example: Backup Cisco and Arista Switch Configs to Git URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-backup-cisco-and-arista-switch-configs-to-git Description: Runnable Ansible playbook example that backs up Cisco and Arista running configs to Git, matching AAP 2.7's Network - Backup Switch Configs template. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7, a self-service template gallery where operators click "Start" without touching the underlying playbook. One of the templates shown was **Network - Backup Switch Configs**, which pulls running configs from Cisco and Arista switches and commits them to Git. Here's a runnable version of that playbook. ## Playbook [code example] ## What it does The first play targets a `network_switches` group and runs vendor-specific config modules — `cisco.ios.ios_config` for IOS devices and `arista.eos.eos_config` for EOS devices — gated by the `ansible_network_os` inventory variable. Each module's `backup_options` writes the running-config to a per-host file. A `lineinfile` task stamps the file with a backup timestamp for auditability. The second play runs on `localhost` and treats the backup directory as a Git working copy: it stages any changed files, commits only if something actually changed (avoiding empty commits), and pushes to the remote. This is exactly the kind of two-stage flow — fetch-from-device, then commit-to-git — that a self-service template like **Network - Backup Switch Configs** wraps behind a single "Start" button in AAP 2.7's Automation Portal, so an operator doesn't need to know which collections or credentials are involved. ## Notes / Gotchas - Requires the `cisco.ios` and `arista.eos` collections installed on the execution environment,... --- ## Ansible Playbook Example: Create an S3 Bucket with Encryption URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-create-an-s3-bucket-with-encryption Description: Runnable Ansible playbook example for creating an encrypted, compliant S3 bucket, based on the AAP 2.7 Automation Portal 'Cloud - Create S3 Bucket' template. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7 — a self-service template gallery where operators click "Start" without knowing where a playbook lives or how it's configured. One of the catalog entries was **Cloud - Create S3 Bucket**, described as creating a compliant S3 bucket with encryption. Here's a runnable playbook that matches that job. ## Example playbook [code example] ## What it does The playbook builds an S3 bucket in four idempotent steps: create the bucket with baseline tags, turn on default server-side encryption using a KMS key, lock down every public-access setting, and enable versioning. Each task targets the `amazon.aws.s3_bucket` module and can be re-run safely — running it twice won't recreate the bucket or fail, it just confirms the desired state. This is exactly the shape of job the Automation Portal template wraps: a platform team pre-builds and tests the playbook, sets survey fields for `bucket_name`, `bucket_region`, and tags, and publishes it as "Cloud - Create S3 Bucket." A developer or app owner then clicks Start, fills in a short form, and gets a compliant bucket without ever opening a YAML file or knowing which controller node the job runs from. Splitting encryption, public-access blocking, and versioning into separate tasks (rather than one giant module call) makes the playbook easier to read in job output and easier to extend — for example, adding a lifecycle ... --- ## Ansible Playbook Example: Emergency CVE Patch Rollout URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-emergency-cve-patch-rollout Description: Runnable Ansible playbook for emergency CVE patching, modeled on the AAP 2.7 Automation Portal CVE Patch template from Red Hat Tech Day 2026. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new AAP 2.7 Automation Portal, a self-service template gallery where operators hit "Start" without knowing where a playbook lives or how it's configured. One catalog entry, **CVE Patch**, runs a patch for a given CVE. Here's a runnable playbook that models what that template kicks off. ## Example playbook: cve-patch-rollout.yml [code example] ## What it does The play targets a `patch_targets` group (or whatever inventory group the Automation Portal template passes in) and rolls out in batches — `serial: 20%` by default — so a bad patch doesn't hit the whole fleet at once. It confirms the vulnerable package is actually present before touching anything, updates it to the latest (or a pinned fixed) version via the correct package manager for the OS family, restarts the affected service only when the package actually changed, and reports the resulting version for audit purposes. This maps directly to how a gallery template is meant to work: `cve_id`, `package_name`, and `fixed_version` are the kind of extra_vars a self-service form would collect from the operator, while the underlying playbook stays generic enough to run against any CVE that boils down to "update this package." ## Notes / Gotchas - `max_fail_percentage: 10` stops the rollout if too many hosts fail mid-batch — tune this for your risk tolerance during an active exploit window. - The `assert` task turns "package not ... --- ## Ansible Playbook Example: Firewall Rule Request Approval Workflow URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-firewall-rule-request-approval-workflow Description: Runnable Ansible playbook example for a firewall rule request approval workflow, modeled on AAP 2.7's Network - Firewall Rule Request template. At Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026), Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in Ansible Automation Platform 2.7 — a self-service template gallery where operators hit "Start" without knowing where a playbook lives or how it's configured. One catalog entry, **Network - Firewall Rule Request**, submits a firewall rule change for an approval workflow instead of applying it directly. Here's a runnable playbook that mirrors that pattern. ## Example playbook [code example] ## What it does and why The play never touches the firewall until a human (or an automated approval gate) signs off. It builds a structured change request from the requested rule, `POST`s it to an approval workflow endpoint, then polls the request status with `until`/`retries` rather than blocking indefinitely. Only when `decision.json.status == 'approved'` does the play push the rule to the device with `cisco.asa.asa_config`; a rejected request just gets logged, so nothing is silently discarded. This is exactly the separation the Automation Portal template relies on: the operator clicks "Start", the job template handles submission and polling, and the actual privileged configuration task is gated behind approval — you don't need job template survey knowledge or credential details to request a change, only permission to run the template. ## Notes / Gotchas - **Swap the `uri` calls for real integrations.** The example uses a generic REST endpoint; in product... --- ## Ansible Playbook Example: Provision an EC2 Instance with Standard Tags URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-provision-an-ec2-instance-with-standard-tags Description: Runnable Ansible playbook example for AAP 2.7's 'Cloud - Provision AWS EC2 Instance' template, spinning up an EC2 instance with standard tagging. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7, a self-service template gallery where every job template gets a one-click "Start" button. One of the templates shown in the catalog was "Cloud - Provision AWS EC2 Instance", described as spinning up an EC2 instance with standard tagging. Here's a runnable playbook that matches what that template would launch behind the button. [code example] ## What this does The `amazon.aws.ec2_instance` task launches a single instance from a given AMI into an existing subnet and security group, then waits for it to reach the `running` state. The `tags` block is the point of the exercise: `Name`, `Environment`, `Owner`, and `CostCenter` are the kind of standard tags a platform team enforces across every cloud request, and `ManagedBy`/`Template` make it obvious in the AWS console that the resource came from an AAP job rather than a manual click-through. In the Automation Portal, `environment_tag`, `owner_email`, and `cost_center` are exactly the kind of fields a survey would collect from the requester before the job runs, so the operator starting the template from the gallery never has to touch the YAML or know where the playbook lives. ## Notes / Gotchas - Requires the `amazon.aws` collection and `boto3`/`botocore` on the execution node or execution environment. - Credentials should come from an AAP-managed AWS credential type, not hardcoded keys in the playboo... --- ## Ansible Playbook Example: Remediate a Firewall Rule Misconfiguration URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-remediate-a-firewall-rule-misconfiguration Description: Runnable Ansible playbook example for the AAP 2.7 Network - Firewall Remediation template that detects and corrects a misconfigured firewall rule. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new AAP 2.7 Automation Portal, a self-service template gallery where every playbook has a one-click "Start" button. One of the templates shown, "Network - Firewall Remediation," corrects a firewall misconfiguration without the operator needing to know where the playbook lives. Here's a runnable example of what that template can look like under the hood. ## Example playbook [code example] ## What it does The play targets a `firewalls` inventory group and pulls the running configuration with `asa_facts` (swap in the collection matching your platform — `cisco.ios`, `arista.eos`, or a vendor-specific Ansible Content Collection). It compares the live rule set against `expected_rule`, a single source of truth for what "correct" looks like. If the rule is missing or its action drifted (for example, someone flipped a deny to a permit), `asa_config` pushes the corrected line and saves it. Every remediation gets a line in a local audit log before the play reports back. This mirrors how the Automation Portal template works: the operator clicks "Start," picks a target device or zone from a form, and AAP runs this logic behind the scenes — no manual login to the firewall, no memorizing vendor CLI syntax. ## Notes - Replace `cisco.asa.*` modules with the collection appropriate to your firewall vendor; the compliance-check-then-remediate pattern stays the same regardless of platform. - Keep ... --- ## Ansible Playbook Example: Request an Azure Resource Group with RBAC URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-request-an-azure-resource-group-with-rbac Description: Runnable Ansible playbook example for provisioning an Azure resource group with RBAC role assignments, based on the AAP 2.7 self-service template gallery. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7, a self-service template gallery where operators click "Start" without knowing where a playbook lives or how it's configured. One catalog entry, "Cloud - Request Azure Resource Group," provisions an Azure resource group with appropriate RBAC. Here's a runnable playbook that models what that template does. ## Playbook [code example] ## What it does The playbook takes two inputs a requester would normally supply through the Automation Portal's form-based survey: a resource group name/location/tags, and a list of RBAC assignments (who gets which role). It runs in two steps: 1. `azure_rm_resourcegroup` creates the resource group if it doesn't exist, and is idempotent — re-running the playbook against an existing group only reconciles tags and location, it won't fail or duplicate anything. 2. `azure_rm_roleassignment` loops over `rbac_assignments` and grants each principal (a user, group, or service principal object ID) the requested built-in role, scoped to the resource group's resource ID returned by the first task. This mirrors the point of the "Cloud - Request Azure Resource Group" template shown in the demo: the requester never edits YAML or touches credentials directly — they fill in a short form, and the underlying job template (built from a playbook like this one) does the provisioning and access wiring behind a single "Start" button. ## Not... --- ## Ansible Playbook Example: Reset WiFi on Branch Access Points URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-reset-wifi-on-branch-access-points Description: Runnable Ansible playbook example for resetting WiFi on branch access points, modeled on the AAP 2.7 Branch - WiFi Reset self-service template. Branch offices generate a steady trickle of "the WiFi is down again" tickets, and most of them are fixed by a clean radio reset on the access points. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the AAP 2.7 Automation Portal's self-service template gallery, where a **Branch - WiFi Reset** template lets a non-technical operator click "Start" without knowing which playbook runs or how it's wired up. Here's a runnable playbook that models what that template kicks off. ## Example playbook [code example] ## What it does The `branch_access_points` group targets every AP at a given site (defined in inventory, grouped per branch). The playbook captures radio status before touching anything, disables all WiFi radios, pauses for `reset_delay_seconds` so client sessions and DHCP leases fully drop, then re-enables the radios and checks that they came back `up`. The final `debug` task leaves a human-readable line in the job output — useful when the job was launched from the Automation Portal gallery rather than the CLI, since the person who clicked "Start" may never open a playbook file. This is exactly the shape of job the Branch - WiFi Reset template is built to run: a short, self-contained, idempotent-in-spirit task that a branch manager or help desk agent can trigger without SSH access, without knowing the AP vendor's CLI syntax, and without waiting on a network engineer. The Automation Portal's job template layer supplies the survey (... --- ## Ansible Playbook Example: RHEL Patching in a Maintenance Window URL: https://www.ansiblebyexample.com/articles/ansible-playbook-example-rhel-patching-in-a-maintenance-window Description: Runnable Ansible playbook example for the RHEL - Patch Servers (Maintenance Window) template, applying security patches with dnf and a controlled reboot. At Red Hat Tech Day Netherlands 2026 in Bunnik, Fred van Zwieten and Ismail Dhaoui demoed the new Automation Portal in AAP 2.7, a self-service template gallery where operators click "Start" without knowing where a playbook lives or how it's configured. One of the templates in the demo catalog was "RHEL - Patch Servers (Maintenance Window)": apply the latest security patches to a host group during a scheduled window. Here's a runnable playbook that implements that same behavior. [code example] ## What it does The play targets a `rhel_servers` group and runs `serial: 1` so hosts are patched one at a time — a reasonable default for a maintenance window where you want to catch a failure before it spreads across the fleet. It first asserts the play is running inside the approved time range, then refreshes the `dnf` cache and installs security updates with `ansible.builtin.dnf` using `security: true`, which limits `state: latest` to packages with security advisories rather than a blanket full upgrade. If a reboot marker exists, it reboots with `ansible.builtin.reboot` and waits for the host to come back before moving on. This maps directly to what a launched Automation Portal template does behind the scenes: the operator clicks "Start," AAP passes in the target group and any prompted survey variables (like `reboot_if_needed`), and the underlying job template runs a playbook like this one against the inventory tied to that template. ## Notes / Gotchas - `security: true` on the... --- ## Ansible Playbook Structure — Project Layout Best Practices URL: https://www.ansiblebyexample.com/articles/ansible-playbook-structure-project-layout-best-practices Description: Organize Ansible projects with the recommended directory structure. Roles, inventories, group_vars, host_vars, and playbook layout for maintainable. # Ansible Playbook Structure — Project Layout Best Practices ## Introduction A well-organized Ansible project is the difference between maintainable automation and spaghetti YAML. This guide covers the recommended directory structure from single playbooks to enterprise-scale projects with multiple environments, roles, and collections. ## Minimal Project [code example] [code example] [code example] ## Standard Project Layout [code example] ## Inventory Organization ### Single Environment [code example] ### Multi-Environment [code example] [code example] ## Group Variables [code example] ### Encrypted Variables [code example] [code example] ## Playbook Organization ### Master Playbook (site.yml) [code example] ### Per-Group Playbooks [code example] ### Task-Specific Playbooks [code example] ## Role Structure [code example] [code example] [code example] ## Collections Requirements [code example] [code example] ## Enterprise Layout [code example] ## Makefile for Common Commands [code example] ## .gitignore [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Role not found | Check `roles_path` in `ansible.cfg` | | Variable not defined | Check precedence: defaults < group_vars < host_vars < playbook | | Wrong inventory | Verify with `ansible-inventory -i inventory/prod/ --list` | | Vault password | Use `--vault-password-file` or `ANSIBLE_VAULT_PASSWORD_FILE` | ## Best Practices 1. **One role per concern** — `nginx... --- ## Ansible playbook_dir — Magic Variable for Relative Paths URL: https://www.ansiblebyexample.com/articles/ansible-playbook-dir-magic-variable-for-relative-paths Description: Use playbook_dir magic variable to reference files relative to your playbook location. Build portable roles, templates, and includes with absolute paths. # Ansible playbook_dir — Magic Variable for Relative Paths ## Introduction `playbook_dir` is an Ansible magic variable that contains the absolute path to the directory where the currently running playbook is located. It's essential for building portable automation that references files, templates, and includes using paths relative to the playbook — regardless of where `ansible-playbook` is executed from. ## Quick Reference [code example] ## How It Works [code example] [code example] ## Common Use Cases ### Reference Files Relative to Playbook [code example] ### Load Templates from Custom Location [code example] ### Dynamic Includes [code example] ### Build Paths for Scripts [code example] ## playbook_dir vs Other Path Variables | Variable | Value | Use When | |----------|-------|----------| | `playbook_dir` | Directory of the playbook | Referencing files relative to playbook | | `role_path` | Directory of the current role | Inside roles, for role-local files | | `inventory_dir` | Directory of the inventory file | Referencing inventory-relative files | | `ansible_config_file` | Path to ansible.cfg | Rarely needed directly | [code example] ## With import_playbook and include_playbook [code example] ## Practical Examples ### Multi-Environment Deployment [code example] ### Portable Role with Local Files [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | `playbook_dir` is empty | Bug in very old Ansible | Upgrade to 2.9+... --- ## Ansible playbook_dir Magic Variable URL: https://www.ansiblebyexample.com/articles/current-ansible-playbook-path-playbook-dir-magic-variable-ansible-tip-and-tricks Description: Use Ansible playbook_dir to get the playbook directory path. Reference templates, files, and vars relative to your playbook location with examples. ## Introduction When building Ansible playbooks that reference local files — templates, scripts, variable files, or custom modules — you need a reliable way to construct file paths that work regardless of where `ansible-playbook` is invoked from. The `playbook_dir` magic variable provides exactly this: the absolute filesystem path to the directory containing the playbook being executed. This article covers `playbook_dir` usage, all related magic variables, practical patterns for portable path construction, and common pitfalls. ## What Is playbook_dir? `playbook_dir` is a **magic variable** (also called a special variable) that Ansible sets automatically. It contains the absolute path to the directory of the playbook that was passed to the `ansible-playbook` command. [code example] Key characteristics: - **Always available** — no need to enable `gather_facts` - **Set by Ansible itself** — cannot be overridden in inventory or vars - **Absolute path** — always a full filesystem path - **Directory only** — does not include the playbook filename ## Basic Usage [code example] ### Execution [code example] ## Practical Use Cases ### 1. Reference Local Files Portably [code example] Without `playbook_dir`, the path would break if you `cd` to a different directory before running the playbook. ### 2. Dynamic Variable File Includes [code example] ### 3. Reference Templates Outside roles/ [code example] ### 4. Store Output Files Relative to Playbook [code example] ### ... --- ## Ansible Playbook: Windows Backup — win_copy & win_robocopy URL: https://www.ansiblebyexample.com/articles/ansible-backup-windows-win-copy-win-robocopy Description: Use Ansible to backup Windows 10, 11, 2019, and 2022 systems. Automate file backups with win_copy, win_robocopy, and scheduled backup playbooks. ## Introduction An Ansible playbook can back up Windows 10, 11, Server 2019, and Server 2022 using the `win_copy` and `win_robocopy` modules, plus PowerShell commands for archives, system state, and SQL Server. Back up user documents, application data, registry keys, and system state — see the complete backup playbook below for a ready-to-run example. ### Which Ansible module should you use for Windows 10, 11, 2019, and 2022 backups? For Windows 10 and Windows 11 workstations, start with `ansible.windows.win_copy` for small profile or configuration backups. For Windows Server 2019 and 2022, use `community.windows.win_robocopy` when you need faster directory mirroring, retries, excludes, and scheduled backup jobs. ## win_copy — Simple File Backup [code example] ## win_robocopy — Enterprise File Backup `community.windows.win_robocopy` is the best choice for large backups — it handles retries, excludes, and mirrors: [code example] ## Backup with PowerShell [code example] ## Windows System State Backup [code example] ## Registry Backup [code example] ## SQL Server Backup [code example] ## Complete Backup Playbook [code example] ## Scheduled Backups [code example] ## Troubleshooting ### "Access Denied" on Backup [code example] ### Robocopy Exit Codes Robocopy returns non-zero on success — codes 0-7 are all OK: [code example] ## Related Articles - Ansible Windows Guide - Ansible cron Module - Ansible copy Module - Ansible Playbook Guide ## Conclusion F... --- ## Ansible Playground: Practice Ansible Online for Free URL: https://www.ansiblebyexample.com/articles/ansible-playground-practice-ansible-online-for-free Description: Try Ansible online with our free playground at app.ansiblebyexample.com. Write and run playbooks directly in your browser — no installation required.. ## What is the Ansible Playground? The **Ansible Playground** at app.ansiblebyexample.com is a free, browser-based environment where you can write and run Ansible playbooks without installing anything on your machine. Whether you're a complete beginner or an experienced engineer testing a quick idea, the playground lets you: - **Write playbooks** in a full-featured code editor - **Run them instantly** against a sandboxed environment - **See real output** — just like running `ansible-playbook` locally - **Share your work** with colleagues or students ## Why Use an Ansible Playground? ### No Installation Required Setting up Ansible locally means installing Python, pip, configuring SSH keys, and managing virtual environments. The playground skips all of that — open your browser and start writing YAML. ### Safe to Experiment Running playbooks against production hosts can be risky. The playground provides an isolated sandbox where mistakes are harmless and learning is fast. ### Perfect for Learning If you're following tutorials on AnsibleByExample, you can immediately test the examples in the playground. ## Getting Started 1. Go to app.ansiblebyexample.com 2. Write your playbook in the editor 3. Click **Run** to execute 4. Review the output ### Example: Your First Playbook [code example] ## What Can You Do in the Playground? | Feature | Supported | |---------|-----------| | Run playbooks against localhost | ✅ | | Use built-in modules (debug, copy, file, template, e... --- ## Ansible Podman — Apache HTTPD Deploy URL: https://www.ansiblebyexample.com/articles/deploy-apache-web-server-in-a-podman-container-for-redhat-like-systems-ansible-modules-podman-image-and-podman-container2 Description: Automate the deployment of Apache HTTPD in a Podman container using Ansible. Set up web root, custom index.html, and manage container settings. ## How to Setup Apache Web Server in a Podman Container for RedHat-like systems with Ansible? ## Setup Apache Web Server in a Podman Container for RedHat-like systems - install packages => `ansible.builtin.yum` - custom index.html => `ansible.builtin.copy` - pull image => `containers.podman.podman_image` - run container => `containers.podman.podman_container` Today we’re talking about how to Deploy a web server apache httpd in a Podman Container for RedHat-like Linux systems. The full process requires four steps that you could automate with different Ansible modules. Firstly you need to verify that `podman` and it dependency is successfully installed on the target system using the `ansible.builtin.yum` Ansible module. Secondly, you need to create the custom index.html with `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Thirdly, you need to pull the image for the container hub registry using the `containers.podman.podman_image` Ansible module. Finally, you could run the `webserver` container setting the right port and settings using the `containers.podman.podman_container` Ansible module. ## Links - containers.podman.podman_image - containers.podman.podman_container - httpd image ## Playbook How to Setup Apache Web Server in a Podman Container for RedHat-like systems with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### ... --- ## Ansible Podman — Rootless Containers Without Docker URL: https://www.ansiblebyexample.com/articles/ansible-podman-rootless-containers-without-docker Description: Ansible Podman guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Podman — Rootless Containers Without Docker ## Introduction Rootless Containers Without Docker. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Podman requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible Postfix — Deploy and Configure Mail Servers URL: https://www.ansiblebyexample.com/articles/ansible-postfix-mail-server-smtp-configuration Description: Deploy Postfix mail servers with Ansible. Installation, relay configuration, SPF/DKIM/DMARC setup, TLS encryption, virtual domains, spam filtering. ## Introduction Postfix is the most popular open-source mail transfer agent (MTA) — secure, fast, and easy to configure. Ansible automates the full email infrastructure: install Postfix, configure SMTP relay or full mail server, set up TLS encryption, deploy SPF/DKIM/DMARC for deliverability, manage virtual domains, and integrate spam filtering. ## Install Postfix [code example] ### main.cf Template [code example] ## SMTP Relay (Satellite System) For servers that only send mail through a relay: [code example] ## DKIM Signing [code example] ## Virtual Domains [code example] [code example] [code example] ## Monitoring [code example] ## Troubleshooting ### Test Mail Delivery [code example] ## Related Articles - Ansible BIND DNS - Ansible Let's Encrypt SSL - Ansible Fail2Ban - Ansible Firewall Module ## Conclusion Ansible automates the full Postfix lifecycle — from simple relay clients (one config file pointing to a smarthost) to full mail servers with virtual domains, DKIM signing, TLS, and spam filtering. Template `main.cf` from variables, deploy DKIM keys, configure SPF/DMARC via DNS, and monitor queue depth. Email infrastructure as code means reproducible, auditable mail servers. --- ## Ansible PostgreSQL — Users Databases Extensions Backup URL: https://www.ansiblebyexample.com/articles/ansible-postgresql-users-databases-extensions-backup Description: Ansible PostgreSQL guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible PostgreSQL — Users Databases Extensions Backup ## Introduction Users Databases Extensions Backup. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible PostgreSQL requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible PostgreSQL Management URL: https://www.ansiblebyexample.com/articles/ansible-for-postgresql-by-examples Description: Manage PostgreSQL databases, users, extensions, backups, and replication with Ansible. Complete playbook examples for postgresql_db, postgresql_user. Ansible provides the `community.postgresql` collection with dedicated modules for every PostgreSQL administration task — from installation and database creation to backup, replication, and security hardening. This guide covers the complete PostgreSQL automation workflow with practical playbook examples. ## Prerequisites ### Install the PostgreSQL Collection [code example] ### Python Dependencies The PostgreSQL modules require the `psycopg2` library on the managed host: [code example] Or via system packages: [code example] ## PostgreSQL Module Reference | Module | Purpose | |--------|---------| | `community.postgresql.postgresql_db` | Create, drop, rename, backup, restore databases | | `community.postgresql.postgresql_user` | Create and manage users/roles | | `community.postgresql.postgresql_privs` | Grant/revoke privileges | | `community.postgresql.postgresql_query` | Execute SQL queries | | `community.postgresql.postgresql_pg_hba` | Manage pg_hba.conf entries | | `community.postgresql.postgresql_set` | Set PostgreSQL configuration parameters | | `community.postgresql.postgresql_info` | Gather PostgreSQL server information | | `community.postgresql.postgresql_slot` | Manage replication slots | | `community.postgresql.postgresql_schema` | Manage schemas | | `community.postgresql.postgresql_ext` | Manage extensions | | `community.postgresql.postgresql_tablespace` | Manage tablespaces | | `community.postgresql.postgresql_copy` | Copy data between files and tables | | `... --- ## Ansible postgresql_db — Drop Database URL: https://www.ansiblebyexample.com/articles/drop-a-postgresql-database-ansible-module-postgresql-db Description: How to automate the delete of a \"testdb\" database on PostgreSQL using Ansible Playbook and postgresql_db module. Tested, copy-paste examples included. ## How to Drop a PostgreSQL Database with Ansible? ## Ansible Drop a PostgreSQL Database - `community.postgresql.postgresql_db` - Add or remove PostgreSQL databases from a remote host Let's talk about the Ansible module `postgresql_db`. The full name is `community.postgresql.postgresql_db`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to add or remove PostgreSQL databases from a remote host. ## Parameters - name _string_ - Name of database - state _string_ - present/absent/dump/restore/rename - The operation Let me summarize the main parameters of the module `postgresql_db`. Ansible supposes that PostgreSQL is in the target node. The only required parameter is "name", the name of the database to interact with. The parameter "state" specify the desired state or the operation for the selected database. The option "present" means that the database should be Dropd and the option "absent" means that the database should be deleted. Other useful operations are "dump" and "restore" that uses `pg_dump`, the embedded PostgreSQL utility to backup and restore to the `target` file. Another useful operation is `rename`, from `name` to `target`. This module uses `psycopg2`, a Python PostgreSQL database library. You must ensure that `python3-psycopg2... --- ## Ansible postgresql_privs Module URL: https://www.ansiblebyexample.com/articles/grant-privileges-to-user-or-role-on-postgresql-database-ansible-module-postgresql-privs Description: How to automate the granting of all permission for "myuser" user/role on database "testdb" on PostgreSQL using Ansible Playbook and postgresql_privs. ## How to Grant Privileges to User/Role on PostgreSQL Database with Ansible? ## Ansible Grant Privileges to User/Role on PostgreSQL Database - `community.postgresql.postgresql_privs` - Grant or revoke privileges on PostgreSQL database objects Let's talk about the Ansible module `postgresql_privs`. The full name is `community.postgresql.postgresql_privs`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to Grant or revoke privileges on PostgreSQL database objects. This module uses `psycopg2`, a Python PostgreSQL User library. You must ensure that `python3-psycopg2` is installed on the host before using this module. ## Link - `community.postgresql.postgresql_privs` ## Playbook Let's jump into a real-life Ansible Playbook to Grant Privileges to User/Role on PostgreSQL Database. I'm going to show you how to grant all the privileges to user/role `myuser` for database `testdb` in the current PostgreSQL server. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Grant Privileges to Users/Roles on PostgreSQL databases with Ansible. --- ## Ansible postgresql_query — Run SQL URL: https://www.ansiblebyexample.com/articles/run-a-sql-command-query-on-postgresql-ansible-module-postgresql-query Description: Execute SQL queries on PostgreSQL with ansible community.postgresql.postgresql_query. Select, insert, update, and manage databases with playbooks. ## How to Run a SQL Command/Query on PostgreSQL with Ansible? ## Ansible Run a SQL Command/Query on PostgreSQL - `community.postgresql.postgresql_query` - Run PostgreSQL queries Let's talk about the Ansible module `postgresql_query`. The full name is `community.postgresql.postgresql_query`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to Run PostgreSQL queries. This module uses `psycopg2`, a Python PostgreSQL database library. You must ensure that `python3-psycopg2` is installed on the host before using this module. ## Parameters - db string - Name of database to connect to and run queries against - query string - SQL query to run - positional_args / named_args list - List of values to be passed to the query - encoding string - Set the client encoding for the current session (e.g. UTF-8) - autocommit boolean - autocommit mode - login_user / login_password / login_unix_socket / login_host / port string - connection parameters Let me summarize the main parameters of the module `postgresql_query`. Ansible supposes that PostgreSQL is running in the target node. First of all, you need to specify the parameter `db`, the name of the database to connect to and run queries against. Another important parameter is `query`, the SQL query to run. ... --- ## Ansible postgresql_user — Create Roles URL: https://www.ansiblebyexample.com/articles/create-a-postgresql-user-or-role-ansible-module-postgresql-user Description: Discover how to create and manage PostgreSQL users and roles with Ansible. Follow our guide for seamless user management on your PostgreSQL server. ## How to Create a PostgreSQL User / Role with Ansible? ## Ansible Create a PostgreSQL User/Role - `community.postgresql.postgresql_user` - Create, alter, or remove a user (role) from a PostgreSQL server instance Let's talk about the Ansible module `postgresql_user`. The full name is `community.postgresql.postgresql_user`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to create, alter, or remove a user (role) from a PostgreSQL server instance. This module uses `psycopg2`, a Python PostgreSQL User library. You must ensure that `python3-psycopg2` is installed on the host before using this module. ## Parameters - name _string_ - Name of User - state _string_ - present/absent - The user (role) state - password _string_ - Password cleartext or MD5-hashed - db _string_ - Grant user permission to the database Let me summarize the main parameters of the module `postgresql_user`. Ansible supposes that PostgreSQL is in the target node. The only required parameter is `name`, the name of the user to interact with. The parameter `state` specify the desired user (role) state. The option "present" means that the user/role should be created. The option `absent` means that the user/role should be deleted. You could specify the desired password in the `... --- ## Ansible pre_tasks and post_tasks — Execute Before and After Roles URL: https://www.ansiblebyexample.com/articles/ansible-pre-tasks-and-post-tasks-execute-before-and-after-roles Description: Use pre_tasks and post_tasks to run tasks before and after roles in Ansible plays. Handle load balancer management, notifications, and deployment. # Ansible pre_tasks and post_tasks — Execute Before and After Roles ## Introduction Ansible plays execute sections in a fixed order: `pre_tasks` → `roles` → `tasks` → `post_tasks`. `pre_tasks` run before any roles — use them for load balancer removal, pre-flight checks, and setup. `post_tasks` run after everything else — use them for load balancer re-addition, notifications, and verification. Handlers are flushed between each section. ## Execution Order [code example] ## The Classic Pattern: Load Balancer Management [code example] ## Pre-Flight Checks [code example] ## Post-Deployment Actions [code example] ## Handler Flushing Between Sections [code example] ## Database Migration Pattern [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Handler runs too early/late | Handlers flush between sections; check which section triggers it | | pre_task fails, roles still run | Use `any_errors_fatal: true` to stop on pre_task failure | | post_tasks skipped on failure | Use `--force-handlers` or `block/rescue` for critical post_tasks | | Order confusion | Remember: pre_tasks → roles → tasks → post_tasks | ## Best Practices 1. **Load balancer out/in** — `pre_tasks` to remove, `post_tasks` to add back 2. **Pre-flight checks in `pre_tasks`** — fail early before roles run 3. **Verification in `post_tasks`** — confirm everything works after deployment 4. **Notifications in `post_tasks`** — Slack, email, monitoring after completion 5. **Use `run_on... --- ## Ansible Private Automation Hub: Centralize and Secure Automation URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-4-private-automation-hub-installation Description: Learn how Ansible Private Automation Hub enhances IT automation by centralizing content, improving security, and facilitating collaboration across teams. ## Introduction In today’s fast-paced world, automation has become crucial for organizations seeking to streamline operations, improve efficiency, and accelerate project delivery. Ansible, a popular open-source automation tool, has revolutionized how organizations manage their IT infrastructure and application deployments. With the introduction of the Ansible Private Automation Hub, organizations now have an even more powerful and flexible solution to leverage the benefits of automation. ## What is Ansible Private Automation Hub? Ansible Private Automation Hub is a feature included in the Red Hat Ansible Automation Platform, designed to enhance the management and distribution of Ansible Content Collections. It is a trusted and secure central repository where organizations can store, control access to, and share their user-generated content alongside Ansible Certified Content from Red Hat and other leading partners. Benefits of Ansible Private Automation Hub: 1. Centralized Repository: With the Private Automation Hub, organizations can store their internally generated Ansible content in a single location. This allows for easy access, version control, and efficient collaboration among teams working on automation projects. 2. Enhanced Security and Governance: By leveraging the Private Automation Hub, organizations can exercise greater control over access to their user-generated content. This ensures that sensitive information and intellectual property are protected, and cont... --- ## Ansible Private Hub & Controller URL: https://www.ansiblebyexample.com/articles/integrate-private-automation-hub-with-automation-controller Description: Step-by-step guide to integrate Red Hat Private Automation Hub with Automation Controller — API tokens, credentials, custom EE configuration. ## Introduction Private Automation Hub is Red Hat's on-premise registry for Ansible collections and Execution Environments (EEs). Integrating it with Automation Controller gives your organization a single source of truth for curated, tested automation content — collections from Red Hat Certified, community, and your own custom content. This guide covers the complete integration: API tokens, credential configuration, collection sync, EE registry setup, and troubleshooting. ## Architecture Overview [code example] ## Prerequisites - Red Hat Ansible Automation Platform 2.4+ installed - Private Automation Hub instance running and accessible - Automation Controller instance running - Network connectivity between Controller and Hub (HTTPS) - Admin access to both systems ## Step 1: Generate API Token from Private Automation Hub 1. Log in to your Private Automation Hub at `https://ah.example.com` 2. Navigate to **Collections → API token management** 3. Click **Load token** to generate a new token 4. Click **Copy to clipboard** 5. Store the token securely (you'll need it for credentials) [code example] **Important**: The token is shown only once. If lost, generate a new one. ## Step 2: Create Credentials in Automation Controller You need three credentials for full integration: ### 2a. Published Collections Credential | Field | Value | |---|---| | Name | `Private Automation Hub — Published` | | Credential Type | `Ansible Galaxy/Automation Hub API Token` | | Galaxy Server UR... --- ## Ansible Privilege Escalation — become sudo su doas URL: https://www.ansiblebyexample.com/articles/ansible-privilege-escalation-become-sudo-su-doas Description: Ansible Privilege Escalation guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Privilege Escalation — become sudo su doas ## Introduction become sudo su doas. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Privilege Escalation requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible Privilege Escalation Failed — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-privilege-escalation-failed-fix-and-solutions Description: Fix become failures from missing sudo, wheel group, and policy issues. Tested on real machines with clear, copy-paste examples. # Ansible Privilege Escalation Failed — Fix and Solutions ## Introduction Fix become failures from missing sudo, wheel group, and policy issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix become failures from missing sudo, wheel group, and policy issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Privilege Escalation: Fix 'become' and sudo Errors URL: https://www.ansiblebyexample.com/articles/privilege-escalation-errors-ansible-troubleshooting Description: Complete guide to fixing Ansible privilege escalation errors. Learn become directives, sudo configuration, common error messages, and how to properly. Privilege escalation errors occur when Ansible cannot switch to a user with sufficient permissions to execute a task. Most commonly, this means the `become` directive is missing or misconfigured. This guide covers every common privilege escalation error and how to fix it. ## How Privilege Escalation Works in Ansible When you set `become: true`, Ansible: 1. Connects to the target host as the **connection user** (e.g., `deploy`) 2. Switches to the **become user** (default: `root`) using the **become method** (default: `sudo`) 3. Executes the task with the elevated privileges 4. Returns results to the connection user [code example] ## The Most Common Error ### Missing become: true **Error:** [code example] Or: [code example] **Wrong — no privilege escalation:** [code example] **Correct — become enabled:** [code example] ## Where to Set become ### Play Level (All Tasks in Play) [code example] ### Task Level (Specific Tasks Only) [code example] ### Block Level [code example] ### In ansible.cfg [code example] ### In Inventory [code example] ## Common Error Messages and Fixes ### "sudo: a password is required" [code example] **Fix options:** 1. Pass password interactively: [code example] 2. Configure passwordless sudo on the target: [code example] 3. Use Ansible Vault: [code example] ### "sudo: no tty present and no askpass program specified" [code example] **Cause:** The sudoers file requires a TTY for sudo. **Fix:** Add to sudoers on the target: [co... --- ## Ansible Product for Lists vs Combine for Dictionaries URL: https://www.ansiblebyexample.com/articles/ansible-product-for-lists-vs-combine-for-dictionaries Description: Learn the distinct use cases of Ansible's `product` filter for lists and `combine` filter for dictionaries. This guide offers practical examples. ## Introduction In the realm of Ansible automation, managing complex data structures is often required. Two powerful tools, the `product` and `combine` filters, play distinct roles in manipulating lists and dictionaries, respectively. Understanding their use cases can significantly enhance your playbook efficiency. ## `product`: Cartesian Product of Lists The `product` filter in Ansible generates the Cartesian product of two or more lists, producing all possible combinations of their elements. This is particularly useful when you need to iterate over multiple sets of values to configure systems or environments. ### Example: Configuring Hosts Across Environments [code example] #### Output: [code example] In this example, the `product` filter creates pairs of environments and roles, enabling scalable and dynamic configuration. ### Use Case: - Generating matrix-style combinations for testing or deployments. - Configuring multiple environments in one go. ## `combine`: Merging Dictionaries The `combine` filter allows you to merge multiple dictionaries into one, providing a way to consolidate configurations or override existing values. ### Example: Merging Configuration Maps [code example] #### Output: [code example] You can use the `combine` filter to dynamically construct configurations or override default values with user-provided data. ### Use Case: - Building dynamic variables from defaults and user inputs. - Consolidating configurations for modular roles or pla... --- ## Ansible Project 2022 Conclusion & 2023 Outlook: Key Developments URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-project-zeitgeist-2022-and-forecast-for-2023 Description: Explore Ansible's milestones from 2022 and what's ahead for 2023, including major releases, community growth, and evolving automation trends. Hello everybody. Welcome to Ansible Pilot from Luca Berton. This is the first video of the year, so it’s pretty special. I would like to touch base with you about the status of the Ansible project, a zeitgeist of the year 2022, and what to expect for the upcoming 2023. The year 2022 was a very interesting year transitioning from a pandemic to being free from restriction worldwide thanks to vaccination campaigns. The economy reached a rebound bus some unforeseen circumstances, the war in Ukraine, and consequently, the rise of inflation and utility costs slowed down. Many IT enterprises, especially the FANG, the four prominent American technology companies (Meta - formerly Facebook - Amazon, Netflix, and Alphabet/Google), put on hold the hiring processes or started some layoffs. The year 2023 begins with persistently high inflation pushed by high energy prices, a looming recession, leading central banks with high-interest rates, and a general risk-averse environment for businesses. This is the economic outlook that all organizations worldwide navigate nowadays. We all need to optimize our resources in order to be more productive. Every IT department faces the challenge of operating more services in less time. Automation is booming. Ansible is becoming prominent in the IT industry, so many job descriptions require the Ansible skill. We can see clearly on the Red Hat website homepage that Ansible is becoming the third prominent product of the company besides Red Hat Enterprise... --- ## Ansible Project Structure Guide — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-project-structure-guide-complete-guide Description: Organize Ansible projects with proper directory structure, roles, collections, and environment separation. With clear, copy-paste, step-by-step examples. # Ansible Project Structure Guide — Complete Guide ## Introduction Organize Ansible projects with proper directory structure, roles, collections, and environment separation. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Organize Ansible projects with proper directory structure, roles, collections, and environment separation. Start with the f... --- ## Ansible Proxmox — Manage VMs and Containers URL: https://www.ansiblebyexample.com/articles/ansible-proxmox-manage-vms-and-containers Description: Ansible Proxmox guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Proxmox — Manage VMs and Containers ## Introduction Manage VMs and Containers. Automate Proxmox infrastructure with Ansible using the `community.general` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches Proxmox naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/... --- ## Ansible Proxmox Automation — VMs, Containers, and Cluster Management URL: https://www.ansiblebyexample.com/articles/ansible-proxmox-automation-vms-containers-cluster Description: Automate Proxmox VE with Ansible using community.general modules. Create VMs from templates, manage LXC containers, configure storage, networking. ## Introduction Proxmox VE is an open-source virtualization platform for KVM virtual machines and LXC containers. The `community.general` collection provides modules to automate Proxmox through its REST API — create VMs from templates, manage LXC containers, handle storage, snapshots, and cluster operations. This article covers the complete Proxmox automation workflow with Ansible. ## Prerequisites [code example] ### Connection Variables [code example] ### Create API Token in Proxmox [code example] ## Module Reference | Module | Description | |---|---| | `community.general.proxmox` | Manage LXC containers | | `community.general.proxmox_kvm` | Manage KVM virtual machines | | `community.general.proxmox_template` | Manage VM/CT templates | | `community.general.proxmox_snap` | Manage snapshots | | `community.general.proxmox_disk` | Manage VM disks | | `community.general.proxmox_nic` | Manage VM network interfaces | | `community.general.proxmox_storage_info` | Query storage information | | `community.general.proxmox_tasks_info` | Query task status | ## Create a KVM Virtual Machine ### From Template (Clone) [code example] ### Create VM from ISO [code example] ## Manage LXC Containers [code example] ## Bulk VM Provisioning [code example] ## Snapshots [code example] ## Download Templates [code example] ## Dynamic Inventory Use the Proxmox dynamic inventory plugin to auto-discover VMs: [code example] [code example] ## Troubleshooting ### Authentication Fail... --- ## Ansible pull — Run Playbooks from Git URL: https://www.ansiblebyexample.com/articles/ansible-pull-mode-run-playbooks-from-git Description: Use ansible-pull to run Ansible playbooks directly on target hosts from a Git repository. Setup, cron scheduling, use cases, and comparison with. ## Introduction `ansible-pull` inverts Ansible's default push model — instead of a controller pushing playbooks to remote hosts, each host pulls a playbook repository from Git and runs it locally. This scales to thousands of hosts without a central controller bottleneck, and it's ideal for self-configuring nodes, edge devices, and auto-scaling cloud instances. ## Push vs Pull | | Push (`ansible-playbook`) | Pull (`ansible-pull`) | |---|---|---| | **Direction** | Controller → targets | Target pulls from Git | | **Central controller** | Required | Not required | | **SSH access** | Controller needs SSH to all targets | Not needed | | **Scaling** | Controller is bottleneck | Each host runs independently | | **Timing** | On-demand from controller | Cron schedule or on-demand | | **Network** | Controller must reach all hosts | Hosts must reach Git repo | | **Use case** | Ad-hoc, orchestration, workflows | Self-configuration, edge, auto-scaling | ## Quick Start [code example] This: 1. Clones the Git repository to a local directory 2. Runs `site.yml` on `localhost` 3. Cleans up after execution ## Command Reference [code example] | Flag | Description | |---|---| | `-U URL` | Git repository URL (required) | | `-C BRANCH` | Git branch, tag, or commit (default: `HEAD`) | | `-d DIR` | Directory to clone into (default: `~/.ansible/pull/`) | | `-i INVENTORY` | Inventory (use `localhost,` for local) | | `-e VARS` | Extra variables | | `--vault-password-file` | Vault password file | ... --- ## Ansible Python Interpreter — Fix Discovery and Version Errors URL: https://www.ansiblebyexample.com/articles/ansible-python-interpreter-fix-discovery-and-version-errors Description: Fix Ansible Python interpreter errors. Configure ansible_python_interpreter for remote hosts, handle discovery warnings, and resolve version mismatches. # Ansible Python Interpreter — Fix Discovery and Version Errors ## Introduction Ansible modules execute on remote hosts using Python. When Ansible can't find the right Python interpreter, you get discovery warnings, module failures, or wrong-version errors. This guide covers how Ansible discovers Python, how to configure it explicitly, and how to fix the most common interpreter problems. ## The Warning [code example] ## How Ansible Discovers Python Ansible tries interpreters in this order on the remote host: [code example] ## Fix: Set interpreter_python in ansible.cfg [code example] ### Options | Value | Behavior | |-------|----------| | `auto` | Discover + show warning | | `auto_silent` | Discover, no warning | | `auto_legacy` | Old behavior (Python 2 preferred) | | `/usr/bin/python3` | Explicit path, no discovery | ## Fix: Per-Host Configuration [code example] ## Fix: Group Variables [code example] ## Common Scenarios ### RHEL 8/9 — Platform Python [code example] ### Ubuntu — Multiple Python Versions [code example] ### Containers — Minimal Images [code example] ### Windows — No Python Interpreter Needed [code example] ## Debugging Interpreter Issues [code example] ## Playbook-Level Override [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | `MODULE FAILURE: No module named` | Wrong Python version for module dependencies | Set interpreter to Python with required packages | | `/usr/bin/python: not found` | Python ... --- ## Ansible Python Interpreter Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-python-interpreter-error-fix-and-solutions Description: Resolve Python interpreter discovery failures on remote hosts. Hands-on, tested examples and best practices for Ansible Python Interpreter Error. # Ansible Python Interpreter Error — Fix and Solutions ## Introduction Resolve Python interpreter discovery failures on remote hosts. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve Python interpreter discovery failures on remote hosts. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Quantum Computing Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/ansible-quantum-computing-infrastructure-automation Description: Automate quantum computing infrastructure with Ansible. Manage quantum simulators, hybrid classical-quantum pipelines, and QPU access across cloud. ## Introduction Quantum computing is moving from research labs to enterprise hybrid environments. Organizations need to manage quantum simulators for development, QPU access through cloud providers (IBM Quantum, Amazon Braket, Google Quantum AI), and hybrid classical-quantum workflows. Ansible automates the provisioning, configuration, and orchestration of this entire stack. ## Quantum Computing Stack [code example] ## Quantum Development Environment [code example] ## Quantum Simulator Cluster [code example] ## QPU Access Gateway [code example] ## Hybrid Quantum-Classical Workflow [code example] ## Monitoring and Cost Control [code example] ## Related Articles - Ansible Post-Quantum Cryptography - Ansible AI Supercomputing GPU Clusters - Ansible at Scale - Ansible Confidential Computing ## Conclusion Quantum computing infrastructure combines quantum-specific components (simulators, QPU access, error mitigation) with classical infrastructure (HPC clusters, job schedulers, monitoring). Ansible automates provisioning of quantum development environments, deploying GPU-accelerated simulators, configuring multi-provider QPU access gateways, and orchestrating hybrid quantum-classical workflows. As quantum hardware improves and quantum advantage becomes practical for more use cases, having automated, reproducible infrastructure will be essential for organizations investing in quantum capabilities. --- ## Ansible RabbitMQ — Deploy Message Brokers and Queues URL: https://www.ansiblebyexample.com/articles/ansible-rabbitmq-deploy-message-brokers-queues Description: Deploy RabbitMQ with Ansible. Installation, clustering, virtual hosts, user management, queue policies, TLS, monitoring with Prometheus, and high. ## Introduction RabbitMQ is the most widely deployed open-source message broker, supporting AMQP, MQTT, and STOMP protocols. Ansible's `community.rabbitmq` collection provides modules for managing every aspect — installation, clustering, virtual hosts, users, permissions, exchanges, queues, policies, and plugins. This guide covers single-node through production clustered deployments. ## Prerequisites [code example] ## Install RabbitMQ [code example] ## Virtual Hosts and Users [code example] ## Exchanges and Queues [code example] ## Clustering [code example] ## Policies [code example] ## TLS Configuration [code example] [code example] ## Monitoring [code example] ## Health Check [code example] ## Troubleshooting ### Cluster Partition [code example] ### Memory Alarm [code example] ## Related Articles - Ansible Redis - Ansible Docker Compose - Ansible ELK Stack - Ansible Firewall Module ## Conclusion Ansible's `community.rabbitmq` collection manages the full RabbitMQ lifecycle — installation, clustering with shared Erlang cookies, virtual hosts for multi-tenancy, users with fine-grained permissions, exchanges and queues with dead-letter routing, HA policies, and TLS encryption. Use quorum queues for durability, Prometheus for monitoring, and policies for automatic message lifecycle management. All configuration is declarative and idempotent. --- ## Ansible rabbitmq_plugin Module — Manage RabbitMQ Plugins URL: https://www.ansiblebyexample.com/articles/ansible-rabbitmq-plugin-module-manage-rabbitmq-plugins Description: Enable and disable RabbitMQ plugins for message broker functionality. Tested on real machines with clear, copy-paste examples. # Ansible rabbitmq_plugin Module — Manage RabbitMQ Plugins ## Introduction The `community.rabbitmq.rabbitmq_plugin` module enable and disable RabbitMQ plugins for message broker functionality. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.rabbitmq` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.rabbitmq.rabbitmq_plugin` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check... --- ## Ansible rabbitmq_user Module — Manage RabbitMQ Users URL: https://www.ansiblebyexample.com/articles/ansible-rabbitmq-user-module-manage-rabbitmq-users Description: Create RabbitMQ users, set passwords, and configure virtual host permissions. With clear, copy-paste, step-by-step examples. # Ansible rabbitmq_user Module — Manage RabbitMQ Users ## Introduction The `community.rabbitmq.rabbitmq_user` module create RabbitMQ users, set passwords, and configure virtual host permissions. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.rabbitmq` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.rabbitmq.rabbitmq_user` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check... --- ## Ansible rabbitmq_vhost Module — Manage RabbitMQ Virtual Hosts URL: https://www.ansiblebyexample.com/articles/ansible-rabbitmq-vhost-module-manage-rabbitmq-virtual-hosts Description: Create and delete RabbitMQ virtual hosts for multi-tenant message isolation. Hands-on, tested examples and best practices for Ansible rabbitmq_vhost Module. # Ansible rabbitmq_vhost Module — Manage RabbitMQ Virtual Hosts ## Introduction The `community.rabbitmq.rabbitmq_vhost` module create and delete RabbitMQ virtual hosts for multi-tenant message isolation. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.rabbitmq` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.rabbitmq.rabbitmq_vhost` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Tes... --- ## Ansible raw Module — Run Commands Without Python URL: https://www.ansiblebyexample.com/articles/ansible-raw-module-run-commands-without-python Description: Use ansible.builtin.raw to execute commands on hosts without Python installed. Bootstrap Python, configure network devices, and manage minimal systems. # Ansible raw Module — Run Commands Without Python ## Introduction Most Ansible modules require Python on the remote host. `ansible.builtin.raw` bypasses this requirement entirely — it sends commands directly over SSH (or the configured connection) without any module framework. This makes it essential for three scenarios: bootstrapping Python on new systems, managing network devices without Python, and interacting with minimal/embedded systems. ## Basic Usage [code example] ## Bootstrap Python The most common use case — install Python on a fresh system so other modules work: [code example] ### Auto-Detect and Bootstrap [code example] ## Network Device Management [code example] ## Docker Container Bootstrap [code example] ## Embedded/IoT Systems [code example] ## raw vs command vs shell | Feature | `raw` | `command` | `shell` | |---------|-------|-----------|---------| | Needs Python | ❌ | ✅ | ✅ | | Pipe/redirect | ✅ (shell-based) | ❌ | ✅ | | `creates`/`removes` | ❌ | ✅ | ✅ | | `chdir` | ❌ | ✅ | ✅ | | `changed_when` auto | ❌ (always changed) | ✅ | ✅ | | Environment vars | Via shell syntax | `environment:` | `environment:` | | Use case | No Python, bootstrap | Normal commands | Commands with pipes | ## Key Behaviors | Behavior | Detail | |----------|--------| | `gather_facts` | Must set to `false` when using raw on Python-less hosts | | Changed status | Always reports "changed" — use `changed_when` | | Return values | `stdout`, `stdout_lines`, `rc`, `stderr` ... --- ## Ansible rds_instance Module — Manage AWS RDS Database Instances URL: https://www.ansiblebyexample.com/articles/ansible-rds-instance-module-manage-aws-rds-database-instances Description: Create, modify, and manage Amazon RDS database instances with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible rds_instance Module — Manage AWS RDS Database Instances ## Introduction The `amazon.aws.rds_instance` module create, modify, and manage Amazon RDS database instances with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.rds_instance` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--... --- ## Ansible Read File Content into Variable — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-read-file-content-into-variable-complete-guide Description: Read remote file content into an Ansible variable using slurp and lookup. Tested on real machines with clear, copy-paste examples. # Ansible Read File Content into Variable — Complete Guide ## Introduction Read remote file content into an Ansible variable using slurp and lookup. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Read remote file content into an Ansible variable using slurp and lookup. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible reboot Module — Reboot Linux URL: https://www.ansiblebyexample.com/articles/reboot-remote-hosts-ansible-module-reboot Description: Reboot Linux servers with the Ansible reboot module. Complete guide with pre/post delay, timeout, test commands, rolling reboots, kernel updates. ## Introduction Rebooting servers is a critical operation in system administration — kernel updates, configuration changes, and hardware maintenance all require it. The `ansible.builtin.reboot` module handles the entire lifecycle: notifying users, executing the reboot, waiting for the host to come back online, and verifying it's functional. No manual SSH reconnection needed. For Windows hosts, use `ansible.windows.win_reboot` instead. ## Module Reference **Full name:** `ansible.builtin.reboot` **Collection:** `ansible.builtin` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `reboot_timeout` | int | 600 | Max seconds to wait for reboot to complete | | `msg` | string | "Reboot initiated by Ansible" | Broadcast message to logged-in users | | `reboot_command` | string | OS-specific | Custom reboot command | | `pre_reboot_delay` | int | 0 | Seconds to wait before rebooting | | `post_reboot_delay` | int | 0 | Seconds to wait after host comes back | | `test_command` | string | `whoami` | Command to verify host is functional | | `boot_time_command` | string | `cat /proc/sys/kernel/random/boot_id` | Command to detect if host has rebooted | | `connect_timeout` | int | None | Override connection timeout during reboot | ### Return Values | Key | Type | Description | |-----|------|-------------| | `rebooted` | bool | Whether the host was rebooted | | `elapsed` | int | Seconds elapsed waiting for reboot | ## Basic Playbook... --- ## Ansible Recursive Loop Detected — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-recursive-loop-detected-fix-and-solutions Description: Fix recursive loop errors from circular includes and variable references. Tested on real machines with clear, copy-paste examples. # Ansible Recursive Loop Detected — Fix and Solutions ## Introduction Fix recursive loop errors from circular includes and variable references. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix recursive loop errors from circular includes and variable references. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Red Hat Satellite and Foreman Integration URL: https://www.ansiblebyexample.com/articles/ansible-red-hat-satellite-foreman-integration Description: Integrate Ansible with Red Hat Satellite and Foreman. Dynamic inventory, host provisioning, content view management, patching workflows, and compliance. ## Introduction Red Hat Satellite (and its upstream project Foreman) is the enterprise platform for lifecycle management of RHEL hosts — provisioning, patching, content management, and compliance. The `theforeman.foreman` Ansible collection provides a dynamic inventory plugin and 70+ modules to automate every Satellite/Foreman operation. This guide covers inventory integration, host provisioning, content view management, patching workflows, and compliance reporting. ## Prerequisites [code example] ### Satellite Credentials [code example] ## Dynamic Inventory from Satellite ### Basic Configuration [code example] [code example] ### Advanced Inventory [code example] ## Host Provisioning ### Create Host [code example] ### Create Host Group [code example] ## Content View Management ### Create Content View [code example] ### Promote Content View [code example] ## Patching Workflow ### Scheduled Patching via Satellite [code example] ### Errata Management [code example] ## Activation Keys [code example] ## Compliance Reporting [code example] ## Troubleshooting ### API Connection Failed [code example] ### Inventory Empty - Verify hosts have `Managed` flag set in Satellite - Check organization/location permissions for the API user - Verify `validate_certs` matches your SSL setup ### Slow Inventory [code example] ## Related Articles - Ansible Automation Platform 2.6 - Ansible RHEL 10 Migration - Ansible Compliance - Ansible Dynamic Inventory ## Co... --- ## Ansible redhat_subscription Module URL: https://www.ansiblebyexample.com/articles/register-a-system-with-red-hat-subscription-manager-ansible-module-redhat-subscription Description: How to automate the registration of a machine RedHat Enterprise Linux 8 to subscription-manager using the access.redhat.com credential, assign a pool of. ## How to register a system with Red Hat Subscription-Manager with Ansible? ## Ansible register a system with Red Hat Subscription-Manager - community.general.redhat_subscription - Manage registration and subscriptions to RHSM using the subscription-manager command Today we're talking about the Ansible module redhat_subscription. The full name is `community.general.redhat_subscription`, which means that is part of the collection `community.general` maintained by the Ansible community Manage registration and subscriptions to RHSM using the subscription-manager command. This module is specific for RedHat Enterprise Linux. ## Parameters - state _string_ - present/absent - username _string_ - access.redhat.com or Satellite 6 username - password _string_ - access.redhat.com or Satellite 6 password - auto_attach _boolean_ - no/yes auto-consume available subscriptions - pool_id _list_ - subscription pool IDs to consume - pool _string_ - '^(Red Hat Enterprise Server|Red Hat Virtualization)$' - consumer_id _string_ - resume a previous registration Let me summarize the main parameters. The `state` parameter allows you to specify if you want to add or remove a registration from the target machine. The username and password allow you to specify the `access.redhat.com` website credential or Satellite 6 credential. Once the machine is registered you need to define which subscription to consume. The `auto_attach` allows you to auto consume all the available subscriptions for the Machi... --- ## Ansible Redis — Deploy and Configure In-Memory Cache Clusters URL: https://www.ansiblebyexample.com/articles/ansible-redis-deploy-configure-cache-clusters Description: Deploy Redis with Ansible. Installation, configuration tuning, persistence, Sentinel high availability, Redis Cluster sharding, security hardening. ## Introduction Redis is the most popular in-memory data store — used as a cache, message broker, session store, and database. Ansible automates the full Redis lifecycle: install, template configurations for standalone or clustered setups, deploy Sentinel for high availability, tune memory and persistence settings, and configure security. ## Install Redis [code example] ### Redis Config Template [code example] ## Redis Sentinel (High Availability) [code example] [code example] ### Replication Setup [code example] ## Redis Cluster (Sharding) [code example] [code example] ## TLS Encryption [code example] ## ACL (Access Control) [code example] ## Monitoring [code example] ## Health Check [code example] ## Troubleshooting ### "MISCONF Redis is configured to save RDB snapshots" [code example] ### High Latency [code example] ## Related Articles - Ansible MySQL PostgreSQL - Ansible Docker Compose - Ansible sysctl Module - Ansible Firewall Module ## Conclusion Ansible deploys Redis at any scale — standalone with persistence, Sentinel for automatic failover, or Cluster for sharding. Template configurations from variables, tune memory (`maxmemory` + eviction policy), enable AOF for durability, set up TLS for encryption, and configure ACLs for fine-grained access. Use the Redis Exporter for Prometheus metrics and scheduled health checks to keep your deployment healthy. --- ## Ansible redis_info Module — Gather Redis Server Information URL: https://www.ansiblebyexample.com/articles/ansible-redis-info-module-gather-redis-server-information Description: Collect Redis server info, stats, and configuration data with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible redis_info Module — Gather Redis Server Information ## Introduction The `community.general.redis_info` module collect Redis server info, stats, and configuration data with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.redis_info` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** —... --- ## Ansible Regex Filters — Search & Replace URL: https://www.ansiblebyexample.com/articles/automating-package-management-with-ansible-extracting-the-latest-kernel-version-using-the-regex-search-regex-findall-and-regex-replace-filters Description: Use ansible regex_search, regex_findall, and regex_replace filters to search, extract, and transform strings in playbooks. Real-world examples included. ## Regular Expression A regular expression (regex) is a character pattern describing a set of strings. It is a powerful tool for searching, validating, and manipulating text data. Regular expressions are widely used in programming languages, text editors, and other software tools that work with text data. A regular expression consists of a sequence of characters defining the matching pattern. These characters can include letters, digits, special characters, and meta-characters. Meta-characters are special characters that have a special meaning in regular expressions, such as `.` (match any character), `*` (match zero or more occurrences), and `+` (check one or more occurrences). Regular expressions can be used for a variety of tasks, such as: - Searching for specific patterns in text data - Validating input data to ensure it conforms to a particular format - Extracting specific data from text - Replacing parts of the text with other text - Splitting text into regions based on a delimiter or pattern For example, the regular expression `^[a-z]+@[a-z]+\.[a-z]{2,3}$` matches email addresses that are composed of one or more lowercase letters before the `@` symbol, one or more lowercase letters after the `@` symbol and before the `.`, and a two or three-letter lowercase top-level domain after the `.`. Regular expressions can be complex and require careful crafting to achieve the desired results. Many online resources and tutorials are available to help learn regular expressio... --- ## Ansible regex_escape — Escape Regex URL: https://www.ansiblebyexample.com/articles/ansible-regex-escape-filter-special-characters Description: Escape special characters in Ansible with regex_escape before using them in regex_search, regex_replace, and lineinfile pattern matching. ## Introduction The `regex_escape` filter in Ansible escapes special regex characters in a string so it can be safely used as a literal match in regex operations. Without escaping, characters like `.`, `*`, `+`, `(`, `)`, `[`, `]`, `{`, `}`, `^`, `$`, `|`, `\`, and `?` are interpreted as regex metacharacters, causing unexpected matches or errors. This filter is essential when building dynamic regex patterns from variables that may contain special characters. ## Syntax [code example] ## Parameters [code example] ## Characters Escaped [code example] ## Basic Examples [code example] ## Practical Use Cases ### Search for Literal Strings in Files [code example] ### Replace Literal Strings Containing Special Characters [code example] ### Dynamic Pattern Building [code example] ### Combining with regex_search and regex_replace [code example] ## Common Mistakes [code example] ## regex_escape vs Manual Escaping [code example] ## Related Articles - Ansible regex_search Filter - Ansible regex_replace Filter - Ansible Jinja2 Filters - Ansible lineinfile Module - Ansible map vs selectattr vs json_query ## Conclusion Use `regex_escape()` any time you build a regex pattern from a variable that might contain special characters. It prevents subtle bugs where dots match any character, brackets create character classes, or parentheses form capture groups. The filter is especially critical for IP addresses, file paths, URLs, version strings, and any user-provided input ... --- ## Ansible regex_escape Filter — Safely Escape Regular Expressions in Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-regex-escape-filter-regular-expressions Description: Use the Ansible regex_escape filter to safely escape special characters in regular expressions. Includes examples with lineinfile, replace. ## Introduction The `regex_escape` filter escapes special regular expression characters in a string so it can be used safely as a literal match in regex operations. Without escaping, characters like `.`, `*`, `[`, `(`, `+`, `?`, `$`, and `^` have special meaning in regex and will cause unexpected matches or errors. ## Syntax [code example] **Optional parameter:** [code example] ## How It Works The filter adds a backslash before every regex metacharacter: | Input | Output | |-------|--------| | `192.168.1.1` | `192\.168\.1\.1` | | `file[0].txt` | `file\[0\]\.txt` | | `C:\Users\admin` | `C:\\Users\\admin` | | `price: $9.99` | `price:\ \$9\.99` | | `(dev)` | `\(dev\)` | | `host+port` | `host\+port` | | `end$` | `end\$` | | `*.log` | `\*\.log` | ## Pattern 1: Safe lineinfile with Dynamic Values [code example] ## Pattern 2: Replace Module with Special Characters [code example] ## Pattern 3: Conditional Check with regex_search [code example] ## Pattern 4: Loop with Dynamic Patterns [code example] ## Pattern 5: Combine with Other Filters [code example] ## When NOT to Use regex_escape Don't escape strings that are intentionally regex patterns: [code example] ## Troubleshooting ### "sre_constants.error: nothing to repeat" You have an unescaped `*`, `+`, or `?` at the start of a pattern. Use `regex_escape()` on the variable: [code example] ### "sre_constants.error: unbalanced parenthesis" Unescaped `(` or `)` in the variable: [code example] ## Related Artic... --- ## Ansible regex_replace vs replace Filter URL: https://www.ansiblebyexample.com/articles/ansible-regex-replace-vs-replace-vs-regex-search Description: Compare regex_replace, replace, and regex_search filters in Ansible. Master string manipulation with practical examples for config files, logs, and data. ## Introduction Ansible provides three filters for string manipulation: `replace` for simple substitution, `regex_replace` for pattern-based substitution, and `regex_search` for extracting matches. Choosing the right one avoids overcomplicated expressions for simple tasks and underpowered tools for complex ones. ## Quick Comparison | Filter | Purpose | Input | Output | |--------|---------|-------|--------| | `replace` | Simple string substitution | Exact string match | Modified string | | `regex_replace` | Pattern-based substitution | Regex pattern | Modified string | | `regex_search` | Extract matching text | Regex pattern | Matched string or list | ## replace — Simple Substitution [code example] ## regex_replace — Pattern Substitution [code example] ## regex_search — Extract Matches [code example] ## regex_findall — All Matches [code example] ## Practical Examples ### Parse Structured Output [code example] ### Sanitize Input [code example] ### Transform Config Values [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Jinja2 Templates - Ansible Filter Plugins - Ansible map vs selectattr vs json_query - Ansible lineinfile Module ## Conclusion **replace** for exact string substitution (fast, simple). **regex_replace** for pattern-based substitution with capture groups. **regex_search** for extracting text that matches a pattern. **regex_findall** for finding all occurrences. Rule of thumb: if your search string is literal tex... --- ## Ansible regex_search Filter — Examples URL: https://www.ansiblebyexample.com/articles/ansible-regex-search-filter-extract-text-examples Description: Use the Ansible regex_search filter to extract text from strings with regular expressions. Includes capture groups, multiline matching, and practical. ## Introduction The `regex_search` filter searches a string for a regular expression pattern and returns the match. If the pattern includes capture groups, it returns the captured text. If there's no match, it returns an empty string. It's the most versatile text extraction tool in Ansible — use it to pull version numbers, IP addresses, error codes, or any structured text out of command output. ## Basic Syntax [code example] ## Simple Match Examples [code example] ## Capture Groups Capture groups `()` extract specific parts of the match: [code example] ## Multiline Matching [code example] ## Command Output Parsing [code example] ## Conditional Logic with regex_search [code example] ## regex_search vs regex_findall | Filter | Returns | Use When | |--------|---------|----------| | `regex_search` | First match (string or list) | You want one result | | `regex_findall` | All matches (list) | You want every occurrence | [code example] ## Common Patterns | What to Extract | Pattern | Example Input → Output | |----------------|---------|----------------------| | Version X.Y.Z | `(\d+\.\d+\.\d+)` | "v2.16.3-rc1" → "2.16.3" | | IP address | `(\d+\.\d+\.\d+\.\d+)` | "host 10.0.0.1 port" → "10.0.0.1" | | Email | `([\w.+-]+@[\w-]+\.[\w.]+)` | "user: a@b.com" → "a@b.com" | | Key=value | `key\s*=\s*(.+)` | "key = value" → "value" | | Between quotes | `"([^"]*)"` | `name="test"` → "test" | | Error code | `error[:\s]+(\d+)` | "error: 403" → "403" | | Port number | `:(\d{2,... --- ## Ansible register: Capture and Use Task Output URL: https://www.ansiblebyexample.com/articles/ansible-register-store-task-output Description: Use Ansible register to capture task output. Access stdout, stderr, return codes, and use registered variables in conditions, loops, and debug. ## What Is Ansible register? Ansible register is a task keyword that captures a task's output into a variable. You can then use that variable in conditions (`when`), display it (`debug`), or pass it to other tasks. Every task produces a result object — `register` saves it for later use. ## Basic Usage [code example] Output structure: [code example] ## Access Result Fields [code example] ## Common Result Fields | Field | Type | Description | |-------|------|-------------| | `stdout` | string | Standard output (one string) | | `stdout_lines` | list | Standard output (list of lines) | | `stderr` | string | Standard error | | `stderr_lines` | list | Standard error (list of lines) | | `rc` | int | Return code (0 = success) | | `changed` | bool | Whether the task changed anything | | `failed` | bool | Whether the task failed | | `skipped` | bool | Whether the task was skipped | | `msg` | string | Module message (varies by module) | | `results` | list | Loop results (when used with `loop`) | Different modules return different fields: [code example] ## Use with Conditions [code example] ## Use with set_fact [code example] ## Register with Loops When using `register` with a loop, the result contains a `results` list: [code example] ## Register with ignore_errors [code example] ## Practical Patterns ### Check Before Acting [code example] ### Parse JSON Output [code example] ### Collect Info from Multiple Hosts [code example] ### Wait for Condition [code exam... --- ## Ansible Rename File — Move and Rename Files on Remote Hosts URL: https://www.ansiblebyexample.com/articles/ansible-rename-file-move-and-rename-files-on-remote-hosts Description: Rename and move files on remote hosts with Ansible. Use command mv, copy+file, and ansible.builtin.stat for conditional file rename operations. # Ansible Rename File — Move and Rename Files on Remote Hosts ## Introduction Ansible doesn't have a dedicated "rename" module — renaming is a move operation. You can use `ansible.builtin.command` with `mv`, or the `copy` + `file` (remove original) pattern for idempotent renames. This guide covers all approaches with their tradeoffs. ## Method 1: command + mv (Simplest) [code example] ### Rename with Condition [code example] ## Method 2: copy + file (Idempotent) [code example] ## Method 3: ansible.posix.synchronize (For Directories) [code example] ## Common Patterns ### Rename with Timestamp (Backup) [code example] ### Rename Multiple Files (Pattern) [code example] ### Rename If Exists (Safe Pattern) [code example] ### Atomic Rename (Replace in Place) [code example] ### Rename with Preserved Permissions [code example] ### Rename Directory [code example] ## Why No ansible.builtin.rename Module? Ansible treats file operations as state declarations: - `file`: Ensure a file/directory exists or is absent - `copy`: Ensure a file has specific content - `template`: Ensure a file matches a template "Rename" is a procedural action, not a state. The closest idempotent approach is `copy` (remote_src) + `file` (state=absent). ## Comparison of Methods | Method | Idempotent | Speed | Preserves Permissions | |--------|-----------|-------|----------------------| | `command: mv` + creates/removes | ✅ | Fast | ✅ | | `copy` (remote_src) + `file` (absent) | ✅ | Slower ... --- ## Ansible Rename File or Directory URL: https://www.ansiblebyexample.com/articles/rename-file-or-directory-ansible-module-copy-and-file Description: How to rename a file or directory \"foo\", checking the file existence, and performing the verification in a live Playbook and some simple Ansible code. ## How to rename a file or directory using an Ansible task on a remote system? ## Ansible rename file/directory First of all let me demystify that I'd like to propose a solution using only Ansible native modules, so no shell module to invoke the Unix utility `mv`. Today we're talking about Ansible two modules copy and file The full names are ansible.builtin.copy and ansible.builtin.file which means are part of the collection of modules "builtin" with ansible and shipped with it. Both are these modules are pretty stable and out for years. The purpose of the `copy` module is to copy files to remote locations. Once the file is successfully copied we could use the module `file` to delete the source file. ## Parameters ### Module copy - dest path - destination - src string - source - remote_src boolean - no / yes ### Module file - path string (dest, name) - file path - state string - file/absent/directory/hard/link/touch The parameter list is pretty wide but I'll summarize the most useful. The only required parameter is "dest" which specifies the destination path. The "src" specifies the source file presumed in the controller host. It could be a relative or absolute path. From version 2.0, in the copy module, you can use the "remote_src" parameter. If True it will search the file in the remote/target machine for the src. From version 2.8 copy module `remote_src` supports recursive copying. The only required is "path", where you specify the filesystem path of the file you're g... --- ## Ansible Rename File or Directory — Move and Rename with copy and file URL: https://www.ansiblebyexample.com/articles/ansible-rename-file-directory-move Description: Rename files and directories with Ansible using copy+file, command module, or synchronize. Handle atomic renames and cross-filesystem moves. ## Introduction Ansible has no dedicated "rename" module. Instead, use `ansible.builtin.copy` + `ansible.builtin.file` (idempotent), or `ansible.builtin.command` with `mv` (simple). This guide covers all approaches with their trade-offs. ## Method 1: copy + file (Idempotent) [code example] **Pros**: Idempotent, safe, preserves permissions **Cons**: Two tasks, briefly duplicates data ## Method 2: command mv (Simple) [code example] `removes` + `creates` make it idempotent: - Skips if source doesn't exist (already renamed) - Skips if destination already exists [code example] **Pros**: Simple, atomic, handles directories **Cons**: Uses command module (ansible-lint warning) ## Method 3: stat + command (Safe) [code example] ## Rename Multiple Files [code example] ## Rename with Backup [code example] ## Rename Directory [code example] ## Windows Rename [code example] ## Atomic Rename Pattern For configuration files that services read: [code example] ## Batch Rename with find [code example] ## Troubleshooting ### "mv: cannot move — Permission denied" [code example] ### Cross-Filesystem Move `mv` across filesystems copies then deletes. For large files: [code example] ## Related Articles - Ansible file Module - Ansible copy Module - Ansible find Module - Ansible shell Module ## Conclusion For simple renames, use `command: mv` with `removes`/`creates` for idempotency. For safety-critical renames, use `copy` + `file` (two tasks but fully idempotent). For... --- ## Ansible replace — Find & Replace URL: https://www.ansiblebyexample.com/articles/ansible-replace-module-regex-find-and-replace-in-files Description: Use ansible.builtin.replace for regex-based text replacement in files. Pattern matching, backreferences, multiline, and idempotent replacements. # Ansible replace Module — Regex Find and Replace in Files ## What Is ansible.builtin.replace? The `ansible.builtin.replace` module performs regex-based find-and-replace operations in files. Unlike `lineinfile` which works on whole lines, `replace` can modify parts of a line, handle multiline patterns, and use backreferences — making it ideal for updating configuration values, commenting out blocks, and bulk text transformations. ## Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `path` | string | required | File to modify | | `regexp` | string | required | Python regex pattern to find | | `replace` | string | `''` | Replacement string (supports backreferences) | | `before` | string | — | Only replace before this pattern | | `after` | string | — | Only replace after this pattern | | `backup` | boolean | false | Create backup before modifying | | `encoding` | string | utf-8 | File encoding | | `mode` | string | — | File permissions after modification | | `owner` | string | — | File owner | | `group` | string | — | File group | ## Basic Usage [code example] ## Backreferences Capture groups let you preserve parts of the matched text: [code example] ## Replace Within a Section Use `after` and `before` to limit replacements to a specific section: [code example] ## Comment Out Lines [code example] ## Case-Insensitive Replacement [code example] ## Multiline Patterns [code example] ## replace vs linei... --- ## Ansible REST API: Call Web APIs with the uri Module URL: https://www.ansiblebyexample.com/articles/ansible-rest-api-call-web-apis-with-the-uri-module Description: Learn how to call REST APIs from Ansible playbooks using the uri module. Practical examples for GET, POST, PUT, DELETE, authentication, and error handling. ## The ansible.builtin.uri Module The `uri` module is Ansible's built-in HTTP client. Use it to interact with REST APIs, web services, and health endpoints directly from your playbooks. ## GET Request [code example] ## POST Request [code example] ## PUT Request (Update) [code example] ## DELETE Request [code example] ## Authentication Methods ### Bearer Token [code example] ### Basic Auth [code example] ### API Key Header [code example] ## Error Handling [code example] ## Parse JSON Response [code example] ## Download a File [code example] For simple file downloads, prefer `get_url`: [code example] ## Wait for API to Be Ready [code example] ## Common Parameters Reference | Parameter | Description | Example | |-----------|-------------|---------| | `url` | Target URL | `https://api.example.com` | | `method` | HTTP method | `GET`, `POST`, `PUT`, `DELETE`, `PATCH` | | `body` | Request body | `{"key": "value"}` | | `body_format` | Body encoding | `json`, `form-urlencoded`, `raw` | | `headers` | HTTP headers | `{"Authorization": "Bearer token"}` | | `status_code` | Expected status | `200`, `[200, 201]` | | `return_content` | Include body in result | `true` | | `timeout` | Request timeout (seconds) | `30` | | `validate_certs` | Verify SSL | `true` (default) | | `dest` | Save response to file | `/tmp/output.json` | ## Related Articles - Ansible Tutorial for Beginners — Complete getting started guide - How to Install Ansible — Installation on all platfor... --- ## Ansible Restart Service — Handlers and Service Module URL: https://www.ansiblebyexample.com/articles/ansible-restart-service-handlers-and-service-module Description: Restart services in Ansible with handlers, service module, and systemd. Reload vs restart, conditional restarts, rolling restarts, and best practices. # Ansible Restart Service — Handlers and Service Module ## Introduction Restarting services is one of the most common Ansible operations — after deploying new config, updating packages, or rotating certificates. The right approach depends on context: handlers for config-triggered restarts, direct tasks for immediate restarts, and rolling patterns for zero-downtime deployments. ## Method 1: Handlers (Recommended) [code example] **Why handlers?** They only fire when notified (config actually changed), and run once even if notified multiple times. ## Method 2: Direct Task [code example] ## Reload vs Restart [code example] | Operation | Downtime | Use When | |-----------|----------|----------| | `reloaded` | None | Config change only | | `restarted` | Brief | Binary update, major config change, stuck process | | `stopped` + `started` | Yes | Need clean state | ## Handler Patterns ### Multiple Handlers [code example] ### Handler Chains [code example] ### Flush Handlers (Force Immediate Execution) [code example] ## Restart with Verification [code example] ## Rolling Restart (Zero Downtime) [code example] ## Conditional Restart [code example] ## systemd-Specific Restart [code example] ## Restart Multiple Services [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | Handler never fires | Verify task actually reports "changed" | | Handler fires too late | Use `meta: flush_handlers` | | Service fails to restart | Check logs: `journalctl -u se... --- ## Ansible rhsm_repository Module — Manage RHEL Subscription Repos URL: https://www.ansiblebyexample.com/articles/ansible-rhsm-repository-module-manage-rhel-subscription-repos Description: Enable and disable Red Hat Subscription Manager repositories with Ansible. With clear, copy-paste, step-by-step examples. # Ansible rhsm_repository Module — Manage RHEL Subscription Repos ## Introduction The `community.general.rhsm_repository` module enable and disable Red Hat Subscription Manager repositories with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.rhsm_repository` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test... --- ## Ansible Roles — Organize Playbooks into Reusable Components URL: https://www.ansiblebyexample.com/articles/ansible-roles-organize-reusable-playbooks Description: Structure Ansible automation with roles. Create, use, and share reusable roles with tasks, handlers, variables, templates, and dependencies. Complete. ## Introduction Roles break large playbooks into reusable, self-contained components. Instead of a 500-line playbook, you have `roles/nginx/`, `roles/postgresql/`, `roles/myapp/` — each with its own tasks, templates, variables, and handlers. Roles are shareable, testable, and the standard way to organize Ansible automation. ## Role Directory Structure [code example] | Directory | Purpose | Auto-loaded? | |-----------|---------|-------------| | `tasks/` | Main task list | ✅ `main.yml` | | `handlers/` | Handler definitions | ✅ `main.yml` | | `defaults/` | Default variables (lowest priority) | ✅ `main.yml` | | `vars/` | Role variables (high priority) | ✅ `main.yml` | | `templates/` | Jinja2 templates | Referenced by tasks | | `files/` | Static files | Referenced by tasks | | `meta/` | Dependencies and metadata | ✅ `main.yml` | ## Create a Role [code example] ### tasks/main.yml [code example] ### defaults/main.yml [code example] ### handlers/main.yml [code example] ### meta/main.yml [code example] ## Use a Role ### In a Playbook [code example] ### include_role (Dynamic) [code example] ### import_role (Static) [code example] ### include_role vs import_role | Feature | include_role | import_role | |---------|-------------|-------------| | When processed | Runtime (dynamic) | Parse time (static) | | Loop support | ✅ | ❌ | | Conditional | Per iteration | Applies to all tasks | | Tags | Limited | Full inheritance | | `tasks_from` | ✅ | ✅ | ## Variable Precedenc... --- ## Ansible Roles Explained — Structure, Create & Best Practices (2026) URL: https://www.ansiblebyexample.com/articles/ansible-roles-explained-structure-best-practices Description: Complete guide to Ansible roles. Learn directory structure, creating roles, using Galaxy, variable precedence, dependencies, and best practices. # Ansible Roles Explained ## What Are Roles? Roles are a way to organize playbooks into reusable components. Instead of one giant playbook, you split tasks, variables, templates, and files into a standard directory structure. ## Directory Structure [code example] ## Create a Role [code example] ### tasks/main.yml [code example] ### defaults/main.yml [code example] ### handlers/main.yml [code example] ### templates/nginx.conf.j2 [code example] ## Using Roles ### In a Playbook [code example] ### With import_role / include_role [code example] ## Variable Precedence From lowest to highest priority: 1. `defaults/main.yml` ← Role defaults (lowest) 2. Inventory `group_vars` 3. Inventory `host_vars` 4. Playbook `vars:` 5. `vars/main.yml` ← Role vars (high) 6. Task `vars:` 7. Extra vars (`-e`) ← Highest [code example] ## Role Dependencies ### meta/main.yml [code example] ## Galaxy Roles [code example] [code example] ## Best Practices 1. **Use defaults for everything users might change** 2. **Use vars for internal constants only** 3. **Tag your roles** for selective execution 4. **Include a README.md** with usage examples 5. **Test with Molecule** for CI/CD 6. **Keep roles focused** — one role = one responsibility 7. **Use FQCN** (fully qualified collection names) in tasks [code example] ## Conclusion Roles are the building blocks of scalable Ansible automation. Use `defaults/` for configurable variables, keep roles focused on a single responsibility, and shar... --- ## Ansible Roles Explained — Structure, Create, and Use Roles URL: https://www.ansiblebyexample.com/articles/what-are-ansible-roles Description: Learn how to create, structure, and use Ansible roles. Complete guide with directory layout, defaults vs vars, Galaxy, dependencies, and real-world. ## What Are Ansible Roles? Ansible roles are a way to organize playbook content into **reusable, self-contained units**. Instead of writing one massive playbook, you break functionality into roles like `nginx`, `postgresql`, `deploy-app` — each with its own tasks, variables, templates, and files. [code example] ## Why Use Roles? - **Reusability** — Write once, use across multiple playbooks and projects - **Organization** — Predictable directory structure, easy to navigate - **Sharing** — Publish to Ansible Galaxy or private Git repos - **Testing** — Test each role independently with Molecule - **Collaboration** — Teams work on different roles without conflicts ## Role Directory Structure [code example] ### What Goes Where | Directory | Purpose | Example | |-----------|---------|---------| | `defaults/` | Default values users can override | `nginx_port: 80` | | `vars/` | Internal role variables (harder to override) | `_nginx_user: www-data` | | `tasks/` | The actual automation tasks | Install, configure, start | | `handlers/` | Actions triggered by `notify` | Restart nginx | | `templates/` | Jinja2 files with variables | `nginx.conf.j2` | | `files/` | Static files to copy as-is | SSL certs, scripts | | `meta/` | Dependencies, author, license | Depends on `common` role | ## Create a Role ### Using ansible-galaxy init [code example] This creates the full directory structure automatically. ### Manual Creation Only create the directories you need — Ansible ignores mi... --- ## Ansible roles vs collections — Organize and Share Automation URL: https://www.ansiblebyexample.com/articles/ansible-roles-vs-collections Description: Compare Ansible roles and collections. Learn when to use each, directory structure, installation, and best practices for organizing reusable automation. ## Introduction Ansible roles and collections both package reusable automation, but they solve different problems. Roles bundle tasks, handlers, templates, and variables for a single purpose. Collections bundle roles, modules, plugins, and playbooks into a distributable namespace. Understanding the difference prevents you from building roles when you need collections, or over-engineering collections when a role suffices. ## Quick Comparison | Feature | Roles | Collections | |---------|-------|------------| | Contains | Tasks, handlers, templates, vars, files | Roles + modules + plugins + playbooks | | Namespace | Name only (`nginx`) | Namespace.name (`community.general`) | | Distribution | Ansible Galaxy (or git) | Ansible Galaxy, Automation Hub, git | | Versioning | Git tags | Semantic versioning | | Custom modules | ❌ Not standard | ✅ First-class support | | Custom plugins | ❌ Not standard | ✅ Filters, lookups, callbacks, etc. | | Dependencies | `meta/main.yml` | `galaxy.yml` with collections list | | Install command | `ansible-galaxy role install` | `ansible-galaxy collection install` | ## Roles — Single-Purpose Automation [code example] [code example] [code example] ### Install Roles [code example] [code example] ## Collections — Namespaced Packages [code example] [code example] ### Install Collections [code example] [code example] ### Using Collections [code example] ## When to Use Each ### Use a Role When... [code example] ### Use a Collection When... --- ## Ansible Rolling Updates — Patch Servers with Zero Downtime URL: https://www.ansiblebyexample.com/articles/rolling-update-redhat-like-systems-ansible-module-yum Description: Perform rolling updates on RHEL/CentOS/Fedora with Ansible. Complete guide covering serial batches, pre/post health checks, automatic rollback, kernel. ## Introduction Rolling updates patch servers in small batches instead of all at once — ensuring some servers are always available to handle traffic. Ansible's `serial` keyword controls batch size, while health checks and conditional reboots keep updates safe and predictable. ## Basic Rolling Update ### Update a Single Package [code example] ### Update All System Packages [code example] ## Serial Strategies ### Fixed Batch Size [code example] ### Percentage-Based [code example] ### Escalating Batches [code example] This is the safest strategy — test on one server first, then gradually increase. ## Production Rolling Update with Health Checks [code example] ## Security-Only Updates [code example] ## Bugfix-Only Updates [code example] ## Update with Rollback [code example] ## Exclude Packages [code example] ## Update Report [code example] ## Parameters Reference | Parameter | Values | Description | |-----------|--------|-------------| | `name` | package name or `"*"` | Package(s) to update | | `state` | `latest` | Update to newest version | | `update_cache` | `true` | Refresh repo metadata first | | `security` | `true` | Only security updates | | `bugfix` | `true` | Only bugfix updates | | `exclude` | list | Packages to skip | | `disablerepo` | string | Disable specific repos | | `enablerepo` | string | Enable specific repos | ## Related Articles - Install Packages: yum Module - Handle Yum Failures - Ansible Best Practices Guide - Ansible Roles Exp... --- ## Ansible Rotate Secrets and Passwords — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-rotate-secrets-and-passwords-complete-guide Description: Automate credential rotation for databases and APIs with Ansible. Hands-on, tested examples and best practices for Ansible Rotate Secrets and Passwords. # Ansible Rotate Secrets and Passwords — Complete Guide ## Introduction Automate credential rotation for databases and APIs with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Automate credential rotation for databases and APIs with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible route53 Module — Manage AWS Route 53 DNS Records URL: https://www.ansiblebyexample.com/articles/ansible-route53-module-manage-aws-route-53-dns-records Description: Create and manage DNS records in Amazon Route 53 hosted zones. Hands-on, tested examples and best practices for Ansible route53 Module. # Ansible route53 Module — Manage AWS Route 53 DNS Records ## Introduction The `amazon.aws.route53` module create and manage DNS records in Amazon Route 53 hosted zones. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install amazon.aws` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `amazon.aws.route53` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` before applying 5.... --- ## Ansible Rsyslog — Centralized Log Management URL: https://www.ansiblebyexample.com/articles/ansible-rsyslog-centralized-log-management Description: Deploy Rsyslog with Ansible for centralized log management. Client and server configuration, TLS encryption, log forwarding, filtering rules, templates,. ## Introduction Rsyslog is the default syslog daemon on most Linux distributions — processing millions of messages per second with filtering, templating, and forwarding to files, databases, or remote servers. Ansible automates the full centralized logging stack: rsyslog server for log collection, client agents for forwarding, TLS encryption, custom templates, and log rotation. ## Deploy Rsyslog Server [code example] ### Server Config Template [code example] ## Configure Clients [code example] [code example] ## Custom Filtering Rules [code example] ## Logrotate Integration [code example] ## Performance Tuning [code example] ## Health Check [code example] ## Troubleshooting ### Check Config Syntax [code example] ## Related Articles - Ansible Grafana Loki - Ansible Logrotate - Ansible ELK Stack - Ansible Auditd ## Conclusion Rsyslog is the workhorse of Linux logging — Ansible automates the central server (TCP/UDP/TLS listeners, per-host directory structure, JSON templates) and client forwarding (reliable queues, protocol selection). Use filtering rules for noise reduction, logrotate for disk management, and performance tuning for high-volume environments. Centralized logging as code means every server forwards logs consistently from day one. --- ## Ansible Run Ansible in Docker — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-run-ansible-in-docker-complete-guide Description: Execute playbooks inside Docker containers for consistent environments. Tested on real machines with clear, copy-paste examples. # Ansible Run Ansible in Docker — Complete Guide ## Introduction Execute playbooks inside Docker containers for consistent environments. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Execute playbooks inside Docker containers for consistent environments. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Run Command as Another User — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-run-command-as-another-user-complete-guide Description: Execute commands as a different user with become_user, su, and runas in Ansible. With clear, copy-paste, step-by-step examples. # Ansible Run Command as Another User — Complete Guide ## Introduction Execute commands as a different user with become_user, su, and runas in Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Execute commands as a different user with become_user, su, and runas in Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Run Playbook on Localhost — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-run-playbook-on-localhost-complete-guide Description: Execute playbooks on the local machine without SSH using connection local. Hands-on, tested examples and best practices for Ansible Run Playbook on Localhost. # Ansible Run Playbook on Localhost — Complete Guide ## Introduction Execute playbooks on the local machine without SSH using connection local. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Execute playbooks on the local machine without SSH using connection local. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Run Task Only Once — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-run-task-only-once-complete-guide Description: Execute a task on only one host using run_once and delegate_to. Tested on real machines with clear, copy-paste examples. # Ansible Run Task Only Once — Complete Guide ## Introduction Execute a task on only one host using run_once and delegate_to. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Execute a task on only one host using run_once and delegate_to. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Run Tasks in Parallel — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-run-tasks-in-parallel-complete-guide Description: Execute Ansible tasks in parallel using async, forks, and free strategy. Hands-on, tested examples and best practices for Ansible Run Tasks in Parallel. # Ansible Run Tasks in Parallel — Complete Guide ## Introduction Execute Ansible tasks in parallel using async, forks, and free strategy. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Execute Ansible tasks in parallel using async, forks, and free strategy. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible run_once — Execute a Task on Only One Host URL: https://www.ansiblebyexample.com/articles/ansible-run-once-execute-task-on-one-host Description: How to use Ansible run_once to execute tasks on a single host in a multi-host play. Examples with delegation, serial, and common pitfalls. # Ansible run_once — Execute a Task on Only One Host The `run_once: true` directive tells Ansible to execute a task only on the first host in the current batch, skipping all other hosts. This is essential for tasks that should happen exactly once — like database migrations, API calls, or generating shared artifacts. ## Basic Syntax [code example] This runs on the **first host** in the play's host list and skips the rest. ## Common Use Cases ### Database Migrations [code example] ### Download a Shared Artifact [code example] ### Send a Notification [code example] ### Generate Shared Config [code example] ## run_once with set_fact Variables set with `set_fact` + `run_once` are applied to **all hosts**: [code example] ## ⚠️ run_once with strategy: free When using `strategy: free`, Ansible runs tasks as fast as possible without synchronizing hosts. This means `run_once` **may behave unpredictably** — the "first host" might not be deterministic. [code example] **Fix:** Use `delegate_to` to specify exactly which host runs the task: [code example] ## run_once vs when: inventory_hostname == ... [code example] Both work, but `run_once` is cleaner and the standard approach. ## Related Articles - Ansible throttle — Control task concurrency - Ansible Dry Run — Test playbooks safely - Ansible Error Handling — Handle failures - Ansible set_fact — Dynamic variables ## Conclusion Use `run_once: true` for any task that should execute exactly once per play — databas... --- ## Ansible run_once — Execute a Task Only Once Across All Hosts URL: https://www.ansiblebyexample.com/articles/ansible-run-once-execute-task-single-host Description: Use Ansible run_once to execute a task on a single host in a play. Understand how it works with serial, strategy free, delegate_to, and when to use it. ## Introduction `run_once: true` tells Ansible to execute a task on only one host in the play, even when the play targets multiple hosts. It's essential for one-time operations like database migrations, load balancer updates, or sending a single notification — tasks that should happen exactly once, not once per host. ## Basic Syntax [code example] By default, Ansible runs the task on the **first host in the inventory** for that play. All other hosts skip it. The registered variable is still available on all hosts. ## How run_once Works [code example] ## run_once with delegate_to Combine `run_once` with `delegate_to` to run the task on a specific host: [code example] ## ⚠️ run_once with strategy: free This is the most common pitfall. The warning message: [code example] With `strategy: linear` (default), all hosts reach each task together, so `run_once` reliably executes on the first host and skips the rest. With `strategy: free`, hosts run independently at their own pace. The first host to reach a `run_once` task executes it — but other hosts might reach it before the first host finishes, causing **unpredictable behavior**. [code example] **Fix:** If you need `strategy: free` with one-time tasks, move the `run_once` task to a separate play with `strategy: linear`: [code example] ## run_once with serial When using `serial` (rolling updates), `run_once` executes once **per batch**, not once for the entire play: [code example] If you truly need once for the e... --- ## Ansible run_once — Execute Tasks on a Single Host URL: https://www.ansiblebyexample.com/articles/ansible-run-once-execute-tasks-on-a-single-host Description: Use run_once to execute Ansible tasks on exactly one host. Run database migrations, leader elections, one-time setup, and cluster initialization correctly. # Ansible run_once — Execute Tasks on a Single Host ## Introduction When a play targets multiple hosts, every task runs on every host. But some tasks should only run once — database migrations, schema changes, license activation, or cluster initialization. `run_once: true` executes the task on the first host in the batch and skips it on all other hosts, while still making the registered results available everywhere. ## Basic Usage [code example] ## Which Host Runs It? By default, `run_once` executes on the **first host** in the play's host list: [code example] ### Control Which Host [code example] ## Registered Variables Variables registered by `run_once` tasks are available on **all hosts**: [code example] ## Common Use Cases ### Database Migrations [code example] ### Cluster Initialization [code example] ### Cache Clearing [code example] ### Leader Election [code example] ## run_once with serial [code example] ## run_once vs delegate_to vs when | Approach | Use Case | |----------|----------| | `run_once: true` | Run on one host, share results with all | | `delegate_to: host` | Run on a specific host, counted against current host | | `when: inventory_hostname == groups['all'][0]` | Explicit first-host targeting | | `run_once: true` + `delegate_to: localhost` | Run on controller once | ## Troubleshooting | Issue | Solution | |-------|----------| | Task runs multiple times with `serial` | `run_once` runs once per batch; use a flag file for true singl... --- ## Ansible run_once vs delegate_to vs serial — Control Execution Targets URL: https://www.ansiblebyexample.com/articles/ansible-run-once-vs-delegate-to-vs-serial Description: Compare run_once, delegate_to, and serial in Ansible. Learn when to use each to control where and how tasks execute across your inventory. ## Introduction Ansible normally runs every task on every host in the play. But sometimes you need to run a task once (database migration), run it on a different host (update load balancer from web server play), or roll out changes in batches (serial deployment). Three directives control this: `run_once`, `delegate_to`, and `serial`. ## Quick Comparison | Directive | Effect | Scope | Common Use | |-----------|--------|-------|-----------| | `run_once` | Execute task on first host only | Task | DB migrations, one-time setup | | `delegate_to` | Execute task on a different host | Task | LB updates, central API calls | | `serial` | Limit concurrent hosts per batch | Play | Rolling deployments | ## run_once — Execute Once [code example] ### run_once Gotchas [code example] ## delegate_to — Run Somewhere Else [code example] ### delegate_to localhost [code example] ### delegate_facts [code example] ## serial — Batch Execution [code example] ### Serial with Rolling Updates [code example] ## Combining All Three [code example] ## Common Mistakes [code example] ## Related Articles - Ansible at Scale - Ansible Strategies Guide - Ansible Inventory Guide - Ansible Playbook Guide ## Conclusion **run_once**: execute a task once across the play (DB migration, API call, notification). **delegate_to**: execute a task on a different host while keeping the current host's variables (load balancer updates, central API calls). **serial**: control how many hosts run at once fo... --- ## Ansible Samba — Configure File Sharing for Linux and Windows URL: https://www.ansiblebyexample.com/articles/ansible-samba-file-sharing-linux-windows Description: Deploy and configure Samba with Ansible. File sharing between Linux and Windows, user management, access control, printer sharing, Active Directory member. ## Introduction Samba provides SMB/CIFS file sharing between Linux and Windows systems. Ansible automates the full setup — install Samba, template `smb.conf` for shares, manage users and passwords, configure access control, join Active Directory domains, and set up printer sharing. This is essential for mixed Linux/Windows environments. ## Install Samba [code example] ### smb.conf Template [code example] ## User Management [code example] [code example] ## Department Shares [code example] ## Join Active Directory [code example] [code example] ## Mount SMB Shares on Linux Clients [code example] ## Troubleshooting ### Test Config [code example] ### Permission Issues [code example] ## Related Articles - Ansible NFS Share - Ansible User Module - Ansible Firewall Module - Ansible Windows AD ## Conclusion Ansible templates `smb.conf` from share definitions in variables — add shares by adding items to a list, manage users with `smbpasswd`, join AD domains with `net ads join`, and mount shares on clients with `ansible.posix.mount`. Validate with `testparm` before applying. Samba + Ansible gives you declarative file sharing that works across Linux, Windows, and macOS. --- ## Ansible Schedule Cron Job — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-schedule-cron-job-complete-guide Description: Create and manage cron jobs on remote hosts with Ansible cron module. Tested on real machines with clear, copy-paste examples. # Ansible Schedule Cron Job — Complete Guide ## Introduction Create and manage cron jobs on remote hosts with Ansible cron module. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Create and manage cron jobs on remote hosts with Ansible cron module. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible script — Local Scripts Remote URL: https://www.ansiblebyexample.com/articles/ansible-script-module-run-local-scripts-on-remote-hosts Description: Use ansible.builtin.script to transfer and execute local scripts on remote hosts without copying them first. Run Bash, Python, and PowerShell scripts. # Ansible script Module — Run Local Scripts on Remote Hosts ## Introduction `ansible.builtin.script` transfers a script from the Ansible controller to remote hosts and executes it — all in one step. No need to `copy` the script first, no need for the script to exist on the remote machine. Ansible handles the transfer, execution, and cleanup automatically. ## Basic Usage [code example] ## With Arguments and Options [code example] ## Practical Examples ### System Health Check [code example] [code example] ### Application Setup Script [code example] ### Collect Diagnostics [code example] ### PowerShell on Windows [code example] ## script vs copy + command [code example] | Feature | `script` | `copy` + `command` | |---------|----------|-------------------| | Steps | 1 | 2-3 | | Script persists on remote | No (auto-cleaned) | Yes (unless you delete) | | `creates`/`removes` | ✅ | ✅ (on command) | | Template variables | ❌ (use `template` + `command`) | ✅ (with `template`) | | Idempotency | Via `creates`/`removes` | Via `creates`/`removes` | ## Idempotency Patterns [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "Permission denied" | Script needs execute bit locally; or use `executable:` | | "Interpreter not found" | Set `executable: /usr/bin/python3` or `/bin/bash` | | Script can't find files | Use `chdir:` to set working directory | | Always shows "changed" | Add `changed_when: false` or use `creates:` | | Variables not expanded ... --- ## Ansible SDK: Run Ansible Programmatically from Python URL: https://www.ansiblebyexample.com/articles/ansible-sdk Description: Complete guide to the Ansible SDK Python library. Learn how to run playbooks programmatically, use AnsibleJobDef and JobExecutor, integrate with. ## Introduction While Ansible is typically run from the command line, many automation platforms and custom applications need to execute Ansible programmatically. The **Ansible SDK** is a lightweight Python library that provides a clean interface to dispatch, monitor, and manage Ansible jobs directly from Python code — no shell commands needed. Whether you're building a self-service portal, integrating Ansible into a CI/CD pipeline, or creating a custom automation dashboard, the Ansible SDK provides the programmatic bridge. ## What is Ansible SDK? Ansible SDK is a Python library that wraps Ansible's execution engine, providing: - **Programmatic execution** of playbooks, roles, and tasks - **Asynchronous job management** with status monitoring - **Local execution** via Ansible Runner - **Remote execution** via Automation Mesh - **Native Python data structures** for inputs and outputs ### Installation [code example] Dependencies include `ansible-runner` and `ansible-core`. ## Architecture [code example] ### Local Execution The SDK uses **Ansible Runner** to execute playbooks on the local machine. Runner handles: - Pulling execution environments (containers) - Running jobs - Collecting output and status - Reporting results back to the SDK ### Remote Execution For distributed environments, the SDK connects to an **Automation Mesh** controller node, which distributes work across a mesh of Receptor nodes. ## Basic Usage ### Run a Playbook [code example] ### Project... --- ## Ansible seboolean — SELinux Booleans URL: https://www.ansiblebyexample.com/articles/enable-or-disable-selinux-boolean-on-linux-ansible-module-seboolean Description: Enable and disable SELinux booleans with ansible.posix.seboolean. Persist settings across reboots, list booleans, and troubleshoot SELinux policies. ## How to Enable or Disable SELinux Boolean on Linux with Ansible? ## SELinux Booleans - SELinux boolean - changes how SELinux reacts What is SELinux? Security-Enhanced Linux (SELinux) is a Linux kernel security module that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC). What are SELinux Booleans? An SELinux boolean is a single string that changes how SELinux reacts. You could find some examples in the following URL: https://www.redhat.com/sysadmin/change-selinux-settings-boolean ## Ansible Enable or Disable SELinux Boolean on Linux - ansible.posix.seboolean - Toggles SELinux booleans Today we're talking about Ansible module `seboolean`. The full name is `ansible.posix.seboolean`, which means that is part of the collection of modules to interact with POSIX systems. It's a module pretty stable and out for years, it toggles SELinux booleans. It supports a huge variety of Linux distributions and POSIX systems. It requires the `python3-libsemanage` or `libsemanage-python` package installed on the target system. ## Parameters - name string - The name of the boolean - state boolean - no/yes - persistent boolean - no/yes - ignore_selinux_state boolean - no/yes Let's see the parameter of the `seboolean` Ansible module. The only mandatory parameters are "name" and "state". The parameter "name" specifies the name of the SELinux boolean that we would like to modify. The parameter "state" allows you to enable or di... --- ## Ansible seboolean — Toggle SELinux Booleans URL: https://www.ansiblebyexample.com/articles/ansible-seboolean-toggle-selinux-booleans Description: Ansible seboolean guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible seboolean — Toggle SELinux Booleans ## Introduction Toggle SELinux Booleans. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible seboolean requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective task ... --- ## Ansible Secrets Management — Vault HashiCorp AWS URL: https://www.ansiblebyexample.com/articles/ansible-secrets-management-vault-hashicorp-aws Description: Ansible Secrets Management guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Secrets Management — Vault HashiCorp AWS ## Introduction Vault HashiCorp AWS. Automate AWS infrastructure with Ansible using the `amazon.aws` collection. This guide covers authentication, resource creation, management, and cleanup with practical playbook examples. ## Prerequisites [code example] ## Authentication [code example] ## Create Resources [code example] ## Manage Resources [code example] ## Resource Lifecycle [code example] ## Variables Structure [code example] ## Dynamic Inventory [code example] ## Error Handling [code example] ## CI/CD Integration [code example] ## Cost Management [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Authentication failed | Check environment variables or vault credentials | | Region not found | Verify region name matches AWS naming | | Rate limit exceeded | Add `retries` and `delay` to tasks | | Resource already exists | Use `state: present` for idempotent operations | | Timeout on creation | Increase `wait_timeout` parameter | ## Best Practices 1. **Use dynamic inventory** — auto-discover resources instead of static lists 2. **Tag everything** — consistent tags enable filtering and cost tracking 3. **Encrypt credentials** with Ansible Vault — never commit plaintext keys 4. **Use check mode** for dry runs: `--check --diff` 5. **Implement state management** — track what Ansible created for cleanup 6. **Separate environments** — different inventories for dev/staging/producti... --- ## Ansible selectattr & rejectattr Filters — Filter Lists by Object Attributes URL: https://www.ansiblebyexample.com/articles/ansible-selectattr-rejectattr-filters-guide Description: Use Ansible selectattr and rejectattr Jinja2 filters to filter lists of dictionaries by attribute values. Includes practical examples for inventory,. ## Introduction `selectattr` filters a list of objects (dictionaries) to keep only items where a specific attribute matches a condition. `rejectattr` does the opposite — it removes matching items. These are the Ansible equivalents of SQL's `WHERE` clause for lists. ## Syntax [code example] ## Available Tests | Test | Description | Example | |------|-------------|---------| | `equalto` / `eq` / `==` | Equal to value | `selectattr("state", "equalto", "running")` | | `ne` / `!=` | Not equal | `selectattr("state", "ne", "stopped")` | | `gt` / `>` | Greater than | `selectattr("size", "gt", 1024)` | | `lt` / `=` | Greater or equal | `selectattr("priority", "ge", 5)` | | `le` / `<=` | Less or equal | `selectattr("count", "le", 100)` | | `in` | Value in sequence | `selectattr("env", "in", ["prod", "staging"])` | | `match` | Regex match (start) | `selectattr("name", "match", "^web")` | | `search` | Regex search (anywhere) | `selectattr("name", "search", "prod")` | | `defined` | Attribute exists | `selectattr("email", "defined")` | | `undefined` | Attribute doesn't exist | `selectattr("email", "undefined")` | | `none` | Attribute is None | `selectattr("value", "none")` | | (omitted) | Truthiness | `selectattr("enabled")` | ## Pattern 1: Filter Services by State [code example] ## Pattern 2: Filter Inventory by Group Variables [code example] ## Pattern 3: Filter Task Results [code example] ## Pattern 4: Filter Mounted Filesystems [code example] ## Pattern 5: Filter Users [... --- ## Ansible selectattr and map — Filters URL: https://www.ansiblebyexample.com/articles/filtering-data-in-ansible-selectattr-and-map Description: Filter lists of dictionaries with Ansible selectattr and extract values with map(attribute). Practical examples with facts, services, and packages. # 🎯 Filtering Data in Ansible: `selectattr` and `map(attribute)` When working with **lists of dictionaries** in Ansible, filtering and extracting specific values is a common requirement. **Jinja2** provides two powerful filters to accomplish this: - `selectattr` → Filters the list based on a condition. - `map(attribute)` → Extracts a specific field from the filtered result. In this article, you'll learn: - ✅ How to **filter lists of dictionaries** in Ansible using `selectattr` - ✅ How to **extract specific values** using `map(attribute)` - ✅ How to **handle missing values safely** using `default()` --- ## 📌 **Understanding `selectattr` and `map(attribute)`** Before jumping into Ansible playbooks, let's break down these Jinja2 filters. ### ✅ `selectattr('name', 'equalto', search_name')` - **Filters** a list of dictionaries to **select** only the ones where `name == search_name`. ### ✅ `map(attribute='folder')` - **Extracts** the `folder` field from the filtered result. ### ✅ **Example Syntax** [code example] - `selectattr` filters the list **where `name` equals `search_name`**. - `map(attribute='folder')` **extracts only the `folder` values**. - `list` ensures the result is returned as a list. --- ## 🔥 **Example Use Case** ### **Scenario** You have a list of **users and their home directories** (`folder`). You want to **search for a specific user** and **get their folder path**. ### **Example Data** [code example] ### **Using `selectattr` and `map(attribute)` ... --- ## Ansible selectattr Filter — Filter Lists by Attribute URL: https://www.ansiblebyexample.com/articles/filter-a-list-by-its-attributes-ansible-selectattr-filter Description: Filter lists by attributes with Ansible selectattr and rejectattr. Working examples with dictionaries, facts, and map(attribute). Copy-paste playbooks. ## How to Filter A List By Its Attributes in an Ansible Playbook? ## selectattr filter in Ansible Playbook? - `{{ users|selectattr("is_active") }}` - `{{ users|selectattr("email", "none") }}` Today we're talking about Ansible `selectattr` Jinja filter. Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean. The two examples explain how-to for a specific attribute or value using a `users` list example. ## Links - Data manipulation - Jinja selectattr ## Playbook How to filter a list by its attributes in an Ansible Playbook. I'm going to use the `selectattr` filter to select only one information from Ansible System Information (Facts). Specifically, I'm going to filter only for enabled features in a network interface (`eth1`). ### code [code example] ### execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Filter A List By Its Attributes in an Ansible Playbook. --- ## Ansible selectattr Filter — Filter Lists of Dictionaries by Attribute URL: https://www.ansiblebyexample.com/articles/ansible-selectattr-filter-lists-dictionaries Description: Use the Ansible selectattr filter to filter lists of dictionaries by attribute values. With examples for match, equalto, defined, search, and rejectattr. ## Introduction The `selectattr` filter in Ansible selects items from a list of dictionaries where a specific attribute matches a condition. It's the Jinja2 equivalent of a SQL `WHERE` clause for list data. Combined with `rejectattr` (its inverse), `map`, and `list`, it's one of the most powerful data manipulation tools in Ansible. ## Syntax [code example] ## Available Tests [code example] ## Basic Examples [code example] ## rejectattr — The Inverse [code example] ## Combining selectattr with map [code example] ## Real-World Use Cases ### Filter Ansible Facts [code example] ### Filter Package Lists [code example] ### Filter Users for Provisioning [code example] ### Filter Inventory Groups [code example] ## Chaining Multiple Filters [code example] ## Common Mistakes [code example] ## selectattr vs json_query vs map [code example] ## Related Articles - Ansible map vs selectattr vs json_query - Ansible Filter Plugins - Ansible regex_search Filter - Ansible Jinja2 Templates - Ansible set_fact Module ## Conclusion `selectattr` is the go-to filter for filtering lists of dictionaries in Ansible. Combine it with `map(attribute='...')` to extract specific fields, chain multiple `selectattr` calls for AND conditions, and use `rejectattr` for exclusions. Always end the chain with `| list` to materialize the result. For complex nested data, consider `json_query` instead, but for most use cases `selectattr` is simpler and more readable. --- ## Ansible selinux Module — Configure SELinux Policy URL: https://www.ansiblebyexample.com/articles/ansible-selinux-module-configure-selinux-policy Description: Ansible selinux Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible selinux Module — Configure SELinux Policy ## Introduction Configure SELinux Policy. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible selinux Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible SELinux Permissive Mode URL: https://www.ansiblebyexample.com/articles/enable-or-disable-permissive-domain-in-selinux-policy-on-linux-ansible-module-selinux-permissive Description: How to automate the enabling or disabling of SELinux Permissive policy per single process or domain keeping the whole system under enforcing policy. ## SELinux Permissive Domain ### What is SELinux? Security-Enhanced Linux (SELinux) is a Linux kernel security module that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC). ### What is SELinux Permissive Domain? SELinux Permissive Domains allow an administrator to configure a single process (domain) to run permissive, rather than making the whole system permissive. ## Ansible Enable or Disable Permissive Domain in SELinux policy - `community.general.selinux_permissive` - Change permissive domain in SELinux policy Today we're talking about Ansible module `selinux_permissive`. The full name is `community.general.selinux_permissive`, which means that is part of the collection of modules to community-supported for Ansible. It supports a huge variety of Linux distributions and it changes the permissive domain in SELinux policy. It requires the `policycoreutils-python` package installed on the target system for `semanage` utility. ## Parameters - **domain** (name) string - the name of the domain - **permissive** boolean - no/yes - no_reload boolean - **no**/yes Let's see the parameter of the selinux_permissive Ansible module. The only mandatory parameters are "domain" and "permissive". The parameter "domain" or alias "name" specifies the name of the SELinux domain that we would add to the list of permissive domains. The parameter "permissive" allows you to enable or disable the SELinux permissive domain immediate... --- ## Ansible Semaphore — Open Source UI URL: https://www.ansiblebyexample.com/articles/ansible-semaphore-open-source-ui Description: Install and configure Ansible Semaphore — a lightweight open-source web UI for running Ansible playbooks. Docker setup, project config, and job scheduling. ## Introduction Ansible Semaphore is a lightweight, open-source web UI for running Ansible playbooks. It provides project management, credential storage, job scheduling, and a clean dashboard — without the resource overhead of AWX or Automation Controller. If you need a simple way for your team to run playbooks through a browser, Semaphore is the fastest path to get there. ## Semaphore vs AWX vs Automation Controller | Feature | Semaphore | AWX | Automation Controller | |---|---|---|---| | **License** | MIT (free) | Apache 2.0 (free) | Red Hat subscription | | **Resource usage** | ~50 MB RAM | ~4 GB RAM | ~8 GB RAM | | **Setup time** | 5 minutes | 30-60 minutes | Hours (with installer) | | **Web UI** | Clean, minimal | Full-featured | Enterprise | | **API** | REST API | REST API | REST API | | **RBAC** | Basic (admin/user) | Full RBAC | Full RBAC + orgs | | **Workflows** | Task templates | Workflow visualizer | Workflow visualizer | | **Scheduling** | Cron schedules | Cron schedules | Cron schedules | | **Inventories** | Static, file-based | Static + dynamic | Static + dynamic | | **Execution Environments** | No (uses system ansible) | Yes | Yes | | **Automation Mesh** | No | No | Yes | | **Best for** | Small teams, labs | Mid-size teams | Enterprise | ## Install with Docker Compose The fastest way to get Semaphore running: [code example] [code example] ### With PostgreSQL (Production) [code example] ## Install with Ansible Deploy Semaphore to a server using Ansibl... --- ## Ansible Semaphore — Open Source Web UI for Ansible URL: https://www.ansiblebyexample.com/articles/ansible-semaphore-open-source-web-ui-for-ansible Description: Ansible Semaphore guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Semaphore — Open Source Web UI for Ansible ## Introduction Open Source Web UI for Ansible. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Semaphore requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible Send Email Notifications — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-send-email-notifications-complete-guide Description: Send email alerts from playbooks on success or failure. Hands-on, tested examples and best practices for Ansible Send Email Notifications. # Ansible Send Email Notifications — Complete Guide ## Introduction Send email alerts from playbooks on success or failure. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Send email alerts from playbooks on success or failure. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Serial Keyword — Rolling Update Batch Size Strategy URL: https://www.ansiblebyexample.com/articles/ansible-serial-keyword-rolling-update-batch-size-strategy Description: Control rolling updates with Ansible serial keyword. Deploy to batches of hosts with percentage, canary patterns, and max_fail_percentage for. # Ansible Serial Keyword — Rolling Update Batch Size Strategy ## Introduction By default, Ansible runs tasks on all hosts simultaneously. The `serial` keyword changes this — it processes hosts in batches, enabling rolling updates, canary deployments, and zero-downtime upgrades. This is essential for production deployments where you can't take all servers offline at once. ## Basic Usage [code example] With 10 webservers: runs on hosts 1-2, waits for completion, then 3-4, then 5-6, etc. ## Percentage-Based Batches [code example] ## Canary Deployment Pattern Start with 1 host, then ramp up: [code example] ## Fail-Safe with max_fail_percentage Stop the entire deployment if too many hosts fail: [code example] ## Load Balancer Integration Remove hosts from load balancer during updates: [code example] ## Serial vs Forks vs Throttle | Keyword | Scope | Purpose | |---------|-------|---------| | `serial` | Play | Process N hosts before moving to next batch | | `forks` | Global | Max parallel SSH connections (default: 5) | | `throttle` | Task | Max parallel executions of a single task | [code example] ## any_errors_fatal with Serial [code example] ## Run Once per Batch [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Too slow | Increase `serial` value or `forks` | | Failures stop everything | Use `max_fail_percentage` instead of `any_errors_fatal` | | Need rollback | Add `block/rescue` pattern within serial play | | Hosts out of LB t... --- ## Ansible serial Percentage and Batch Deployment Strategies URL: https://www.ansiblebyexample.com/articles/ansible-serial-percentage-and-batch-deployment-strategies Description: Use serial with percentages and batch sizes for rolling deployments in Ansible. Control update speed, manage risk, and implement canary releases. # Ansible serial Percentage and Batch Deployment Strategies ## Introduction The `serial` keyword controls how many hosts Ansible updates at once. Using percentages (`serial: "25%"`) or stepped batches (`serial: [1, 5, "50%"]`) enables rolling deployments, canary releases, and risk-controlled updates. Without `serial`, Ansible runs on all hosts simultaneously — fine for configuration, risky for deployments. ## Basic Percentage [code example] With 20 hosts and `serial: "25%"`, Ansible runs 5 hosts per batch (4 batches total). ## Percentage Rounding | Hosts | serial | Batch Size | Batches | |-------|--------|------------|---------| | 10 | "25%" | 3 (rounds up) | 4 | | 10 | "30%" | 3 | 4 | | 10 | "50%" | 5 | 2 | | 100 | "10%" | 10 | 10 | | 7 | "25%" | 2 (rounds up) | 4 | | 1 | "50%" | 1 (minimum 1) | 1 | Percentages always round **up** to at least 1. ## Fixed Batch Size [code example] ## Stepped Batches (Canary Pattern) [code example] With 100 hosts: 1. Batch 1: 1 host (canary) 2. Batch 2: 5 hosts 3. Batch 3: 24 hosts (25% of 94 remaining) 4. Batch 4: 70 hosts (all remaining) ## Fail Fast with max_fail_percentage [code example] If >10% of a batch fails, the entire play aborts — preventing a bad deploy from spreading. ## Zero-Downtime with Load Balancer [code example] ## order Directive [code example] | Order | Description | |-------|-------------| | `inventory` | Default — order defined in inventory | | `sorted` | Alphabetical by hostname | | `reverse_sorted`... --- ## Ansible service — Restart Services URL: https://www.ansiblebyexample.com/articles/restart-services-on-remote-hosts-ansible-module-service Description: Manage system services with ansible.builtin.service. Start, stop, restart, and enable services on Linux with handlers and conditional examples. ## Introduction Managing services — starting, stopping, restarting, and enabling them at boot — is one of the most common tasks in system automation. The `ansible.builtin.service` module provides a cross-platform interface that works with systemd, SysV init, OpenRC, Solaris SMF, upstart, and BSD init systems. For Windows targets, use `ansible.windows.win_service` instead. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | string | Yes | Name of the service | | `state` | string | No* | `started`, `stopped`, `restarted`, `reloaded` | | `enabled` | bool | No* | Whether the service starts on boot | | `sleep` | int | No | Seconds to sleep between stop and start during restart | | `arguments` | string | No | Extra arguments passed to the service command | | `pattern` | string | No | Substring to match in `ps` output if service status is unavailable | | `use` | string | No | Force a specific service manager (`systemd`, `sysvinit`, etc.) | *At least one of `state` or `enabled` must be specified. ### State Values Explained | State | Behavior | |-------|----------| | `started` | Start service if not running; no action if already running | | `stopped` | Stop service if running; no action if already stopped | | `restarted` | Always stop and start (triggers `changed` every time) | | `reloaded` | Reload configuration without full restart | ## Basic Examples ### Restart a Service [code example] ### Start and... --- ## Ansible Service Module — Start Stop Restart Enable Services URL: https://www.ansiblebyexample.com/articles/ansible-service-module-start-stop-restart-enable-services Description: Manage system services with Ansible service module. Start, stop, restart, reload, and enable services on boot. Supports systemd, SysV init, and BSD. # Ansible Service Module — Start Stop Restart Enable Services ## Introduction The `ansible.builtin.service` module manages system services across all init systems — systemd, SysV init, OpenRC, and BSD rc.d. It's the universal way to start, stop, restart, and enable services on boot without worrying about the underlying init system. ## Quick Reference [code example] ## Parameters | Parameter | Values | Description | |-----------|--------|-------------| | `name` | string | Service name (required) | | `state` | started, stopped, restarted, reloaded | Desired service state | | `enabled` | true/false | Start on boot | | `pattern` | regex | Process name pattern for status check | | `sleep` | seconds | Wait between stop and start (for restarted) | | `arguments` | string | Additional arguments for the service command | ## Common Patterns ### Install and Start [code example] ### Restart on Configuration Change [code example] ### Reload vs Restart [code example] ### Multiple Services [code example] ### Stop and Disable [code example] ## service vs systemd Module [code example] | Feature | service | systemd | |---------|---------|---------| | Cross-platform | ✅ All init systems | ❌ systemd only | | `daemon_reload` | ❌ | ✅ | | `scope` (user units) | ❌ | ✅ | | Masked units | ❌ | ✅ | | Timer units | ❌ | ✅ | **Rule:** Use `service` unless you need systemd-specific features. ## Conditional Service Management [code example] ## Check Service Status [code example] ## W... --- ## Ansible service Module — Start, Stop, and Restart Services URL: https://www.ansiblebyexample.com/articles/ansible-service-module-start-stop-restart-services Description: How to use Ansible service module to manage system services — start, stop, restart, reload, and enable on boot. Examples for systemd and SysV. # Ansible service Module — Start, Stop, and Restart Services The `ansible.builtin.service` module manages system services across different init systems (systemd, SysV, Upstart). It's one of the most frequently used Ansible modules. ## Basic Usage [code example] ## Enable on Boot [code example] ## Restart with Handlers (Best Practice) Rather than unconditionally restarting, use handlers to restart only when config changes: [code example] ## systemd-specific Module For systemd-specific features (daemon-reload, scope, etc.), use `ansible.builtin.systemd`: [code example] ## Manage Multiple Services [code example] ## Parameters Reference | Parameter | Values | Description | |-----------|--------|-------------| | `name` | service name | Service to manage (required) | | `state` | started, stopped, restarted, reloaded | Desired state | | `enabled` | true, false | Start on boot | | `pattern` | regex | Process name to search for (fallback detection) | | `sleep` | seconds | Seconds to sleep between stop and start (for restarted) | ## Common Patterns [code example] ## Related Articles - Ansible Tutorial for Beginners — Getting started - Ansible Error Handling — Handle service failures - Ansible Facts — Use service_facts - Ansible assert Module — Validate service state - Ansible for Windows — Windows service management ## Conclusion The `service` module is essential for any Ansible automation. Use `state: started` + `enabled: true` for idempotent service management, a... --- ## Ansible service_facts — Enable on Boot URL: https://www.ansiblebyexample.com/articles/start-and-enable-services-on-boot-on-remote-hosts-ansible-module-service-facts-service Description: How to list the available Linux services and automate the start and enable service on boot process with Ansible playbook. Included code and Playbook with. ## How to enable services on boot on remote hosts with Ansible? ## Ansible enable services on boot on remote hosts - ansible.builtin.service_facts - Return service state information as fact data - ansible.builtin.service - Manage services Today we're talking about Ansible modules `service_facts` and `service`. First, you need to acquire the information of the services on the target machine. This task is performed by the Ansible module `service_facts`. You can't enable a service that doesn't exist, can you? The effective actions are performed by the Ansible module service. The full name is `ansible.builtin.service` which means that both these modules are part of the collection of modules "builtin" with Ansible and shipped with it. This module is pretty stable and out for years and its purpose is to manage services on remote hosts. For Windows targets, use the `ansible.windows.win_service` module instead. ## Parameters - name path - name of the service - state string - started / stopped / restarted / reloaded - enabled boolean - no/yes - arguments/args string - extra args The parameter list is pretty wide but I'll summarize the most useful. The only required parameter is "name" that specifies the name of the service. At least one between the "state" and "enabled" parameters is mandatory. The "state" parameter defines the action that we are going to take. It has four alternative options: "started" and "stopped" options allow you to run or stop the service. "restarted" is a... --- ## Ansible service_facts — Stop Services URL: https://www.ansiblebyexample.com/articles/stop-and-disable-services-on-boot-on-remote-hosts-ansible-module-service-facts-service Description: Stop, disable, and manage Linux services with Ansible service and service_facts modules. Control systemd units on remote hosts with playbook examples. ## How to stop and disable services on boot on Linux remote hosts with Ansible? ## Ansible enable services on boot on remote hosts - ansible.builtin.service_facts - Return service state information as fact data - ansible.builtin.service - Manage services Today we're talking about Ansible modules `service_facts` and `service`. First, you need to acquire the information of the services on the target machine. This task is performed by the Ansible module `service_facts`. You can't enable a service that doesn't exist, can you? The effective actions are performed by the Ansible module service. The full name is `ansible.builtin.service` which means that both these modules are part of the collection of modules "builtin" with Ansible and shipped with it. This module is pretty stable and out for years and its purpose is to manage services on remote hosts. For Windows targets, use the `ansible.windows.win_service` module instead. ## Parameters - name path - name of the service - state string - started / stopped / restarted / reloaded - enabled boolean - no/yes - arguments/args string - extra args The parameter list is pretty wide but I'll summarize the most useful. The only required parameter is "name" that specifies the name of the service. At least one between the "state" and "enabled" parameters is mandatory. The "state" parameter defines the action that we are going to take. It has four alternative options: "started" and "stopped" options allow you to run or stop the service. ... --- ## Ansible ServiceNow Integration — Automate ITSM Tickets and CMDB URL: https://www.ansiblebyexample.com/articles/ansible-servicenow-integration-itsm-tickets-cmdb Description: Integrate Ansible with ServiceNow for IT Service Management. Automate incident creation, change requests, CMDB updates, and closed-loop remediation. ## Introduction ServiceNow is the dominant IT Service Management (ITSM) platform in enterprise environments. Integrating Ansible with ServiceNow creates closed-loop automation: incidents trigger remediation playbooks, change requests auto-execute approved changes, and the CMDB stays in sync with actual infrastructure state. The `servicenow.itsm` collection provides native Ansible modules for the full ServiceNow API. ## Install the ServiceNow Collection [code example] ## Connection Setup [code example] [code example] ## Create Incidents Automatically [code example] ## Manage Change Requests [code example] ## Sync CMDB with Inventory [code example] ## ServiceNow Dynamic Inventory [code example] [code example] ## Closed-Loop Remediation Workflow [code example] [code example] ## Related Articles - Ansible Compliance as Code - Ansible AAP Enterprise - Ansible Error Handling - Ansible Vault Guide ## Conclusion Ansible + ServiceNow integration creates powerful enterprise automation. The `servicenow.itsm` collection handles incidents (auto-create from alerts, auto-resolve after remediation), change requests (create, wait for approval, execute, close), and CMDB sync (keep configuration items in sync with actual infrastructure). The dynamic inventory plugin lets you use ServiceNow as your source of truth. The ultimate pattern: closed-loop automation where monitoring triggers an incident, Ansible remediates it, and the incident closes automatically — with full audi... --- ## Ansible Set Environment Variables — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-set-environment-variables-complete-guide Description: Set environment variables for tasks, plays, and globally in Ansible playbooks. With clear, copy-paste, step-by-step examples. # Ansible Set Environment Variables — Complete Guide ## Introduction Set environment variables for tasks, plays, and globally in Ansible playbooks. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Set environment variables for tasks, plays, and globally in Ansible playbooks. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Set Up CICD Pipeline Integration — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-set-up-cicd-pipeline-integration-complete-guide Description: Integrate Ansible into GitHub Actions, GitLab CI, and Jenkins. Hands-on, tested examples and best practices for Ansible Set Up CICD Pipeline Integration. # Ansible Set Up CICD Pipeline Integration — Complete Guide ## Introduction Integrate Ansible into GitHub Actions, GitLab CI, and Jenkins. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Integrate Ansible into GitHub Actions, GitLab CI, and Jenkins. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Set Up Load Balancer — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-set-up-load-balancer-complete-guide Description: Configure HAProxy and Nginx load balancers with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible Set Up Load Balancer. # Ansible Set Up Load Balancer — Complete Guide ## Introduction Configure HAProxy and Nginx load balancers with Ansible. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Configure HAProxy and Nginx load balancers with Ansible. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Set Up VPN Server — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-set-up-vpn-server-complete-guide Description: Deploy WireGuard or OpenVPN servers with Ansible automation. Hands-on, tested examples and best practices for Ansible Set Up VPN Server. # Ansible Set Up VPN Server — Complete Guide ## Introduction Deploy WireGuard or OpenVPN servers with Ansible automation. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Deploy WireGuard or OpenVPN servers with Ansible automation. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible set_fact — ansible.builtin.set_fact Module Guide URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-module-create-runtime-variables Description: Complete guide to ansible.builtin.set_fact — create runtime variables, compute dynamic values, conditional facts, and variable scope with practical. ## Introduction `ansible.builtin.set_fact` creates or modifies variables during playbook execution. Unlike `vars` (which are static), `set_fact` lets you compute values from command output, transform data, combine facts, and make decisions at runtime. ## Basic Syntax [code example] ## Computed Values [code example] ## Conditional set_fact [code example] ## Lists and Dictionaries [code example] ## Variable Scope `set_fact` creates **host-scoped** variables — they persist for the rest of the play for that specific host: [code example] ### Access Other Host's Facts [code example] ## Cacheable Facts By default, `set_fact` values are lost after the playbook ends. Use `cacheable: true` to persist them in the fact cache: [code example] ## Common Patterns ### Build Dynamic Inventory Groups [code example] ### Parse Structured Command Output [code example] ### Accumulate Results Across Loop [code example] ## set_fact vs vars vs register | Method | When Set | Scope | Persistence | |--------|----------|-------|-------------| | `vars` | Before tasks | Play/role | Static | | `set_fact` | During execution | Host, all plays | Runtime (or cached) | | `register` | After task | Host, all plays | Runtime | [code example] ## Troubleshooting ### "set_fact value is a string, not an integer" Jinja2 returns strings by default. Cast explicitly: [code example] ### Variable Not Available in Next Play `set_fact` is host-scoped. If the next play targets different hosts, th... --- ## Ansible set_fact — Create and Modify Variables at Runtime URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-create-and-modify-variables-at-runtime Description: Use ansible.builtin.set_fact to create variables during playbook execution. Transform data, build dynamic values, cache facts, and share between plays. # Ansible set_fact — Create and Modify Variables at Runtime ## Introduction `ansible.builtin.set_fact` creates or modifies host variables during playbook execution. Unlike `vars` (defined before tasks run), `set_fact` values are computed at runtime — based on command output, conditional logic, or data transformations. Facts set this way persist for the rest of the play and can be cached across runs. ## Basic Usage [code example] ## Dynamic Values from Task Output [code example] ## Conditional Facts [code example] ## Data Transformations [code example] ## set_fact in Loops [code example] ## Fact Caching (cacheable) [code example] [code example] ## Scope and Persistence [code example] ## set_fact vs vars vs register | Feature | `set_fact` | `vars` | `register` | |---------|-----------|--------|-----------| | When evaluated | Runtime | Parse time | Runtime | | Can use task output | ✅ | ❌ | ✅ (auto) | | Persists across plays | ✅ | ❌ (play scope) | ✅ | | Can be cached | ✅ (`cacheable`) | ❌ | ❌ | | Can be conditional | ✅ | ❌ | ✅ | | Overrides other vars | Yes (high precedence) | Lower precedence | N/A | ## Common Patterns ### Default with Override [code example] ### Cross-Host Data Sharing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Fact not available in later task | Check task order; `set_fact` must run before use | | Fact overridden unexpectedly | `set_fact` has high precedence; check for duplicates | | Cached fact stale... --- ## Ansible set_fact — Create Dynamic Variables at Runtime URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-module-dynamic-variables Description: Use ansible.builtin.set_fact to create and modify variables during playbook execution. Dynamic facts, conditional variables, computed values. # Ansible set_fact — Create Dynamic Variables at Runtime ## Introduction The `ansible.builtin.set_fact` module creates or modifies variables (facts) during playbook execution. Unlike `vars` which are static, `set_fact` values can be computed from task results, conditionals, and other facts — making them essential for dynamic playbook logic. ## Basic Usage [code example] ## Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `key: value` | any | — | Variable name and value to set | | `cacheable` | boolean | `false` | Store fact in cache for persistence across runs | ## Computed Facts from Task Results [code example] ## Conditional Facts [code example] ## Build Lists and Dictionaries [code example] ## Cacheable Facts Cacheable facts persist across playbook runs when a fact cache is configured: [code example] [code example] ## Loop with set_fact [code example] ## set_fact vs vars vs register | Feature | `set_fact` | `vars` | `register` | |---------|-----------|--------|-----------| | When set | Runtime (task) | Parse time | After task | | Scope | Host (persistent in play) | Block/play/role | Task result | | Dynamic | ✅ Computed values | ❌ Static | ✅ Task output | | Cacheable | ✅ With `cacheable: true` | ❌ | ❌ | | Overrides | Can override vars | — | — | ## Cross-Host Facts [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Variables — Complete Guide - Ansible Facts — Gather Sy... --- ## Ansible set_fact Module — Create and Use Dynamic Variables URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-module-create-dynamic-variables Description: How to use Ansible set_fact module to create variables dynamically during playbook execution. Examples with register, conditionals, and complex data. # Ansible set_fact Module — Create and Use Dynamic Variables The `ansible.builtin.set_fact` module creates or updates variables (facts) dynamically during playbook execution. Unlike static variables in `vars:`, set_fact values can be computed from task output, conditionals, or other facts. ## Basic Syntax [code example] ## Compute Variables from Other Variables [code example] ## Use with register Output [code example] ## Conditional Facts [code example] ## Complex Data Structures [code example] ## Append to Lists [code example] ## Persistent Facts with cacheable By default, set_fact values only last for the current play. Use `cacheable: true` to persist across plays: [code example] Requires a fact caching plugin configured in `ansible.cfg`: [code example] ## Parameters | Parameter | Required | Description | |-----------|----------|-------------| | `key: value` | yes | Variable name and value to set | | `cacheable` | no | Store as cached fact (persists across plays) | ## Common Patterns [code example] ## Related Articles - Ansible Facts — Built-in system facts - Ansible Magic Variables — Special variables reference - Ansible assert Module — Validate your facts - Ansible Jinja2 length Filter — Count items in variables - Ansible Template Module — Use facts in templates ## Conclusion `set_fact` is essential for dynamic playbooks — use it to compute values at runtime, transform command output into usable variables, and build complex configurations from sys... --- ## Ansible set_fact vs vars — Variable Scope and Persistence URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-vs-vars-variable-scope-and-persistence Description: Understand the difference between set_fact and vars in Ansible. When to use each, variable scope rules, persistence across plays, and performance impact. # Ansible set_fact vs vars — Variable Scope and Persistence ## Introduction Ansible offers multiple ways to define variables — `vars`, `set_fact`, `register`, `include_vars`, and more. The most common confusion is between `vars` (defined statically) and `set_fact` (created dynamically at runtime). Understanding when each is appropriate prevents scope bugs and unexpected behavior. ## Key Differences | Feature | `vars` | `set_fact` | |---------|--------|------------| | When evaluated | Before play starts | During task execution | | Scope | Play or block | Host (persists across plays) | | Dynamic values | Limited (Jinja2 at definition) | Full (computed at runtime) | | Survives between plays | ❌ | ✅ | | Performance | Faster (no task execution) | Slower (runs as a task) | | Conditional | ❌ | ✅ (with `when`) | | Cacheable | N/A | ✅ (`cacheable: true`) | ## When to Use vars [code example] **Use `vars` when:** - Values are known before execution - Static configuration (ports, paths, names) - Template variables - Values don't depend on task results ## When to Use set_fact [code example] **Use `set_fact` when:** - Value depends on task results or gathered facts - Conditional variable assignment (with `when`) - Computing values from other dynamic data - Variable needed across multiple plays - Transforming registered output ## Scope Demonstration [code example] ## Register + set_fact Pattern [code example] ## Conditional set_fact [code example] ## Cacheable Facts [code ... --- ## Ansible set_fact vs vars vs extra vars — Variable Assignment Compared URL: https://www.ansiblebyexample.com/articles/ansible-set-fact-vs-vars-vs-extra-vars Description: Compare set_fact, vars, and extra vars in Ansible. Understand scope, precedence, persistence, and when to use each variable assignment method. ## Introduction Ansible has multiple ways to define variables: `vars`, `set_fact`, `register`, extra vars (`-e`), `group_vars`, `host_vars`, and more. Each has different scope, precedence, and persistence. Choosing wrong leads to variables silently overridden or unavailable where you need them. ## Quick Comparison | Method | Scope | Precedence | Persistent Across Plays | Set At | |--------|-------|------------|------------------------|--------| | `vars:` (play) | Play | 14 | ❌ No | Playbook parse time | | `vars:` (task) | Task | 14 | ❌ No | Task execution | | `set_fact` | Host (rest of playbook) | 19 | ✅ Yes | Runtime | | `register` | Host (rest of playbook) | 19 | ✅ Yes | Runtime | | Extra vars `-e` | Global | 22 (highest) | ✅ Yes | Command line | | `group_vars/` | Group hosts | 10-12 | ✅ Yes | File load | | `host_vars/` | Single host | 13 | ✅ Yes | File load | | Role `defaults/` | Role scope | 2 (lowest) | ❌ No | Role load | | Role `vars/` | Role scope | 18 | ❌ No | Role load | | `include_vars` | Play/host | 18 | ✅ Yes | Runtime | ## vars — Static Play/Task Variables [code example] **Use vars when:** - Values are known at write time - Values don't change during execution - You want clear, readable variable definitions ## set_fact — Runtime Variables [code example] **Use set_fact when:** - Value depends on runtime data (facts, registered output) - Value needs computation or conditionals - Value must persist across plays - Value differs per host based on gathered fac... --- ## Ansible set_fact: Create and Modify Variables at Runtime URL: https://www.ansiblebyexample.com/articles/mastering-dynamic-variable-creation-with-set-fact Description: Master Ansible set_fact for dynamic variable creation. Learn syntax, set_fact vs register, conditionals, loops, caching, and best practices. ## What is the set_fact Module? The `ansible.builtin.set_fact` module lets you create or modify variables dynamically during playbook execution. Unlike variables defined in `vars`, `group_vars`, or `host_vars`, facts set with `set_fact` are computed at runtime and can depend on the results of previous tasks. This makes `set_fact` essential for: - Transforming data from API responses or command output - Building conditional variables based on host properties - Creating computed values from multiple sources - Setting host-specific facts that persist across plays (with `cacheable: true`) ## Basic Syntax The simplest use of `set_fact` creates a variable with a static or computed value: [code example] You can set multiple facts in a single task: [code example] ## set_fact vs register: When to Use Each A common source of confusion is when to use `set_fact` versus `register`. Here's the distinction: **`register`** captures the entire output of a task: [code example] **`set_fact`** creates a variable with a specific, often transformed, value: [code example] **Use `register`** when you need the raw output of a task. **Use `set_fact`** when you need a clean, transformed value. ## Practical Examples ### Conditional Fact Setting Set different values based on the operating system: [code example] ### Building Dynamic Data Structures Create lists and dictionaries dynamically: [code example] ### Extracting Data from API Responses A common pattern is querying an API an... --- ## Ansible set_stats Module — Set Custom Stats for Playbook Reporting URL: https://www.ansiblebyexample.com/articles/ansible-set-stats-module-set-custom-stats-for-playbook-reporting Description: Define custom statistics that display in the playbook PLAY RECAP summary. Tested on real machines with clear, copy-paste examples. # Ansible set_stats Module — Set Custom Stats for Playbook Reporting ## Introduction The `ansible.builtin.set_stats` module define custom statistics that display in the playbook PLAY RECAP summary. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.set_stats` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode**... --- ## Ansible shell — Remote Shell Commands URL: https://www.ansiblebyexample.com/articles/ansible-shell-module-run-commands Description: Use the Ansible shell module to run shell commands with pipes, redirects, and environment variables. When to use shell vs command. ## Introduction `ansible.builtin.shell` executes commands through the shell (`/bin/sh`) on remote hosts. Unlike the `command` module, `shell` supports pipes, redirects, environment variables, and globbing. Use it when you need shell features — but prefer dedicated modules when possible. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `cmd` | — | Command string to execute | | `chdir` | — | Change to directory before running | | `creates` | — | Skip if this file exists | | `removes` | — | Skip if this file doesn't exist | | `executable` | `/bin/sh` | Shell to use | | `stdin` | — | Data to pipe to stdin | | `stdin_add_newline` | `true` | Add newline to stdin | | `warn` | `true` | Show warnings for common mistakes | ## Shell Features ### Pipes [code example] ### Redirects [code example] ### Environment Variables [code example] ### Globbing [code example] ## Idempotent Patterns ### creates / removes [code example] ### changed_when / failed_when [code example] ## shell vs command | Feature | `shell` | `command` | |---------|---------|-----------| | Pipes (`\|`) | ✅ | ❌ | | Redirects (`>`, `>>`) | ✅ | ❌ | | Environment variables (`$VAR`) | ✅ | ❌ | | Globbing (`*.log`) | ✅ | ❌ | | Semicolons (`;`) | ✅ | ❌ | | Shell injection risk | ⚠️ Higher | ✅ Lower | | Speed | Slightly slower | Slightly faster | **Rule**: Use `command` when you don't need shell features. Use `shell` only when you need p... --- ## Ansible shell vs command Module — When to Use Each URL: https://www.ansiblebyexample.com/articles/ansible-shell-vs-command-module-difference Description: Understand the difference between Ansible shell and command modules. When to use pipes, redirects, and environment variables vs simple commands. Examples. ## Introduction Ansible has two modules for running commands on remote hosts: `command` and `shell`. They look similar but behave differently. `command` runs a binary directly (safer, faster). `shell` runs through `/bin/sh` (supports pipes, redirects, environment variables). Choosing the wrong one is a common source of bugs. ## The Key Difference [code example] | Feature | command | shell | |---------|---------|-------| | Pipes (`\|`) | ❌ | ✅ | | Redirects (`>`, `>>`) | ❌ | ✅ | | Globbing (`*.log`) | ❌ | ✅ | | Environment variables (`$HOME`) | ❌ | ✅ | | Chained commands (`&&`, `;`) | ❌ | ✅ | | Subshells (`$(...)`) | ❌ | ✅ | | Shell injection risk | Low | Higher | | Performance | Slightly faster | Slightly slower | ## When to Use command Use `command` for simple, single-binary execution: [code example] ## When to Use shell Use `shell` when you need shell features: [code example] ## Safer shell Usage ### Avoid Shell Injection [code example] ### Use executable Parameter [code example] ## Common Parameters (Both Modules) [code example] ## Handling Output [code example] ## Idempotency (creates/removes) Both modules are **not idempotent by default** — they run every time. Use `creates` or `removes` to make them conditional: [code example] ## Better Alternatives Before using `command` or `shell`, check if a dedicated module exists: | Instead of... | Use... | |--------------|--------| | `command: apt install nginx` | `ansible.builtin.apt: name=nginx` | | `com... --- ## Ansible shell vs command Module: When to Use Each URL: https://www.ansiblebyexample.com/articles/ansible-shell-vs-command-module-when-to-use-each Description: Ansible shell vs command module compared — when to use pipes, redirects, and environment variables. Learn best practices and why command is preferred over. ## shell vs command at a Glance | Feature | command | shell | |---------|---------|-------| | **Pipes** (`\|`) | ❌ No | ✅ Yes | | **Redirects** (`>`, `>>`) | ❌ No | ✅ Yes | | **Wildcards** (`*`, `?`) | ❌ No | ✅ Yes | | **Environment variables** (`$HOME`) | ❌ No | ✅ Yes | | **Shell builtins** (`source`, `export`) | ❌ No | ✅ Yes | | **Security** | ✅ Safer | ⚠️ Injection risk | | **Preferred** | ✅ Yes | When needed | ## ansible.builtin.command (Preferred) Runs commands **without** a shell. Safer because it avoids shell injection: [code example] ### With Arguments [code example] ## ansible.builtin.shell (When You Need Shell Features) Runs commands **through** `/bin/sh`. Use when you need pipes, redirects, or shell features: [code example] ## When to Use Which ### Use command (default choice): [code example] ### Use shell (only when needed): [code example] ## Best Practices ### 1. Prefer Ansible Modules Over Shell [code example] ### 2. Use creates/removes for Idempotency [code example] ### 3. Use changed_when for Accurate Reporting [code example] ## Security Warning The `shell` module is vulnerable to injection if you pass untrusted input: [code example] --- *Explore 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible shell vs command vs raw — Execute Commands the Right Way URL: https://www.ansiblebyexample.com/articles/ansible-shell-vs-command-vs-raw Description: Compare Ansible shell, command, and raw modules. Learn when to use each, security implications, and best practices for running commands on remote hosts. ## Introduction Ansible has three modules for running commands on remote hosts: `command`, `shell`, and `raw`. Each has different capabilities and security implications. Using `shell` when `command` works, or `command` when a dedicated module exists, leads to less secure and less idempotent playbooks. ## Quick Comparison | Feature | `command` | `shell` | `raw` | |---------|-----------|---------|-------| | Shell processing | ❌ No | ✅ Yes | ✅ Yes | | Pipes `\|` | ❌ No | ✅ Yes | ✅ Yes | | Redirects `>` `<` | ❌ No | ✅ Yes | ✅ Yes | | Env variables `$HOME` | ❌ No | ✅ Yes | ✅ Yes | | Glob `*.log` | ❌ No | ✅ Yes | ✅ Yes | | Requires Python | ✅ Yes | ✅ Yes | ❌ No | | `creates`/`removes` | ✅ Yes | ✅ Yes | ❌ No | | `chdir` | ✅ Yes | ✅ Yes | ❌ No | | Security | ✅ Safest | ⚠️ Shell injection risk | ⚠️ Shell injection risk | | Idempotent by default | ❌ No | ❌ No | ❌ No | ## command — Safe Default `command` runs a command directly without a shell. No pipes, redirects, or shell features. [code example] ## shell — When You Need Shell Features `shell` runs through `/bin/sh`. Use only when you need pipes, redirects, or shell expansion. [code example] ### Shell Injection Warning [code example] ## raw — No Python Required `raw` sends a command over SSH without Python. Use only for bootstrapping or network devices. [code example] ## Decision Flowchart [code example] ## Prefer Dedicated Modules [code example] ## Make Commands Idempotent [code example] ## Related Articles - An... --- ## Ansible skip_tags — Exclude Tasks When Running Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-skip-tags-exclude-tasks-when-running-playbooks Description: Use --skip-tags to exclude specific tasks from Ansible playbook runs. Control execution granularity with tag inheritance, special tags, and CI/CD patterns. # Ansible skip_tags — Exclude Tasks When Running Playbooks ## Introduction `--skip-tags` lets you exclude tagged tasks from a playbook run without modifying the playbook. Skip slow tests in dev, bypass database tasks during frontend deploys, or exclude destructive operations in check mode. Combined with `--tags`, it gives fine-grained control over what executes. ## Quick Reference [code example] ## Basic Usage [code example] [code example] ## Tag Inheritance [code example] [code example] ## Special Tags [code example] [code example] ## Role Tags [code example] [code example] ## Common Patterns ### Development vs Production [code example] [code example] ### Destructive Operations [code example] [code example] ### CI/CD Pipeline [code example] ## List Available Tags [code example] ## ansible.cfg Default Skip Tags [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Task runs despite skip-tags | Check if task has `tags: always` | | Entire play skipped | Play-level tag matches skip-tags | | Handler not triggered | Handler's tag is skipped, or notifying task was skipped | | `--skip-tags` and `--tags` conflict | `--skip-tags` wins — if a task matches both, it's skipped | ## Best Practices 1. **Tag by function** — `install`, `deploy`, `configure`, `test`, `backup` 2. **Tag destructive tasks** — easy to skip in dry runs 3. **Use `always` sparingly** — only for truly mandatory tasks (facts gathering) 4. **Document your tags** —... --- ## Ansible skipped_reason Deprecated — Fix the Warning URL: https://www.ansiblebyexample.com/articles/ansible-skipped-reason-deprecated-fix-the-warning Description: Fix the 'skipped_reason value is deprecated' warning in Ansible. Migrate callback plugins and playbooks from skipped_reason to skip_reason for Ansible. # Ansible skipped_reason Deprecated — Fix the Warning ## Introduction Starting with ansible-core 2.20 (Ansible 14), the `skipped_reason` result key is deprecated in favor of `skip_reason`. If you see the warning `The 'skipped_reason' value is deprecated`, your callback plugins or custom code needs updating before this becomes an error in a future release. ## The Warning [code example] This appears when: - A callback plugin accesses `result._result['skipped_reason']` - Custom action plugins set `skipped_reason` in results - Third-party collections use the old key name ## The Fix ### Callback Plugins [code example] ### Backward-Compatible Fix [code example] ### Action Plugins [code example] ## Playbook Impact Standard playbooks using `when` conditions are **not affected** — this is an internal API change for plugin developers. However, if you register results and check `skipped_reason`: [code example] ## Check Your Code [code example] ## Common Affected Components | Component | Action | |-----------|--------| | Custom callback plugins | Replace `skipped_reason` → `skip_reason` | | Custom action plugins | Update return dict key | | Third-party collections | Update collection or wait for fix | | Playbooks using `register` | Add fallback: `skip_reason \| default(skipped_reason)` | | ansible.cfg callback settings | No change needed | ## Timeline | Version | Behavior | |---------|----------| | ansible-core ≤2.19 | `skipped_reason` works, no warning | | ansible-c... --- ## Ansible SNMP — Network Monitoring and Discovery URL: https://www.ansiblebyexample.com/articles/ansible-snmp-network-monitoring-and-discovery Description: Ansible SNMP guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible SNMP — Network Monitoring and Discovery ## Introduction Network Monitoring and Discovery. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible SNMP requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selecti... --- ## Ansible SNMP Monitoring Network Devices URL: https://www.ansiblebyexample.com/articles/ansible-snmp-monitoring-network-devices Description: Configure SNMP monitoring with Ansible for network devices, servers, and infrastructure including SNMPv3 security, trap receivers, and MIB management # Ansible SNMP Monitoring Network Devices SNMP (Simple Network Management Protocol) remains the standard for monitoring network devices — switches, routers, firewalls, UPS systems, and servers. Ansible automates SNMP configuration across your entire fleet, ensuring consistent community strings, SNMPv3 credentials, and trap destinations. ## Why Automate SNMP with Ansible - **Consistent security** — same SNMPv3 credentials everywhere - **Rapid deployment** — configure hundreds of devices at once - **Audit trail** — version-controlled SNMP configurations - **Compliance** — enforce SNMPv3 (disable v1/v2c) fleet-wide - **Integration** — pair with Prometheus SNMP exporter or Zabbix ## SNMPv3 Configuration on Linux Servers [code example] ## SNMPD Configuration Template `templates/snmpd.conf.j2`: [code example] ## Network Device SNMP Configuration For Cisco, Arista, and Juniper devices: [code example] ## Prometheus SNMP Exporter Integration [code example] ## SNMP Trap Receiver (snmptrapd) [code example] ## Security Hardening [code example] ## Troubleshooting | Problem | Cause | Solution | |---------|-------|----------| | "Timeout: No Response" | Firewall or wrong community | Check UDP 161, verify credentials | | "Authentication failure" | Wrong auth/priv passwords | Recreate SNMPv3 user | | "No Such Object" | OID not in view | Expand SNMP view to include OID tree | | Incomplete walk results | Agent maxGetbulk too low | Increase `maxGetbulkRepeats` | | High CPU from... --- ## Ansible SOC 2 — Security Audit Automation URL: https://www.ansiblebyexample.com/articles/ansible-soc-2-security-audit-automation Description: Ansible SOC 2 guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible SOC 2 — Security Audit Automation ## Introduction Security Audit Automation. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted deviations ## Conclu... --- ## Ansible splunk.enterprise Module Example: Automate Forwarder Deployment URL: https://www.ansiblebyexample.com/articles/ansible-splunk-enterprise-module-example-automate-forwarder-deployment Description: Runnable Ansible playbook example for the splunk.enterprise collection, showing Universal Forwarder install, configuration, and lifecycle automation. Red Hat announced `splunk.enterprise` alongside 11 other new content collections for AAP 2.7 at Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026). The collection targets Universal Forwarder lifecycle automation — install, configure, and manage forwarders across a fleet from a single playbook instead of touching each host by hand. ## Example playbook [code example] ## What it does The play targets a `splunk_forwarders` inventory group and runs four tasks in sequence. `uf_install` pulls down and installs the specified Universal Forwarder version, accepting the license and setting the local admin password non-interactively — the kind of step that's tedious to script by hand across dozens of hosts with shell one-liners and package managers. `uf_outputs` points the forwarder at your indexer tier so log data actually leaves the host, and `uf_deploymentclient` registers the forwarder with a deployment server so app bundles and configuration updates get pushed centrally rather than managed per-host. `uf_boot_start` makes sure the forwarder survives a reboot. The two configuration tasks notify a handler that restarts the forwarder service once, at the end of the play, instead of after every change. This mirrors the pattern used across the other collections announced at the same event — `microsoft.mecm` and `infra.mecm_ops` do the same idempotent install/configure/verify loop for Windows patching, and `hashicorp.vault` does it for secrets rotation. The idea behind all 12 col... --- ## Ansible splunk.es Module Example: Trigger Incident Response Playbook URL: https://www.ansiblebyexample.com/articles/ansible-splunk-es-module-example-trigger-incident-response-playbook Description: Runnable Ansible playbook example using the splunk.es collection to trigger Splunk Enterprise Security incident response and notable event workflows. The `splunk.es` collection was announced at Red Hat Tech Day Netherlands 2026 (Bunnik, 3 June 2026) as one of twelve new content collections shipping for AAP 2.7. It targets Splunk Enterprise Security incident workflows and response plan automation, letting playbooks react to notable events instead of waiting on an analyst to click a button. ## Example playbook [code example] ## What it does and why The playbook chains three `splunk.es` tasks against a notable event raised in Splunk Enterprise Security. First it pulls the event's details, then conditionally escalates urgency and reassigns ownership when the affected asset is flagged as high-criticality, and finally kicks off a named incident response plan (for example, an isolate-and-investigate workflow). In a real deployment this playbook is not run by hand — it's launched as a job template from AAP, invoked directly by Event-Driven Ansible when Splunk ES fires a notable event, or called from `splunk.itsi` correlation logic for closed-loop remediation. Running IR steps this way keeps the analyst's console and the automation in sync: the ticket updates in Splunk ES at the same time infrastructure changes happen, so there's a single source of truth for what was done and when. ## Notes / Gotchas - Store `splunk_es_user` and `splunk_es_password` in an AAP credential (or Vault, per the `hashicorp.vault` collection also announced at Red Hat Tech Day Netherlands 2026) — never in plaintext vars. - `server_port: 8089` is Splu... --- ## Ansible splunk.itsi Module Example: EDA-Triggered Remediation URL: https://www.ansiblebyexample.com/articles/ansible-splunk-itsi-module-example-eda-triggered-remediation Description: Runnable Ansible playbook for the splunk.itsi collection showing EDA-triggered closed-loop remediation for Splunk ITSI notable events. `splunk.itsi` is one of 12 new content collections announced for AAP 2.7 at Red Hat Tech Day Netherlands 2026 in Bunnik. It brings Splunk IT Service Intelligence (ITSI) into Event-Driven Ansible so a service-health notable event can trigger an automated fix without a human touching a ticket first. ## Example: rulebook + remediation playbook [code example] [code example] ## What this does The rulebook uses the `splunk.itsi.notable_event_source` EDA source plugin to poll a named ITSI service and fires when its health score drops below a threshold. The matched event lands in `ansible_eda.event`, so the remediation playbook can pull the ITSI service ID, KPI ID, and event ID straight out of the payload. The playbook acknowledges the notable event first (so nobody else double-remediates it), restarts the affected service, confirms recovery through a health check, then writes the resolution back into ITSI. That last step is the "closed-loop" part: the remediation status is visible in the same ITSI glass table the on-call team is already watching. ## Notes / Gotchas - Store `itsi_host` and `itsi_token` in an AAP credential type, not in plain vars — inject them at rulebook activation time. - The `until`/`retries` loop on the health check matters: without it, the playbook would close the notable event before confirming the restart actually fixed anything. - Scope `hosts:` in the remediation playbook tightly (inventory group per service) so a notable event for one service can't a... --- ## Ansible Squid — Deploy Forward Proxy and Cache Server URL: https://www.ansiblebyexample.com/articles/ansible-squid-forward-proxy-cache-server Description: Deploy Squid proxy with Ansible. Configure forward proxy, HTTP caching, ACLs, authentication, SSL bump, bandwidth throttling, and logging for enterprise. # Ansible Squid — Deploy Forward Proxy and Cache Server ## Introduction Squid is the most widely deployed forward proxy and web cache server. It reduces bandwidth usage, improves response times, and provides access control for outbound HTTP/HTTPS traffic. Ansible automates Squid deployment and ACL management across your infrastructure. ## Basic Squid Deployment [code example] ## Configuration Template [code example] ## Authentication [code example] ## Monitoring [code example] ## Troubleshooting [code example] ## Related Articles - Ansible HAProxy Load Balancer - Ansible Traefik Reverse Proxy - Ansible Firewalld UFW - Ansible iptables Firewall - Ansible Dnsmasq DNS DHCP ## Conclusion Squid remains the go-to forward proxy for enterprise networks. Ansible automates the entire lifecycle — installation, ACL management, cache tuning, authentication, and monitoring. Use templates for environment-specific configs and handlers for zero-downtime reloads. --- ## Ansible Squid Proxy — Forward and Reverse Proxy Setup URL: https://www.ansiblebyexample.com/articles/ansible-squid-proxy-forward-and-reverse-proxy-setup Description: Ansible Squid Proxy guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Squid Proxy — Forward and Reverse Proxy Setup ## Introduction Forward and Reverse Proxy Setup. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Squid Proxy requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags**... --- ## Ansible SSH Connection Timeout — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-ssh-connection-timeout-fix-and-solutions Description: Fix SSH connection timeouts from slow networks, firewalls, and DNS resolution. Tested on real machines with clear, copy-paste examples. # Ansible SSH Connection Timeout — Fix and Solutions ## Introduction Fix SSH connection timeouts from slow networks, firewalls, and DNS resolution. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix SSH connection timeouts from slow networks, firewalls, and DNS resolution. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible SSH Hardening — Secure Configuration Guide URL: https://www.ansiblebyexample.com/articles/ansible-ssh-hardening-secure-configuration-guide Description: Ansible SSH Hardening guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible SSH Hardening — Secure Configuration Guide ## Introduction Secure Configuration Guide. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted deviations ... --- ## Ansible SSH Key Authentication Failed — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-ssh-key-authentication-failed-fix-and-solutions Description: Troubleshoot SSH key authentication failures from permissions and agent issues. Tested on real machines with clear, copy-paste examples. # Ansible SSH Key Authentication Failed — Fix and Solutions ## Introduction Troubleshoot SSH key authentication failures from permissions and agent issues. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Troubleshoot SSH key authentication failures from permissions and agent issues. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible SSH Key Management URL: https://www.ansiblebyexample.com/articles/ansible-ssh-key-management-secure-access Description: Use Ansible to manage SSH keys, configure sshd, disable password authentication, set up key rotation, and harden SSH access across your infrastructure. ## Introduction SSH is Ansible's default connection method — managing SSH keys and hardening SSH configuration is fundamental. Ansible automates key distribution, sshd configuration, and security hardening across your entire fleet. ## Manage Authorized Keys [code example] ## authorized_key Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `user` | (required) | Username | | `key` | (required) | SSH public key or URL | | `state` | `present` | `present` or `absent` | | `exclusive` | `false` | Remove all other keys | | `path` | `~/.ssh/authorized_keys` | Key file path | | `key_options` | — | SSH key options (e.g., `command=`, `no-pty`) | | `manage_dir` | `true` | Create `.ssh` directory | | `comment` | — | Key comment | ## Key Options (Restrict Access) [code example] ## Generate SSH Keys [code example] ## Harden sshd Configuration [code example] ### Template-Based sshd Config [code example] ## Complete SSH Hardening Playbook [code example] ## SSH Key Rotation [code example] ## Troubleshooting ### Locked Out After Disabling Passwords Always ensure key-based access works BEFORE disabling passwords: [code example] ### Permission Errors [code example] ## Related Articles - Ansible user Module - Ansible Firewall Guide - Ansible Vault Guide - Ansible Best Practices ## Conclusion SSH key management is the foundation of secure Ansible automation. Use `authorized_key` to distribute keys, `exclusive: true` for strict control... --- ## Ansible SSH Password Auth — sshpass URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-use-ssh-with-passwords Description: Fix 'to use ssh with passwords you must install sshpass' error. Install sshpass on Ubuntu, RHEL, macOS, and configure Ansible SSH password auth safely. ## Introduction When you run an Ansible playbook using SSH password authentication, you may encounter this error: [code example] This means Ansible needs the `sshpass` utility to pass passwords non-interactively to SSH. Here's how to fix it — and why SSH keys are the better long-term solution. ## Quick Fix: Install sshpass ### RHEL / CentOS / Fedora [code example] ### Ubuntu / Debian [code example] ### macOS [code example] > **Note:** Homebrew doesn't include sshpass in the default tap because it encourages SSH key usage. Use a third-party tap as shown above. ### Arch Linux [code example] ### Verify Installation [code example] ## Using SSH Passwords in Ansible ### Method 1: Command Line (Testing Only) [code example] ### Method 2: Inventory Variables [code example] **Never store plaintext passwords in inventory files.** Use Ansible Vault: [code example] [code example] [code example] ### Method 3: ansible.cfg [code example] ## Why SSH Keys Are Better | Feature | Password Auth | SSH Key Auth | |---------|--------------|--------------| | Security | Weaker (brute-forceable) | Stronger (cryptographic) | | Convenience | Requires sshpass | Built into SSH | | Automation | Needs vault for secrets | Key file on controller | | Audit trail | Shared passwords | Unique keys per user | | Revocation | Change password everywhere | Remove one key | ### Switch to SSH Keys [code example] ### Ansible Inventory with Keys [code example] ## Troubleshooting ### sshpas... --- ## Ansible ssh_config Module — Manage SSH Client Configuration URL: https://www.ansiblebyexample.com/articles/ansible-ssh-config-module-manage-ssh-client-configuration Description: Add, modify, and remove SSH client config entries (~/.ssh/config) with Ansible. With clear, copy-paste, step-by-step examples. # Ansible ssh_config Module — Manage SSH Client Configuration ## Introduction The `community.general.ssh_config` module add, modify, and remove SSH client config entries (~/.ssh/config) with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.ssh_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check... --- ## Ansible SSL TLS Certificates — Generate and Deploy URL: https://www.ansiblebyexample.com/articles/ansible-ssl-tls-certificates-generate-and-deploy Description: Ansible SSL TLS Certificates guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible SSL TLS Certificates — Generate and Deploy ## Introduction Generate and Deploy. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible SSL TLS Certificates requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for s... --- ## Ansible stat — Check If Directory Exists URL: https://www.ansiblebyexample.com/articles/check-if-a-directory-exists-ansible-module-stat Description: Check if a directory exists in Ansible with stat module. Conditional task execution, create-if-missing patterns, and permission verification. ## Introduction Checking whether a file or directory exists before performing an action is one of the most common patterns in Ansible automation. The `ansible.builtin.stat` module retrieves file system status — existence, type, permissions, size, timestamps, and checksums — without modifying anything. Combined with `register` and `when`, it enables powerful conditional logic in your playbooks. ## Module Reference **Full name:** `ansible.builtin.stat` **Collection:** `ansible.builtin` ### Key Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | Full filesystem path to check | | `follow` | bool | No | Follow symlinks (default: `false`) | | `get_checksum` | bool | No | Calculate file checksum (default: `true`) | | `checksum_algorithm` | string | No | `md5`, `sha1` (default), `sha256`, `sha384`, `sha512` | | `get_mime` | bool | No | Get MIME type (default: `true`) | | `get_attributes` | bool | No | Get file attributes (default: `true`) | ### Key Return Values | Property | Type | Description | |----------|------|-------------| | `stat.exists` | bool | Whether the path exists | | `stat.isdir` | bool | True if path is a directory | | `stat.isreg` | bool | True if path is a regular file | | `stat.islnk` | bool | True if path is a symbolic link | | `stat.mode` | string | File permissions (e.g., `"0755"`) | | `stat.size` | int | File size in bytes | | `stat.uid` | int | Owner user ID | | `stat.gid` | int... --- ## Ansible stat Module — Check If Files & Directories Exist URL: https://www.ansiblebyexample.com/articles/check-if-a-file-exists-ansible-module-stat Description: Check if a file or directory exists with ansible.builtin.stat. Conditional execution, file attributes, checksum verification, and ownership. ## Introduction Checking whether a file exists before performing an action is one of the most common patterns in Ansible automation — skip a download if the file is already present, fail if a required config is missing, or verify a deployment artifact. The `ansible.builtin.stat` module retrieves file status information that you can use in conditionals. For Windows targets, use `ansible.windows.win_stat`. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | Full path to the file or directory | | `follow` | bool | No | Follow symlinks (default: `false`) | | `get_checksum` | bool | No | Calculate checksum (default: `true`) | | `checksum_algorithm` | string | No | `md5`, `sha1`, `sha224`, `sha256` (default), `sha384`, `sha512` | | `get_mime` | bool | No | Get MIME type (default: `true`) | | `get_attributes` | bool | No | Get file attributes (default: `true`) | ## Key Return Values | Return Value | Type | Description | |-------------|------|-------------| | `stat.exists` | bool | Whether the path exists | | `stat.isdir` | bool | Is a directory | | `stat.isreg` | bool | Is a regular file | | `stat.islnk` | bool | Is a symbolic link | | `stat.size` | int | File size in bytes | | `stat.mode` | string | Permissions (e.g., `0644`) | | `stat.uid` | int | Owner user ID | | `stat.gid` | int | Owner group ID | | `stat.checksum` | string | File checksum | | `stat.mtime` | float | Last modification ti... --- ## Ansible STIG Compliance — DoD Security Automation URL: https://www.ansiblebyexample.com/articles/ansible-stig-compliance-dod-security-automation Description: Ansible STIG Compliance guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible STIG Compliance — DoD Security Automation ## Introduction DoD Security Automation. This guide covers implementing security controls, automating compliance checks, and maintaining audit-ready infrastructure with Ansible playbooks. ## Overview Security automation with Ansible ensures consistent policy enforcement across your entire fleet. Instead of manually configuring each server, define your security baseline as code and apply it uniformly. ## Security Baseline Playbook [code example] ## Audit and Compliance Checks [code example] ## Firewall Configuration [code example] ## Compliance Report [code example] ## Handlers [code example] ## Scheduled Compliance Scans [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | SSH lockout | Ensure SSH key auth works before disabling passwords | | Audit log full | Configure log rotation for `/var/log/audit/` | | False positives | Tune rules to exclude known-good changes | | Performance impact | Schedule intensive scans during maintenance windows | ## Best Practices 1. **Start with a baseline** — apply minimum security standards to all hosts 2. **Layer controls** — combine network, host, and application security 3. **Automate scanning** — run compliance checks on schedule 4. **Version control everything** — track security policy changes in Git 5. **Test before enforcing** — use `--check --diff` mode first 6. **Document exceptions** — maintain a risk register for accepted deviations ## ... --- ## Ansible Stop Playbook on Error — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-stop-playbook-on-error-complete-guide Description: Control error behavior with any_errors_fatal and max_fail_percentage. Tested on real machines with clear, copy-paste examples. # Ansible Stop Playbook on Error — Complete Guide ## Introduction Control error behavior with any_errors_fatal and max_fail_percentage. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Control error behavior with any_errors_fatal and max_fail_percentage. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible Strategies — Linear Free Serial URL: https://www.ansiblebyexample.com/articles/ansible-playbook-strategies-linear-free-serial Description: Control how Ansible executes tasks across hosts. Linear vs free strategy, serial batches, max_fail_percentage, and rolling update patterns. ## Introduction Ansible's execution strategy controls how tasks run across multiple hosts. The default `linear` strategy runs each task on all hosts before moving to the next. `free` lets each host proceed independently. `serial` limits how many hosts are updated at once — essential for zero-downtime deployments. ## Strategy Types ### Linear (Default) Every host completes task 1 before any host starts task 2: [code example] [code example] ### Free Strategy Each host proceeds at its own pace: [code example] [code example] Use `free` when: - Tasks are independent per host - Hosts have different speeds - You want maximum parallelism ## Serial (Rolling Updates) Process hosts in batches: [code example] [code example] ### Serial with Percentages [code example] ### Progressive Serial (Canary) [code example] This is perfect for canary deployments — test on 1 host, then 5, then roll out to the rest. ## max_fail_percentage Stop the deployment if too many hosts fail: [code example] [code example] ## Practical Patterns ### Zero-Downtime Rolling Deploy [code example] ### Canary Deployment [code example] ### Database Migration (Single Run) [code example] ### Maintenance Window [code example] ## Comparison | Feature | linear | free | serial | |---------|--------|------|--------| | Sync between tasks | Yes | No | Yes (per batch) | | Host independence | No | Yes | Per batch | | Rolling update | No | No | Yes | | Canary deploy | No | No | Yes | | Speed | Medi... --- ## Ansible Structural Battery Composites Manufacturing Automation URL: https://www.ansiblebyexample.com/articles/ansible-structural-battery-composites-manufacturing Description: Automate structural battery composite manufacturing with Ansible. Manage MES systems, quality control, digital twins, and production line orchestration. ## Introduction Structural battery composites — materials that simultaneously bear mechanical loads and store electrical energy — are transforming vehicle, aerospace, and electronics design. Manufacturing these composites requires precise process control: layup sequencing, curing profiles, electrode integration, and quality inspection at every stage. Ansible automates the IT/OT infrastructure supporting this manufacturing: MES systems, digital twins, quality control pipelines, and production line orchestration. ## Manufacturing Infrastructure [code example] ## MES System Deployment [code example] ## Quality Control Pipeline [code example] ## Digital Twin Integration [code example] ## Environmental and Safety Monitoring [code example] ## Related Articles - Ansible Autonomous Industrial Systems - Ansible Digital Provenance C2PA - Ansible at Scale - Ansible Advanced Nuclear Technology ## Conclusion Structural battery composites require manufacturing infrastructure that bridges traditional composites production with electrochemical processing. Ansible automates the full stack: MES systems tracking multi-station production lines, AI-powered quality inspection, statistical process control, digital twin simulations, and cleanroom environmental monitoring. As structural batteries move from lab to production — enabling lighter EVs, longer-range drones, and energy-storing building panels — automated, traceable manufacturing infrastructure becomes the bottleneck to scale. --- ## Ansible Style Guide and Naming Conventions — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-style-guide-and-naming-conventions-complete-guide Description: Consistent naming conventions for Ansible variables, roles, tasks, handlers, and files. With tested, real-world examples. # Ansible Style Guide and Naming Conventions — Complete Guide ## Introduction Consistent naming conventions for Ansible variables, roles, tasks, handlers, and files. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Consistent naming conventions for Ansible variables, roles, tasks, handlers, and files. Start with the fundamentals, implement best... --- ## Ansible subversion Module — Deploy Code from SVN Repositories URL: https://www.ansiblebyexample.com/articles/ansible-subversion-module-deploy-code-from-svn-repositories Description: Checkout and update Subversion repositories on remote hosts with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible subversion Module — Deploy Code from SVN Repositories ## Introduction The `ansible.builtin.subversion` module checkout and update Subversion repositories on remote hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.builtin` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.builtin.subversion` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — ... --- ## Ansible sudo Password — Fix Missing Sudo and Become Errors URL: https://www.ansiblebyexample.com/articles/ansible-sudo-password-fix-missing-sudo-and-become-errors Description: Fix 'Missing sudo password' and become errors in Ansible. Configure ansible_become_pass, use vault-encrypted passwords, and set up passwordless sudo. # Ansible sudo Password — Fix Missing Sudo and Become Errors ## Introduction When Ansible runs tasks with `become: true`, it needs to escalate privileges via sudo. If the remote user requires a password for sudo and Ansible doesn't have it, you get "Missing sudo password" or "Incorrect sudo password" errors. This guide covers all methods to provide the sudo password — or eliminate the need for one. ## The Error [code example] [code example] ## Quick Fix Options [code example] ## Method 1: Command-Line Prompt [code example] ## Method 2: Inventory Variables [code example] ## Method 3: Vault-Encrypted Password (Recommended) [code example] [code example] [code example] [code example] ### Per-Host Vault Passwords [code example] ## Method 4: Passwordless Sudo (Best Practice) [code example] [code example] ### Limited Passwordless Sudo [code example] ## Method 5: ansible.cfg Configuration [code example] ## Playbook-Level Configuration [code example] ### Per-Task Become [code example] ## CI/CD Integration ### GitHub Actions [code example] ### Using Environment Variable [code example] [code example] ## Alternative Become Methods [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | `Missing sudo password` | No password provided, sudo requires one | Use `-K`, set `ansible_become_pass`, or configure NOPASSWD | | `Incorrect sudo password` | Wrong password | Verify password, check user exists on remote | | `sudo: a passwo... --- ## Ansible Sudo Password — Secure become URL: https://www.ansiblebyexample.com/articles/securing-ansible-managing-sudo-passwords-safely-and-non-interactively Description: Configure sudo password for Ansible become. Use --ask-become-pass, ansible-vault encrypted vars, and NOPASSWD sudoers safely. Privilege escalation in Ansible — running tasks as root or another user via `sudo` — is fundamental to most playbooks. This guide covers every method to handle sudo passwords securely, from interactive prompts to fully automated vault-encrypted approaches. ## How Ansible Privilege Escalation Works Ansible uses the `become` system for privilege escalation: [code example] ### Key Directives | Directive | Description | Default | |-----------|-------------|---------| | `become` | Enable privilege escalation | `false` | | `become_method` | Escalation method | `sudo` | | `become_user` | Target user to become | `root` | | `become_password` | Password for escalation | None | | `become_flags` | Additional flags for become method | None | These can be set at play, block, task, or role level. ## Method 1: Interactive Password Prompt (--ask-become-pass) The simplest approach — Ansible prompts you for the sudo password at runtime: [code example] **Pros:** Password never stored on disk. Simple to use. **Cons:** Requires manual input — not suitable for CI/CD or unattended automation. **Note:** The older `--ask-sudo-pass` flag is deprecated. Always use `--ask-become-pass` or `-K`. ## Method 2: Ansible Vault Encrypted Password Store the sudo password encrypted with Ansible Vault — the recommended approach for automation: ### Step 1: Create an Encrypted Variables File [code example] Add the password variable: [code example] ### Step 2: Reference in Inventory or Playbook The ... --- ## Ansible supervisorctl — Manage Supervisor Processes URL: https://www.ansiblebyexample.com/articles/ansible-supervisorctl-manage-supervisor-processes Description: Ansible supervisorctl guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible supervisorctl — Manage Supervisor Processes ## Introduction Manage Supervisor Processes. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible supervisorctl requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for... --- ## Ansible Swap Management — Create and Configure Swap Space URL: https://www.ansiblebyexample.com/articles/ansible-swap-management-create-configure Description: Manage Linux swap space with Ansible. Create swap files and partitions, configure swappiness, mount via fstab, monitor usage, and automate swap management. ## Introduction Swap space extends available memory by using disk as overflow. Ansible automates swap management — create swap files or partitions, set permissions, activate swap, persist via fstab, and tune swappiness. This is essential for servers that need memory safety nets without manual configuration. ## Create a Swap File [code example] ## Using fallocate (Faster) [code example] **Note:** `fallocate` doesn't work on all filesystems (e.g., XFS with copy-on-write). Use `dd` as the safe default. ## Swap Partition [code example] ## Resize Swap [code example] ## Remove Swap [code example] ## Monitor Swap Usage [code example] ## Conditional Swap Creation [code example] ## Recommended Swap Sizes | RAM | Swap (No Hibernation) | Swap (With Hibernation) | |---|---|---| | ≤ 2 GB | 2× RAM | 3× RAM | | 2–8 GB | Equal to RAM | 2× RAM | | 8–64 GB | ≥ 4 GB | 1.5× RAM | | > 64 GB | ≥ 4 GB | Not recommended | [code example] ## Troubleshooting ### "swapon: /swapfile: insecure permissions" Swap file must be `0600`: [code example] ### "swapon failed: Invalid argument" The file wasn't formatted with `mkswap`: [code example] ### Swap Not Persisting After Reboot Ensure fstab entry exists: [code example] ## Related Articles - Ansible sysctl Module - Ansible File Module - Ansible Mount Module - Ansible LVM Storage ## Conclusion Ansible manages swap with `dd` or `fallocate` to create the file, `mkswap` to format, `swapon` to enable, and `ansible.posix.mount` to p... --- ## Ansible synchronize Module — rsync Files Between Hosts URL: https://www.ansiblebyexample.com/articles/backup-with-rsync-local-to-remote-ansible-module-synchronize Description: Sync files with ansible.posix.synchronize (rsync). Local-to-remote, remote-to-remote, checksum verification, excludes, and delete mode examples. ## How to backing up with rsync with Ansible? ## Ansible backup with rsync > `ansible.posix.synchronize`: `synchronize` is a wrapper around rsync to make common tasks in your playbooks quick and easy. Today we're talking about the Ansible module `synchronize`. The full name is `ansible.posix.synchronize`, which means that is part of the collection targeting POSIX platforms. A wrapper around `rsync` to make common tasks in your playbooks quick and easy. rsync is a utility for efficiently transferring and synchronizing files between a computer and a storage drive and across networked computers by comparing the modification times and sizes of files. rsync must be installed on both the local and remote host. Currently, there are only a few connection types that support synchronize (ssh, paramiko, local, and docker) because a sync strategy has been determined for those connection types. ## Main Parameters - src _string_ - source path - absolute or relative - dest _string_ - destination path - absolute or relative - archive _boolean_ - mirrors the Rsync archive flag, enables recursive, links, perms, times, owner, group flags, and -D - rsync_opts _string_ - no/yes The parameter list is pretty wide but these are the most important options of `synchronize` module. The only mandatory parameters are "src" and "dest" parameters. The "src" parameter is mandatory and specifies the path on the source host that will be synchronized to the destination. The path can be absolute or relati... --- ## Ansible synchronize Module — Rsync Files Between Hosts URL: https://www.ansiblebyexample.com/articles/ansible-synchronize-module-rsync-files-between-hosts Description: Ansible synchronize Module guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible synchronize Module — Rsync Files Between Hosts ## Introduction Rsync Files Between Hosts. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible synchronize Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible Syntax Error in Playbook — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-syntax-error-in-playbook-fix-and-solutions Description: Diagnose and fix YAML syntax errors in Ansible playbooks and role files. Tested on real machines with clear, copy-paste examples. # Ansible Syntax Error in Playbook — Fix and Solutions ## Introduction Diagnose and fix YAML syntax errors in Ansible playbooks and role files. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Diagnose and fix YAML syntax errors in Ansible playbooks and role files. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible sysctl Module — Configure Linux Kernel Parameters URL: https://www.ansiblebyexample.com/articles/ansible-sysctl-configure-kernel-parameters Description: Use the Ansible sysctl module to tune Linux kernel parameters. Network settings, memory management, security hardening, and performance optimization. ## Introduction `ansible.posix.sysctl` sets Linux kernel parameters at runtime and persists them across reboots. Tune networking, memory, security, and performance — the same as editing `/etc/sysctl.conf` and running `sysctl -p`. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Kernel parameter name | | `value` | (required) | Parameter value | | `state` | `present` | `present` or `absent` | | `sysctl_set` | `false` | Apply immediately (sysctl -w) | | `reload` | `true` | Reload sysctl after change | | `sysctl_file` | `/etc/sysctl.conf` | Config file to update | | `ignoreerrors` | `false` | Ignore errors from sysctl command | ## Network Tuning [code example] ## Security Hardening [code example] ## Memory Tuning [code example] ## Application-Specific Tuning ### Docker/Kubernetes [code example] ### PostgreSQL [code example] ### Redis [code example] ### Elasticsearch [code example] ## Custom sysctl File [code example] ## Complete Server Hardening Playbook [code example] ## Troubleshooting ### "sysctl: permission denied" Ensure `become: true` is set — sysctl requires root. ### "Key not found" The kernel module might not be loaded: [code example] ## Related Articles - Ansible Firewall Guide - Ansible service Module - Ansible Playbook Guide - Ansible Docker Guide ## Conclusion `ansible.posix.sysctl` tunes the Linux kernel for security, networking, and perfo... --- ## Ansible sysctl Module — Kernel Tuning URL: https://www.ansiblebyexample.com/articles/set-sysctl-kernel-parameters-ansible-module-sysctl Description: Set and persist Linux kernel parameters with ansible.posix.sysctl. Playbook examples for vm.swappiness, ip_forward, file-max, and more. ## How to set the sysctl kernel parameters with Ansible? Use the `ansible.posix.sysctl` module to set and persist Linux kernel parameters in `/etc/sysctl.conf`, with an option to apply the change immediately using `sysctl_set` and `reload`. ## Ansible set sysctl kernel parameters - ansible.posix.sysctl - Manage entries in sysctl.conf Today we're talking about the Ansible module sysctl. The full name is `ansible.posix.sysctl`, which means that is part of the collection of modules "ansible.posix" to interact with POSIX platforms. The purpose of the module is to manage entries in the `sysctl.conf` file. ## Parameters - name string (key) - Parameter name - value string - Parameter value - reload boolean - yes/no - state string - present/absent - sysctl_file string - "/etc/sysctl.conf" - sysctl_set string - no/yes - sysctl -w - ignoreerrors boolean - no/yes Let me summarize the parameters of sysctl module. The only required is "name", where you specify the parameter name to access or edit. The parameter "value" sets the value of the sysctl parameter. The parameter "reload", default to yes, reload the configuration file if any changes occur. The parameter "state" sets the presence or absence of the parameter in the sysctl file. The parameter "sysctl_file" allows specifying the configuration file for sysctl, default to "/etc/sysctl.conf". The parameter "sysctl_set" allows you to configure a parameter permanently, that survives after reboot. The parameter "ignoreerrors" allow ... --- ## Ansible systemd Module — Services, Units & Timers URL: https://www.ansiblebyexample.com/articles/ansible-systemd-manage-units-timers-services Description: Use Ansible to manage systemd units, create custom services, configure timers, enable/disable units, and troubleshoot service failures. ## Introduction systemd manages services on modern Linux distributions. Ansible's `systemd_service` module controls units — start, stop, enable, mask, and reload. Combined with templates, you can deploy custom services, timers, and socket-activated units. ## Basic Service Management [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `name` | Unit name | | `state` | `started`, `stopped`, `restarted`, `reloaded` | | `enabled` | Start on boot (`true`/`false`) | | `daemon_reload` | Reload systemd manager config | | `masked` | Mask unit (prevent starting) | | `scope` | `system`, `user`, `global` | | `no_block` | Don't wait for completion | ## Create Custom Service [code example] ### Service Unit Template [code example] ## Systemd Timers (Cron Replacement) [code example] ### Timer Schedules | OnCalendar | Schedule | |------------|----------| | `*-*-* 02:00:00` | Daily at 2 AM | | `Mon *-*-* 09:00:00` | Monday 9 AM | | `*-*-01 00:00:00` | First of each month | | `hourly` | Every hour | | `daily` | Every day | | `weekly` | Every week | | `*-*-* *:00/15:00` | Every 15 minutes | ## Mask/Unmask Services [code example] ## Socket Activation [code example] ## Practical Pattern: Java Application [code example] [code example] ## Troubleshooting ### Service Won't Start [code example] ### "Unit file changed on disk" Always reload after changing unit files: [code example] ## Related Articles - Ansible service Module - Ansible Jinja... --- ## Ansible Tags — Run or Skip Tasks URL: https://www.ansiblebyexample.com/articles/what-are-ansible-tags Description: Use Ansible tags to selectively run or skip tasks. Examples with --tags, --skip-tags, always, never, and tag inheritance in roles and includes. Ansible tags are a feature that allows users to selectively control which tasks in a playbook are executed. They are an essential tool for optimizing automation workflows, especially in complex playbooks. This article explains what Ansible tags are, their usage, and best practices for implementing them. ## What Are Ansible Tags? Tags in Ansible are **labels** assigned to tasks or plays within a playbook. They enable users to execute specific parts of a playbook, skipping others based on the tags provided during execution. ### Key Features: - **Selective Execution**: Run only tasks with specified tags. - **Improved Efficiency**: Save time by skipping unnecessary tasks. - **Flexibility**: Apply multiple tags to a single task or play. ## How Do Ansible Tags Work? Tags are added to tasks, roles, or entire plays using the `tags` keyword. During playbook execution, you can specify which tags to include or skip using command-line options. ### Example: Using Tags in a Playbook [code example] In this example: - The `install` tag applies to the Nginx installation task. - The `start` tag applies to the task starting the Nginx service. - Both tasks share the `web` tag. ### Running Tagged Tasks To execute only tasks with a specific tag, use the `--tags` option: [code example] ### Skipping Tags To skip tasks with specific tags, use the `--skip-tags` option: [code example] ## Tagging Roles and Plays Tags can also be applied to roles and entire plays for broader control. ### E... --- ## Ansible Tags — Run Specific Tasks from a Playbook URL: https://www.ansiblebyexample.com/articles/ansible-tags-run-specific-tasks Description: Use Ansible tags to selectively run or skip tasks. Tag tasks, roles, plays, and imports. Run with --tags and --skip-tags for targeted execution. ## Introduction Tags let you run a subset of tasks from a playbook. Instead of running everything, target only what you need — just the config deployment, just the packages, or just the service restarts. Essential for large playbooks and iterative development. ## Tag a Task [code example] ## Run and Skip Tags [code example] ## Multiple Tags on a Task [code example] ## Special Tags ### always Tasks tagged `always` run even when you use `--tags` (unless explicitly skipped): [code example] [code example] ### never Tasks tagged `never` only run when explicitly requested: [code example] [code example] ## Tag a Block [code example] ## Tag a Role [code example] [code example] ## Tag a Play [code example] [code example] ## Tag with include/import [code example] This is an important distinction: | | import_tasks | include_tasks | |---|---|---| | Tag inheritance | Tags flow to all imported tasks | Tags only on the include line | | When evaluated | Parse time (static) | Runtime (dynamic) | | Best for | Applying tags to a whole file | Conditional includes | ## Practical Patterns ### Deployment Workflow [code example] [code example] ### Debug Tag [code example] [code example] ## Best Practices 1. **Use consistent tag names** across playbooks: `packages`, `config`, `services`, `deploy`, `security` 2. **Tag at the right level** — don't over-tag individual tasks; tag blocks or roles 3. **Use `always` sparingly** — only for truly essential tasks (fact gath... --- ## Ansible tempfile Module — Temp Files URL: https://www.ansiblebyexample.com/articles/ansible-tempfile-module-create-temporary-files-safely Description: Ansible tempfile Module guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible tempfile Module — Create Temporary Files Safely ## Introduction Create Temporary Files Safely. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible tempfile Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ta... --- ## Ansible template — Jinja2 Config Files URL: https://www.ansiblebyexample.com/articles/apply-a-file-template-ansible-module-template Description: Use the Ansible template module to deploy dynamic configuration files with Jinja2. Variables, loops, conditionals, and real-world template examples. How to apply a file template to the target host with Ansible? This is extremely useful for service configuration files, placeholder web pages, reports, and so much more use cases. ## Ansible applies a file template - ansible.builtin.template - Template a file out to a target host - ansible_managed, template_host, template_uid, template_path, template_fullpath, template_destpath, and template_run_date Today we're talking about Ansible module template. The full name is ansible.builtin.template, it's part of `ansible-core` and is included in all Ansible installations. It templates a file out to a target host. Templates are processed by the Jinja2 templating language. Also you could use also some special variables in your templates: `ansible_managed`, `template_host`, `template_uid`, `template_path`, `template_fullpath`, `template_destpath`, and `template_run_date`. It supports a large variety of Operating Systems. For basic text formatting, use the Ansible `ansible.builtin.copy` module or for empty file Ansible `ansible.builtin.file` module. For Windows, use the `ansible.windows.win_template` module instead. ## Parameters - `src` path - template ("`templates/`" dir) - `dest` path - target location - `validate` string - validation command before ("`%s`") - `backup` boolean - no/yes - `mode`/`owner`/`group` - permission - `setype`/`seuser`/`selevel` - SELinux Let me highlight the most useful parameters for template module. The only required parameters are "src" and "dest". T... --- ## Ansible template — Jinja2 Module URL: https://www.ansiblebyexample.com/articles/what-are-ansible-templates Description: Use Ansible template module with Jinja2 to generate dynamic configuration files. Variables, loops, conditionals, and filters with playbook examples. Ansible templates are a powerful feature that enables dynamic generation of configuration files and scripts during automation workflows. Using Jinja2 templating, Ansible templates allow for flexibility and adaptability in creating infrastructure and application configurations. This article explains what templates are, how they work, and their benefits. ## What Are Ansible Templates? Ansible templates are **Jinja2-based files** used to create dynamic configuration files or scripts. These templates can include variables, conditionals, loops, and filters, allowing for highly customized output tailored to the specific needs of managed systems. ### Key Features: - **Dynamic Content**: Generate files with runtime-specific data. - **Customization**: Use variables and logic to create tailored configurations. - **Reusability**: Write once and reuse templates across multiple tasks. ## How Do Ansible Templates Work? Templates are stored as `.j2` files and processed using Ansible’s `template` module, which replaces variables and applies logic before deploying the file to the target system. ### Example Template File **nginx.conf.j2**: [code example] ### Example Playbook Using a Template [code example] This playbook: 1. Substitutes variables (e.g., `{{ nginx_port }}`) with their defined values. 2. Saves the rendered configuration file to `/etc/nginx/nginx.conf`. ## Common Features of Templates ### 1. **Variables**: Insert variables into templates for dynamic values. [code e... --- ## Ansible Template File Not Found — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-template-file-not-found-fix-and-solutions Description: Fix template not found errors from wrong paths and role directory structure. With clear, copy-paste, step-by-step examples. # Ansible Template File Not Found — Fix and Solutions ## Introduction Fix template not found errors from wrong paths and role directory structure. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix template not found errors from wrong paths and role directory structure. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible template Module — Generate Config Files with Jinja2 URL: https://www.ansiblebyexample.com/articles/ansible-template-module-jinja2-config-files Description: Use the Ansible template module to generate dynamic config files from Jinja2 templates. Variables, loops, conditionals, filters, and validation with. ## Introduction The `ansible.builtin.template` module processes Jinja2 templates and deploys the rendered output to remote hosts. It's how you generate dynamic configuration files — inject hostnames, IP addresses, port numbers, environment-specific values, and computed settings into any config format. ## Basic Syntax [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | Path to Jinja2 template (`.j2`) | | `dest` | (required) | Remote destination path | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions | | `backup` | `false` | Backup existing file before overwriting | | `validate` | — | Validation command (`%s` = temp file) | | `force` | `true` | Overwrite even if destination exists | | `newline_sequence` | `\n` | Line ending: `\n`, `\r`, `\r\n` | | `trim_blocks` | `true` | Remove first newline after block tags | | `lstrip_blocks` | `false` | Strip leading whitespace from block lines | ## Simple Template Playbook: [code example] `templates/nginx.conf.j2`: [code example] ## Jinja2 Variables All Ansible variables are available in templates — facts, vars, registered results: [code example] ## Conditionals in Templates [code example] ## Loops in Templates [code example] ## Filters [code example] ## Practical Examples ### Application Config File [code example] `templates/app.yml.j2`: [code example] ### Hosts File [code example] ### Sudoers File (... --- ## Ansible template Module — Generate Configuration Files with Jinja2 URL: https://www.ansiblebyexample.com/articles/ansible-template-module-jinja2-configuration Description: Use the Ansible template module to generate dynamic configuration files with Jinja2. Variables, loops, conditionals, and filters in templates. ## Introduction `ansible.builtin.template` processes Jinja2 template files and deploys them to remote hosts. Unlike `copy`, templates support variables, loops, conditionals, and filters — making them the standard way to generate dynamic configuration files. ## Basic Usage [code example] Template file: [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | Template file on controller (`.j2`) | | `dest` | (required) | Destination path on remote | | `owner` | — | File owner | | `group` | — | File group | | `mode` | — | File permissions | | `backup` | `false` | Backup before overwrite | | `validate` | — | Validation command | | `force` | `true` | Overwrite if different | | `newline_sequence` | `\n` | Line ending style | | `trim_blocks` | `true` | Remove first newline after block tag | | `lstrip_blocks` | `false` | Strip leading whitespace from block lines | ## Variables in Templates [code example] ## Conditionals [code example] ## Loops [code example] [code example] ## Filters [code example] [code example] ## Practical Examples ### Systemd Service File [code example] ### SSH Config [code example] ### Database Config [code example] ### Environment File [code example] ## Template with Validation [code example] ## Advanced Patterns ### Include Other Templates [code example] ### Macros (Reusable Blocks) [code example] ## template vs copy | Scenario | Module | |----------|------... --- ## Ansible template Module: Generate Config Files with Jinja2 URL: https://www.ansiblebyexample.com/articles/ansible-template-module-generate-config-files-with-jinja2 Description: Master the Ansible template module — generate dynamic config files with Jinja2 variables, loops, and conditionals. Practical examples for nginx, systemd,. ## The ansible.builtin.template Module The `template` module processes Jinja2 template files (`.j2`) and deploys the rendered output to remote hosts. Variables, loops, and conditionals make your configs dynamic. ## Basic Usage **Template file** (`templates/nginx.conf.j2`): [code example] **Playbook:** [code example] ## Variables in Templates ### From Playbook vars [code example] [code example] ### From Ansible Facts [code example] ## Conditionals [code example] ## Loops [code example] [code example] ### Loop with Index [code example] ## Filters [code example] ## Practical Examples ### systemd Service File [code example] ### Environment File [code example] ### SSH Config [code example] ## Template with Validation [code example] ## Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `src` | Template file path | `templates/app.conf.j2` | | `dest` | Remote destination | `/etc/app/config` | | `mode` | File permissions | `'0644'` | | `owner` | File owner | `root` | | `group` | File group | `root` | | `validate` | Validation command | `nginx -t -c %s` | | `backup` | Create backup | `true` | | `force` | Overwrite always | `true` | --- *Browse 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible terminology — What is an Ansible Playbook? URL: https://www.ansiblebyexample.com/articles/what-is-an-ansible-playbook Description: A step-by-step guide inside the Ansible Playbook anatomy: play, tasks, modules, conditional, loop, handler, variable, list. ## What is an Ansible Playbook? I will show you a live Playbook with some simple Ansible code. ## Ansible Playbook - blueprint for automation - YAML format - Ansible language The Ansible Playbook is the blueprint for your automation. The Ansible Playbook enables you to execute any, again again, operation in a specified order. It's like a recipe book for someone who likes to cook a cake. Every ingredient needs to be added in a specific order at a particular moment of the execution. The code is human-readable in YAML format, a well-known easy-to-read coding format. Every line of coding is the Ansible language that is changed a little bit yearly, but the principles are always the same. Like all programming languages, you can declare variables, include other files, execute actions on conditions, and repeat with loops. Other particular actions, called handlers, execute only when another task is performed. You can execute your Ansible Playbook using the `ansible-playbook` command line utility included in any ansible installation. When the execution is successful, you obtain a green result, otherwise a failure with a relative error. ## Links - https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html ## Playbook A step-by-step guide inside the Ansible Playbook anatomy. ### code - example.yml [code example] ### execution [code example] ## Conclusion Now you know what an Ansible Playbook is and how to use it. You know how to use it based on your use case. --- ## Ansible Ternary Filter — If-Else in One Line (With Examples) URL: https://www.ansiblebyexample.com/articles/ansible-ternary-operator-in-jinja2-templates Description: Master the Ansible ternary filter with copy-paste examples. Syntax, nested ternary, default values, common errors, and comparison with Jinja2 inline. ## Introduction The ternary filter is Ansible's one-line if-else — choose between two values based on a condition without verbose `when` blocks or multi-line Jinja2 `{% if %}` statements. But many users hit the `template error: unexpected character` error because they use JavaScript-style syntax. Here's the correct way. ## The Wrong Way (JavaScript-style) [code example] Error: [code example] ## The Correct Way: Ternary Filter [code example] ### Syntax [code example] **Three rules:** 1. Wrap the condition in **parentheses** 2. Use the **pipe** `|` before `ternary` 3. `ternary` is a **filter**, not a function ## Ternary vs Inline If-Else Jinja2 also supports inline `if-else`: [code example] Both are equivalent. The ternary filter is better when chaining with other filters: [code example] ## Ternary with Three Values (Null/Undefined) The ternary filter accepts an optional third argument for `None`/undefined: [code example] | `debug` value | Result | |---------------|--------| | `true` | `verbose` | | `false` | `quiet` | | `None` / undefined | `default_mode` | ## Common Patterns ### Boolean Variables [code example] ### Default + Ternary (Undefined-Safe) [code example] ### Nested Ternary [code example] ### Select from Mapping (Alternative to Nested Ternary) [code example] ### In Templates (.j2 files) [code example] ### With set_fact [code example] ### In Task Parameters [code example] ## Common Mistakes | Mistake | Fix | |---------|-----| | `env... --- ## Ansible ternary Filter — Inline If-Else for Variables URL: https://www.ansiblebyexample.com/articles/ansible-ternary-filter-inline-if-else-examples Description: Use the Ansible ternary filter for inline conditional logic in Jinja2 templates. Syntax, nested ternary, default values, and common use cases with. ## Introduction The `ternary` filter is Ansible's inline if-else — it returns one value when a condition is true and another when false. It's cleaner than writing full `{% if %}` blocks when you just need to pick between two values. [code example] ## Basic Syntax [code example] ## Simple Examples [code example] ## Ternary in Templates [code example] `nginx.conf.j2`: [code example] ## Ternary with Variables [code example] ## Three-Argument Ternary (Null Handling) The third argument handles `None`/`undefined` values: [code example] ## Nested Ternary Chain ternary filters for multiple conditions (use sparingly — readability drops fast): [code example] For more than 2-3 conditions, use a dictionary lookup instead: [code example] ## Common Use Cases ### Package Installation [code example] ### Conditional Service State [code example] ### Dynamic Paths [code example] ### Boolean to String [code example] ## Ternary vs Jinja2 if-else [code example] | Approach | Best For | |----------|----------| | `ternary` | Simple true/false with clear values | | Jinja2 inline `if` | When the condition reads more naturally | | Jinja2 `{% if %}` block | Complex multi-branch logic | ## Troubleshooting ### "ternary expects 2 or 3 arguments" You passed the wrong number of arguments: [code example] ### Unexpected Result with Strings Non-empty strings are truthy in Jinja2: [code example] ### Integer 0 is Falsy [code example] ## Related Articles - Ansible Jinja2 Fi... --- ## Ansible Terraform Integration — Infrastructure as Code URL: https://www.ansiblebyexample.com/articles/ansible-terraform-integration-infrastructure-as-code Description: Ansible Terraform Integration guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Terraform Integration — Infrastructure as Code ## Introduction Infrastructure as Code. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Terraform Integration requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible Test Plugins — Validate Data in Conditionals URL: https://www.ansiblebyexample.com/articles/ansible-test-plugins-validate-data-in-conditionals Description: Ansible Test Plugins guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Test Plugins — Validate Data in Conditionals ## Introduction Validate Data in Conditionals. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Test Plugins requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** f... --- ## Ansible Text Capitalization — upper, lower, title, capitalize Filters URL: https://www.ansiblebyexample.com/articles/automating-text-capitalization-with-ansible-playbooks Description: Transform text capitalization in Ansible with upper, lower, title, and capitalize Jinja2 filters. Complete guide with practical examples for string. ## Introduction Text manipulation is a common need in Ansible playbooks — normalizing hostnames, formatting output, creating consistent naming conventions, or transforming user input. Ansible's Jinja2 template engine provides powerful string filters for case conversion and text transformation. ## String Case Filters Ansible inherits all Jinja2 string filters plus adds its own. Here are the essential case transformation filters: | Filter | Input | Output | Description | |--------|-------|--------|-------------| | `upper` | `hello world` | `HELLO WORLD` | All uppercase | | `lower` | `Hello World` | `hello world` | All lowercase | | `capitalize` | `hello world` | `Hello world` | First char upper, rest lower | | `title` | `hello world` | `Hello World` | First char of each word upper | ## Basic Usage [code example] ## Practical Use Cases ### Normalize Hostnames [code example] ### Create Consistent File Names [code example] ### Format Output Messages [code example] ### User Input Normalization [code example] ### Conditional Logic with Case Normalization [code example] ## Advanced String Filters Beyond case conversion, Ansible/Jinja2 provides additional string manipulation: [code example] ## Complete Playbook: Naming Convention Enforcement [code example] ## Filter Chaining Patterns [code example] ## Related Articles - Ansible Jinja2 Templates — Full template guide - Ansible Filter Plugins — All filter plugins - Ansible regex_replace Filter — Regex patterns ... --- ## Ansible Text Transformation Filters URL: https://www.ansiblebyexample.com/articles/harnessing-the-power-of-ansible-uppercase-text-automation Description: Transform text in Ansible with upper, lower, capitalize, title, replace, regex_replace, and other Jinja2 string filters. Complete reference with practical. ## Introduction Jinja2 string filters in Ansible transform text in variables, templates, and task parameters — uppercase, lowercase, title case, replace, regex, and more. These filters work everywhere Jinja2 expressions are used: playbooks, templates, and inventory variables. ## Case Transformation Filters ### upper — Convert to Uppercase [code example] ### lower — Convert to Lowercase [code example] ### capitalize — First Letter Uppercase [code example] ### title — Title Case [code example] ## String Manipulation Filters ### replace [code example] ### regex_replace [code example] ### regex_search [code example] ## Whitespace and Formatting ### trim [code example] ### center / ljust / rjust (in templates) [code example] ### wordwrap [code example] ### truncate [code example] ## Practical Examples ### Normalize Hostnames [code example] ### Generate Config from Variables [code example] ### Dynamic File Paths [code example] ### Conditional Formatting in Templates [code example] ### Sanitize User Input [code example] ## Complete Filter Reference | Filter | Input | Output | |--------|-------|--------| | `upper` | `hello` | `HELLO` | | `lower` | `HELLO` | `hello` | | `capitalize` | `hello world` | `Hello world` | | `title` | `hello world` | `Hello World` | | `replace('a','b')` | `cat` | `cbt` | | `regex_replace` | Pattern-based replace | — | | `regex_search` | Extract match | — | | `trim` | ` hi ` | `hi` | | `truncate(10)` | `long text here`... --- ## Ansible throttle — Limit Concurrent Task Execution Across Hosts URL: https://www.ansiblebyexample.com/articles/ansible-throttle-limit-concurrent-task-execution Description: Control how many hosts run a task simultaneously with Ansible throttle. Prevent resource exhaustion during rolling updates, API calls, and database. ## Introduction The `throttle` keyword in Ansible limits how many hosts can execute a specific task at the same time, regardless of the `forks` setting. While `forks` controls the global parallelism and `serial` controls batch size for plays, `throttle` gives per-task concurrency control. Use it to prevent overloading a shared resource like a database, API endpoint, load balancer, or license server during automation. ## Syntax [code example] ## throttle vs serial vs forks [code example] [code example] ## Basic Examples ### Rate-Limit API Calls [code example] ### Rolling Service Restart [code example] ### Database Migration [code example] ### License Server Protection [code example] ## throttle with Blocks [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Strategies — linear, free, debug - Ansible async and poll - Ansible Playbook Best Practices - Ansible Error Handling - Ansible At Scale Performance Tuning ## Conclusion Use `throttle` when a specific task needs rate-limiting but the rest of the play can run at full parallelism. Set `throttle: 1` for operations that must be strictly sequential (database migrations, load balancer drain), `throttle: N` for resources with a known concurrency limit (APIs, license servers), and combine with `block` to throttle a group of related tasks together. It's the surgical tool for concurrency control — more precise than `serial`, more targeted than reducing `forks`. --- ## Ansible Throttle — Scale Safely URL: https://www.ansiblebyexample.com/articles/networking-throttle-strategies-for-managing-3000-servers-with-ansible Description: Learn how to effectively manage networking throttles and optimize performance when automating tasks across 3000 servers with Ansible, including practical. ## Introduction Managing a large-scale Ansible deployment with 3000 servers can lead to network bottlenecks, extended wait times, and task failures. This challenge becomes even more critical when performing resource-heavy operations, such as Product Lifecycle Management (PLM) upgrades. This article provides practical strategies to implement network throttling and optimize performance in Ansible. --- ## Key Networking Challenges ### 1. **Network Saturation** Simultaneously connecting to thousands of servers can overwhelm the network, leading to timeouts and retries. ### 2. **Server Hangs** Tasks like `yum` updates can hang or fail when network congestion increases. ### 3. **Unpredictable Latency** Variable performance across servers makes achieving consistent task execution difficult. --- ## Solutions for Networking Throttling ### 1. **Control Parallelism with Forks** Adjust Ansible's `forks` setting to control the number of concurrent tasks. **Configuration Example:** [code example] ### 2. **Batch Processing with `serial`** Limit the number of hosts being processed simultaneously. **Example Playbook:** [code example] ### 3. **Introduce Pauses Between Batches** Prevent network saturation by adding a delay between task executions. **Example Playbook with Pause:** [code example] ### 4. **Use Asynchronous Tasks** Prevent tasks from hanging by running them asynchronously and polling for results. **Async Task Example:** [code example] --- ## Strategies to Enhance ... --- ## Ansible throttle: Control Task Concurrency Across Hosts URL: https://www.ansiblebyexample.com/articles/ansible-throttle-control-task-concurrency-across-hosts Description: Learn how to use Ansible throttle to limit task concurrency. Control how many hosts run a task simultaneously — essential for database migrations, API. ## What is Ansible throttle? The `throttle` keyword limits how many hosts can execute a specific task at the same time — even if `forks` or `serial` allows more. This is essential when a task hits a shared resource (database, API, load balancer) that can't handle many simultaneous connections. ## Basic Syntax [code example] ## throttle vs serial vs forks | Setting | Scope | What it controls | |---------|-------|-----------------| | `forks` | Global (ansible.cfg) | Max SSH connections Ansible opens | | `serial` | Play-level | How many hosts per batch | | `throttle` | Task-level | Max concurrent hosts for one task | [code example] ## Practical Examples ### API Rate Limiting [code example] ### Database Operations [code example] ### Load Balancer Registration [code example] ### Certificate Renewal [code example] ### Rolling Restart Without Downtime [code example] ## Key Rules 1. `throttle` cannot be higher than `serial` or `forks` — it only reduces concurrency, never increases it 2. `throttle` is set per-task, not per-play 3. Value must be a positive integer 4. Works with all strategies (`linear`, `free`, `host_pinned`) ## When to Use throttle - **API rate limits** — external services cap concurrent requests - **Database migrations** — prevent lock conflicts - **License servers** — limited concurrent connections - **Shared storage** — avoid I/O bottleneck - **Certificate authorities** — rate-limited issuance - **Load balancer registration** — gradual traffic... --- ## Ansible timezone — Set System Timezone URL: https://www.ansiblebyexample.com/articles/ansible-timezone-module-set-system-timezone Description: Use the Ansible timezone module to set system timezone, configure NTP, and synchronize time across your infrastructure. With tested, real-world examples. ## Introduction `community.general.timezone` sets the system timezone on Linux hosts. Consistent time configuration prevents authentication failures, log correlation issues, cron scheduling bugs, and certificate validation errors. ## Basic Usage [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `name` | Timezone name (e.g., `UTC`, `America/New_York`) | | `hwclock` | Hardware clock: `UTC` or `local` | ## Common Timezones | Region | Timezone | |--------|----------| | UTC | `UTC` | | US East | `America/New_York` | | US Central | `America/Chicago` | | US Pacific | `America/Los_Angeles` | | UK | `Europe/London` | | Germany | `Europe/Berlin` | | Japan | `Asia/Tokyo` | | India | `Asia/Kolkata` | | Australia | `Australia/Sydney` | List all available timezones: [code example] ## Set Timezone from Variable [code example] Inventory: [code example] ## Configure NTP (Time Synchronization) ### Chrony (Modern — RHEL 8+, Ubuntu 20.04+) [code example] [code example] ### systemd-timesyncd (Lightweight) [code example] ## Complete Time Configuration Playbook [code example] ## Ansible Date/Time Facts [code example] ## Windows Timezone [code example] ## Troubleshooting ### "Timezone not found" [code example] ### Time Drift After Configuration [code example] ## Related Articles - Ansible hostname Module - Ansible cron Module - Ansible sysctl Module - Ansible systemd Module ## Conclusion Set timezone with `community.general.timezon... --- ## Ansible Tips’n’Tricks: Defining –extra-vars as JSON URL: https://www.ansiblebyexample.com/articles/defining-extra-vars-as-json Description: A practical guide on using JSON for Ansible’s extra-vars to enhance efficiency and test flexibility. Tested on real machines with clear, copy-paste examples. ## Introduction In the realm of Ansible automation, managing variables effectively can save time and reduce errors. A lesser-known but powerful feature is using JSON files with the `--extra-vars` option to pass parameters to your playbooks. This approach is particularly handy when testing multiple parameters without altering global configurations, such as those stored in `group_vars` or `host_vars`. This article explains how to define `--extra-vars` as JSON, streamlining your workflow and maintaining version control hygiene. --- ## The Basics: `--extra-vars` Ansible allows variables to be overridden on the command line using the `--extra-vars` option. The most common method is passing a space-separated list of `key=value` pairs. However, for extensive variables, this can become unwieldy and error-prone. JSON files provide a clean and structured alternative. --- ## Example Playbook Consider the following simple playbook, `main.yml`: [code example] When executed, the variables output their default values: [code example] --- ## Overriding Variables To override variables, use `--extra-vars`: [code example] The output reflects the overridden values. However, this method becomes cumbersome with many variables. --- ## Using JSON for `--extra-vars` Instead of typing variables inline, create a JSON file, `params.json`: [code example] Run the playbook with: [code example] Here, `@params.json` tells Ansible to load the variables from the specified file. ### Outpu... --- ## Ansible Tomcat — Deploy Java Applications and Servlet Containers URL: https://www.ansiblebyexample.com/articles/ansible-tomcat-deploy-java-servlet-container Description: Deploy Apache Tomcat with Ansible. Installation, JDK setup, WAR deployment, virtual hosts, SSL/TLS, clustering, JVM tuning, and zero-downtime application. ## Introduction Apache Tomcat serves Java Servlets, JSPs, and WebSocket applications. Ansible automates the complete lifecycle — install JDK, deploy Tomcat, configure connectors, manage WAR files, tune the JVM, set up SSL, and perform zero-downtime deployments. This guide covers standalone through clustered production setups. ## Install JDK and Tomcat [code example] ### Systemd Service [code example] ## Deploy WAR Files [code example] ## Zero-Downtime Deployment [code example] ## JVM Tuning [code example] ## SSL/TLS Configuration [code example] [code example] ## Manager App Access [code example] ## Health Monitoring [code example] ## Troubleshooting ### OutOfMemoryError Increase heap in `CATALINA_OPTS`: [code example] ### Port Already in Use [code example] ## Related Articles - Ansible Apache HTTPD - Ansible HAProxy - Ansible Let's Encrypt SSL - Ansible Service Module ## Conclusion Ansible automates Tomcat from install to production — JDK setup, Tomcat extraction, `server.xml` templating, WAR deployment from build artifacts, JVM tuning, SSL configuration, and rolling zero-downtime updates with `serial: 1`. Use systemd services for process management and the Manager API for health monitoring. Every Tomcat configuration is a template; every deployment is idempotent. --- ## Ansible Touch File — Create Empty Files and Update Timestamps URL: https://www.ansiblebyexample.com/articles/ansible-touch-file-create-empty-files-and-update-timestamps Description: Create empty files and update timestamps with Ansible file module state touch. Set permissions, ownership, and modification times on remote hosts. # Ansible Touch File — Create Empty Files and Update Timestamps ## Introduction The `ansible.builtin.file` module with `state: touch` creates an empty file if it doesn't exist, or updates its modification timestamp if it does — exactly like the Unix `touch` command. Use it to create marker files, initialize logs, or signal task completion. ## Quick Reference [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `path` | File path to touch (required) | | `state` | `touch` (required for this operation) | | `owner` | File owner | | `group` | File group | | `mode` | File permissions | | `modification_time` | Set mtime (format: YYYYMMDDHHmm.ss or `preserve`) | | `access_time` | Set atime (same format or `preserve`) | ## Common Patterns ### Create Log File Before Service Start [code example] ### Deployment Marker File [code example] ### Lock File Pattern [code example] ### Create Only If Missing (Don't Update Timestamp) [code example] ### Create Multiple Files [code example] ### Preserve Timestamps [code example] ## touch vs Other Create Methods | Method | Creates File | Updates mtime | Content | |--------|-------------|---------------|---------| | `file: touch` | ✅ (empty) | ✅ (every run) | No | | `copy: content=""` | ✅ (empty) | Only on create | Optional | | `copy: force=false` | ✅ (only if missing) | No | Optional | | `template` | ✅ | Only on change | Yes | ## Troubleshooting | Issue | Fix | |-------|-----| | Always reports... --- ## Ansible Tower vs AWX — Automation Platform Comparison URL: https://www.ansiblebyexample.com/articles/ansible-tower-vs-awx-automation-platform Description: Compare Ansible Tower (AAP) and AWX. Features, pricing, use cases, installation, and when to choose each. Enterprise automation platform guide. ## Introduction Ansible Tower (now part of **Ansible Automation Platform / AAP**) and **AWX** are both web-based UIs for managing Ansible automation. Tower/AAP is the enterprise product from Red Hat with support and certifications. AWX is the free, open-source upstream project. They share the same codebase, but differ in support, stability, and enterprise features. ## Quick Comparison | Feature | AWX | Tower / AAP | |---------|-----|------------| | **Cost** | Free (open source) | Paid subscription | | **Support** | Community only | Red Hat support | | **Updates** | Frequent (upstream) | Scheduled releases | | **Stability** | Development pace | Enterprise-tested | | **Certifications** | None | SOC2, FedRAMP, etc. | | **LDAP/SAML** | ✅ | ✅ | | **RBAC** | ✅ | ✅ | | **REST API** | ✅ | ✅ | | **Workflow Engine** | ✅ | ✅ | | **Execution Environments** | ✅ | ✅ | | **Analytics** | Basic | Advanced (Automation Analytics) | | **Content Collections Hub** | No | ✅ (Private Automation Hub) | | **Clustering** | Manual | Built-in HA | | **Installation** | Docker/K8s (manual) | RPM/Operator (supported) | ## What Is AWX? AWX is the open-source upstream project for Ansible Tower. It provides: - **Web UI** — visual dashboard for managing playbooks, inventories, credentials - **REST API** — automate everything programmatically - **RBAC** — role-based access control for teams - **Job scheduling** — run playbooks on a schedule - **Workflow engine** — chain multiple playbooks together - **Cred... --- ## Ansible Tower vs AWX — Enterprise vs Open Source URL: https://www.ansiblebyexample.com/articles/ansible-tower-vs-awx-enterprise-vs-open-source Description: Ansible Tower vs AWX guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible Tower vs AWX — Enterprise vs Open Source ## Introduction Enterprise vs Open Source. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Tower vs AWX requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selec... --- ## Ansible Traefik — Deploy Cloud-Native Reverse Proxy URL: https://www.ansiblebyexample.com/articles/ansible-traefik-cloud-native-reverse-proxy Description: Deploy Traefik with Ansible. Cloud-native reverse proxy with automatic Let's Encrypt TLS, Docker and Kubernetes service discovery, middleware chains, rate. ## Introduction Traefik is a cloud-native reverse proxy and load balancer that integrates with Docker, Kubernetes, and Consul for automatic service discovery. It handles Let's Encrypt certificates automatically and supports middleware for authentication, rate limiting, and headers. Ansible deploys Traefik as a system service or Docker container with full configuration management. ## Deploy Traefik as System Service [code example] ### Static Config [code example] ### Dynamic Config [code example] ### Service Variables [code example] ## Traefik with Docker [code example] ## Health Check [code example] ## Troubleshooting ### Certificate Not Issuing [code example] ### Check Traefik Logs [code example] ## Related Articles - Ansible Nginx - Ansible HAProxy - Ansible Let's Encrypt - Ansible Docker Compose ## Conclusion Traefik is the cloud-native alternative to Nginx/HAProxy — it discovers services automatically from Docker labels or file-based config, handles TLS certificates via Let's Encrypt without any cron jobs, and provides middleware for security headers, rate limiting, and authentication. Ansible templates both static and dynamic configs, deploys as a system service or Docker container, and manages the full proxy lifecycle as code. --- ## Ansible Training — Courses & Certs URL: https://www.ansiblebyexample.com/articles/ansible-training-courses-certifications-guide Description: Ansible training guide: Red Hat EX294 certification, online courses, hands-on labs, and free learning resources for all skill levels. # Ansible Training — Best Courses, Certifications & Learning Resources Whether you're new to automation or want to advance your Ansible skills, this guide covers all the training options available in 2026. ## Official Red Hat Training Red Hat offers the definitive Ansible training paths: ### DO007 — Ansible Basics: Automation Technical Overview (Free) A free introductory course covering what Ansible is and how it works. Perfect starting point for complete beginners. ### DO374 — Developing Advanced Automation with Red Hat Ansible Automation Platform The primary hands-on training course. Covers playbooks, roles, collections, and Ansible Automation Platform features. ### EX294 — Red Hat Certified Engineer (RHCE) The gold standard Ansible certification. Validates your ability to use Ansible to automate configuration, deployment, and management across multiple systems. [code example] ## Online Learning Platforms ### Udemy Hundreds of Ansible courses ranging from beginner to advanced. Look for courses with high ratings and recent updates. ### LinkedIn Learning Professional-focused Ansible courses, often included with LinkedIn Premium subscriptions. ### Pluralsight In-depth Ansible skill paths covering core concepts through advanced automation patterns. ### A Cloud Guru / KodeKloud Hands-on lab environments where you practice Ansible in real infrastructure. ## Free Learning Resources ### Official Documentation The Ansible documentation is comprehensive and well-maintai... --- ## Ansible troubleshooting — 'not a valid attribute for a Play' URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-not-a-valid-attribute-for-a-play-error Description: Fix the Ansible error 'not a valid attribute for a Play' — caused by YAML typos like 'task' instead of 'tasks'. Complete list of valid play attributes. ## Introduction The "'X' is not a valid attribute for a Play" error is one of the most common Ansible errors, and it's almost always caused by a typo in a YAML key. Ansible validates every top-level key in a play against a fixed list of valid attributes. If you mistype `tasks` as `task`, or `become` as `becmoe`, Ansible rejects the entire play. This article covers the error, every valid play attribute, and the most common typos that trigger it. ## The Error ### Problematic Playbook [code example] ### Error Output [code example] ### Fixed Playbook [code example] ## All Valid Play Attributes Here is the complete list of valid top-level keys in an Ansible play: ### Required | Attribute | Description | |---|---| | `hosts` | Target hosts/groups for this play | ### Common Attributes | Attribute | Description | |---|---| | `name` | Play description | | `tasks` | List of tasks to execute | | `handlers` | List of handlers | | `vars` | Play-level variables | | `vars_files` | External variable files | | `vars_prompt` | Interactive variable prompts | | `roles` | List of roles to include | | `pre_tasks` | Tasks before roles | | `post_tasks` | Tasks after roles | ### Execution Control | Attribute | Description | |---|---| | `become` | Enable privilege escalation | | `become_user` | User to escalate to | | `become_method` | Escalation method (sudo, su) | | `become_flags` | Extra flags for become | | `gather_facts` | Collect system facts | | `strategy` | Execution strategy (l... --- ## Ansible Troubleshooting — Debug and Fix Common Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-debug-fix-common-errors Description: Troubleshoot common Ansible errors: SSH failures, permission denied, undefined variables, module errors, and slow playbooks. Debugging techniques. ## Introduction When Ansible fails, the error message usually tells you exactly what's wrong — if you know where to look. This guide covers the most common errors, what causes them, and how to fix them. ## Debugging Techniques ### Verbose Mode [code example] ### Debug Module [code example] ### Check Mode (Dry Run) [code example] ### Step Mode [code example] ### Start at Specific Task [code example] ## SSH Connection Errors ### "UNREACHABLE! => SSH Error" [code example] **Fixes:** [code example] ### "Permission denied (publickey)" [code example] ### Connection Timeout [code example] ## Permission Errors ### "MODULE FAILURE: Permission denied" [code example] ### "sudo: a password is required" [code example] ## Variable Errors ### "undefined variable" [code example] **Fixes:** [code example] ### "dict object has no attribute" [code example] ## Module Errors ### "No module named..." [code example] ### "Unsupported parameters" [code example] Check for typos in parameter names: [code example] ### "Could not find or access" [code example] ## YAML Syntax Errors ### "could not find expected ':'" [code example] ### "found character that cannot start any token" [code example] ### Indentation Errors [code example] ## Slow Playbook Performance [code example] [code example] ## Common Error Reference | Error | Cause | Fix | |-------|-------|-----| | UNREACHABLE | SSH can't connect | Check SSH, firewall, hostname | | Permission denied | N... --- ## Ansible Troubleshooting — Deprecated Module Usage (Rule 105) URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-105-deprecated-module-usage Description: Fix ansible-lint rule 105 (deprecated module). Find replacement modules, check deprecation timelines, and update playbooks to use actively maintained. ## Introduction Ansible-lint rule 105 (`deprecated-module`) flags modules that are no longer actively maintained and scheduled for removal. Using deprecated modules means you're building on code that won't receive security patches, bug fixes, or compatibility updates — and will eventually break when the module is removed. ## The Error [code example] [code example] ## Common Deprecated Modules and Replacements | Deprecated Module | Replacement | Removed In | |-------------------|-------------|------------| | `ansible.netcommon.net_vlan` | Platform-specific (e.g., `cisco.ios.ios_vlans`) | Varies | | `ansible.builtin.include` | `ansible.builtin.include_tasks` | 2.16+ | | `ansible.builtin.raw` for Windows | `ansible.windows.win_shell` | — | | `community.general.docker_container` (old) | `community.docker.docker_container` | Moved | | `ansible.builtin.ec2` | `amazon.aws.ec2_instance` | Moved to collection | ## How to Find Replacements ### Check Module Documentation [code example] ### Check the Ansible Module Index The Ansible module index lists all modules with their status (deprecated, removed, or active). ### Use ansible-lint --fix For some rules, ansible-lint can auto-fix: [code example] This works for FQCN migration and some module renames. ## Fix Examples ### Example 1: Network Module [code example] ### Example 2: include → include_tasks [code example] ### Example 3: Docker Module Migration [code example] Install the new collection: [code example] ## ... --- ## Ansible troubleshooting — Destination does not exist rc 257 URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-destination-does-not-exist-rc-257 Description: Troubleshoot the "Destination does not exist" error (return code 257) in Ansible with Luca Berton on Ansible Pilot! Learn to fix file path issues. ## Introduction Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll delve into Ansible troubleshooting, focusing on the "Destination does not exist" error with return code 257. This error typically occurs when attempting to edit a file that doesn't exist on the target file system. We'll explore the root causes and Playbooknstrate how to resolve this issue using the Ansible `lineinfile` module. ## Understanding the Error The fatal error message "Destination does not exist" with return code 257 arises when Ansible attempts to modify a file that is either misspelled or entirely absent on the target system. This error is commonly encountered while configuring SSH settings, particularly when enabling `PasswordAuthentication`. I'm Luca Berton, and let's dive into today's Ansible troubleshooting session. ## Demo To illustrate the troubleshooting process, we'll jump into a live Playbook. In this scenario, we'll attempt to edit a configuration file, `/etc/ssh/sshd_config2`, which is misspelled on our target system. ### Error Code Let's examine the Ansible playbook (`destinationdoesnotexist_257_error.yml`) triggering the error: [code example] Upon execution, the playbook results in a fatal error with return code 257: [code example] ### Fix Code Let's correct the playbook to reference the correct file (`/etc/ssh/sshd_config`) in the fixed version (`destinationdoesnotexist_257_fix.yml`): [code example] ### Fix Execution Now, when we execute the c... --- ## Ansible troubleshooting — Error 102: No Jinja2 in 'when' Conditions URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-102-no-jinja2-in-when-conditions Description: The when clause in Ansible playbooks controls task execution based on conditions. Learn to avoid Ansible Error 102 by ensuring correct Jinja2. ## Introduction Ansible is a powerful automation tool that allows you to manage and configure servers and applications using simple YAML-based playbooks. One of the fundamental elements in Ansible playbooks is the 'when' clause, which is used to control the flow of tasks based on specific conditions. However, it's crucial to understand that when conditions are always templated, Ansible enforces a specific structure for these expressions to avoid errors and issues. In this article, we will explore Ansible Error 102, "No Jinja2 in when," and how to work with 'when' conditions properly using Ansible-Lint. ## The 'when' Clause in Ansible The 'when' clause is an essential feature in Ansible playbooks, allowing you to control the execution of tasks based on specific conditions. These conditions determine whether a task should run or be skipped. To specify conditions, you use the 'when' keyword followed by an expression, and Ansible evaluates this expression to determine if the task should be executed. ## Understanding the Error Ansible Error `102, "No Jinja2 in when"` occurs when there is a Jinja2 template error within a 'when' condition. Jinja2 is the templating engine used by Ansible to process variables and expressions. The error message signifies that the 'when' condition contains a Jinja2 expression that is improperly formatted or missing necessary brackets. Example playbook: [code example] Output: [code example] ## Correcting the 'when' Condition To avoid Ansible Err... --- ## Ansible troubleshooting — Error 104: Deprecated Bare Vars URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-104-deprecated-bare-vars Description: Ansible Error 104, "Deprecated Bare Vars", identifies ambiguous expressions that could be misinterpreted as variables or strings, promoting clarity in. ## Introduction Ansible, the popular open-source automation platform, provides a straightforward and efficient way to automate tasks, manage configurations, and orchestrate processes. However, as with any tool, there are best practices to follow and potential pitfalls to avoid. In this article, we will delve into Ansible Error 104, “`Deprecated Bare Vars`”, which is a rule in Ansible-Lint designed to identify potentially confusing expressions where it’s unclear whether a variable or string should be used. We will explore this error, understand its implications, and learn how to write clean, maintainable Ansible code that adheres to best practices. ## The Problem: Deprecated Bare Vars Ansible Error 104, known as “`Deprecated Bare Vars`”, is a valuable rule designed to maintain code clarity and consistency. This rule points out situations where it is unclear whether a given expression should be interpreted as a variable or a string. To address this, Ansible encourages users to either use the full variable syntax or convert the expression into a list of strings. Problematic Code Example: [code example] In the code above, the variable “foo” is being referenced without any clear indication of whether it’s a variable or a string. This ambiguity can lead to confusion and potential issues down the line. Output: [code example] ## Correcting the Code To resolve Ansible Error 104 and improve code clarity, it’s essential to provide explicit indications of whether “`foo`”` is a v... --- ## Ansible troubleshooting — Error 106: Role Name Rules URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-106-role-name-rules Description: Fix Ansible Lint Error 106 role-name — naming conventions for roles using lowercase alphanumeric characters and underscores with practical examples. ## Introduction Ansible Lint Rule 106 (`role-name`) enforces naming conventions for Ansible roles. Role names must use only lowercase alphanumeric characters and underscores, and must start with a letter. This prevents issues with Galaxy imports, cross-platform compatibility, and playbook readability. This article covers the rule, common violations, how to rename roles, and Galaxy namespace requirements. ## The Rule Role names must follow these requirements: 1. **Start with a letter** (a-z) 2. **Contain only** lowercase letters (a-z), digits (0-9), and underscores (_) 3. **No uppercase**, hyphens, dots, spaces, or special characters ### Valid Role Names [code example] ### Invalid Role Names [code example] ## The Error ### Problematic Code [code example] ### Lint Output [code example] ### Fixed Code [code example] ## Why These Rules Exist ### 1. Ansible Galaxy Compatibility Galaxy enforces the same naming rules. Roles with invalid names cannot be published: [code example] ### 2. Cross-Platform File Systems Some operating systems are case-insensitive (macOS, Windows). A role named `WebServer` and `webserver` would collide: [code example] ### 3. Python Module Compatibility When roles are part of collections, they map to Python namespaces. Python modules must follow the same naming rules: [code example] ### 4. URL and Path Safety Role names appear in URLs (Galaxy), file paths, and variable names. Special characters cause issues: [code example] ## Rena... --- ## Ansible troubleshooting — Error 202: Risky Octal Permissions URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-202-risky-octal-permissions Description: Ansible Error 202, "`risky-octal`", warns against using octal file permissions without a leading zero, which can lead to unpredictable outcomes. ## Introduction Ansible, a powerful automation tool, enables you to manage configurations, deploy software, and automate various tasks in a structured and organized manner. However, to harness the full potential of Ansible, it’s essential to follow best practices and avoid potential pitfalls. In this article, we’ll explore Ansible Error 202, “`risky-octal`”, in Ansible-Lintwhich focuses on the use of octal file permissions in your Ansible playbooks. We’ll discuss why using integers or octal values in YAML can lead to unexpected behavior and how to ensure that your file permissions are defined safely and predictably. ## The Problem: Risky Octal File Permissions Ansible Error 202, “`risky-octal`”, is designed to prevent the use of octal file permissions in a non-standard form, which can result in unpredictable outcomes. Octal file permissions are typically written with a leading zero (e.g., `0644`). When you omit the leading zero and use an integer (e.g., `644`), the YAML parser interprets the value differently, leading to unexpected results. Problematic Code Example: [code example] In the above code snippet, the `“mode”` parameter lacks the leading zero in the octal permission, making it prone to unpredictable behavior. Output: [code example] ## Modules that are checked - ansible.builtin.assemble - ansible.builtin.copy - ansible.builtin.file - ansible.builtin.replace - ansible.builtin.template ## Correcting File Permissions To address Ansible Error 202 and define fi... --- ## Ansible troubleshooting — Error 206 Jinja Spacing URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-206-jinja-spacing Description: Ansible Error 206, "`jinja[spacing]`", ensures proper spacing within Jinja2 templates for improved readability and accuracy ## Introduction Ansible, the popular open-source automation platform, provides a powerful and flexible way to automate tasks, manage configurations, and orchestrate processes. However, to ensure the maintainability and readability of Ansible playbooks, it's important to adhere to best practices and guidelines. In this article, we'll explore Ansible Error 206, "`jinja[spacing]`", in Ansible-Lint which is related to Jinja2 string templates. We'll discuss how this rule helps improve readability and reduce the likelihood of typos by enforcing proper spacing in Jinja2 templates within your Ansible playbooks. ## The Problem: Jinja Spacing Ansible Error 206, "`jinja[spacing]`", checks for the correct spacing within Jinja2 string templates. Specifically, it ensures there are spaces between variables and operators, including filters, such as {{ var_name | filter }}. Proper spacing not only enhances readability but also makes it less likely for typographical errors to occur. Problematic Code Example: [code example] In the problematic code above, Jinja2 templates need to have the appropriate spacing between variables, operators, and filters, making the code less readable and prone to typos. Output: [code example] ## Correcting Jinja Spacing Use the appropriate spacing to address Ansible Error 206 and ensure that your Jinja2 templates are correctly formatted for readability and accuracy. Here's the corrected code: [code example] In the corrected code, spaces have been added betw... --- ## Ansible troubleshooting — Error 207: Jinja Invalid URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-207-jinja-invalid Description: Fix Ansible Lint Error 207 jinja[invalid] — invalid Jinja2 template syntax, common patterns, auto-fix, and best practices. ## Introduction Ansible leverages Jinja2 templates for dynamic configurations, variable interpolation, and conditional logic in playbooks. Ansible Lint rule 207 (`jinja[invalid]`) detects invalid Jinja2 template syntax — expressions that would cause runtime failures when Ansible attempts to render them. This article covers every common pattern that triggers this error, how to fix each one, the auto-fix capability, and current limitations. ## Understanding the Error Rule 207 belongs to the `basic` profile and is tagged as `formatting`. It catches Jinja2 expressions that contain syntax errors — invalid characters, malformed filters, nested template markers, or broken conditional expressions. ### Error Output Example [code example] ## Common Patterns That Trigger Error 207 ### Pattern 1: Invalid Characters in Expressions Using characters that are not valid Python/Jinja2 operators: [code example] ### Pattern 2: Nested Template Markers Double curly braces inside an existing Jinja2 expression: [code example] ### Pattern 3: Unbalanced Braces Missing or extra curly braces: [code example] ### Pattern 4: Invalid Filter Syntax Misspelled filters or wrong filter arguments: [code example] ### Pattern 5: Unclosed String Literals [code example] ### Pattern 6: Invalid Comparison Operators [code example] ### Pattern 7: Missing Filter Name After Pipe [code example] ### Pattern 8: Invalid Arithmetic [code example] ## Complete Error and Fix Example ### Error Playbook ... --- ## Ansible troubleshooting — Error 208: risky-file-permissions URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-208-risky-file-permissions Description: Ansible Error 208, "`risky-file-permissions`," warns against insecure file permissions set by modules like ansible.builtin.copy or. ## Introduction Ansible, the robust automation tool, empowers users to manage configurations, deploy software, and automate a wide range of tasks with ease. However, ensuring the security and predictability of file permissions when creating or manipulating files is crucial to maintaining a stable and safe environment. In this article, we’ll explore Ansible Error 208, “`risky-file-permissions`,” in Ansible-Lint which focuses on the risks associated with modules that can create or modify files with potentially insecure or unpredictable permissions. We’ll discuss how to use these modules safely and mitigate potential security issues in your Ansible playbooks. ## The Problem: Risky File Permissions Ansible Error 208, “`risky-file-permissions`,” serves as a reminder of the potential security risks posed by modules that can create or modify files with overly open or unpredictable permissions. This rule is triggered by various modules, such as ansible.builtin.copy, ansible.builtin.file, community.general.archive, and others. If the proper arguments are not used with these modules, it can result in files on disk having insecure permissions. Problematic Code Example: [code example] In the problematic code above, the `ini_file` module is used with the create argument set to true, potentially creating a file with insecure permissions, depending on the system settings. Output: [code example] ## Modules that are checked Modules that are checked: - ansible.builtin.assemble - ansib... --- ## Ansible troubleshooting — Error 304: inline-env-var URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-304-inline-env-var Description: Rule 304, inline-env-var, advises against setting environment variables directly within the ansible.builtin.command module. ## Introduction Ansible, the powerful automation tool, empowers users to streamline tasks and processes efficiently. However, ensuring best practices and maintaining a clean and predictable playbook is crucial. Ansible-Lint, a popular linting tool for Ansible playbooks, enforces a range of rules to help users optimize their automation scripts. In this article, we focus on Rule 304, "`inline-env-var`," in Ansible-Lint which checks that environment variables should not be set within the `ansible.builtin.command` module. Instead, the `ansible.builtin.shell` module or the environment keyword should be used for this purpose. ## Understanding Rule 304 Rule 304, "`inline-env-var`," offers a simple yet effective piece of guidance for Ansible playbook authors. It highlights the importance of maintaining clarity and best practices in your playbooks by ensuring that environment variables are not set directly within the `ansible.builtin.command` module. ## Problematic Code Consider this problematic code snippet: [code example] In this code, the playbook attempts to set an environment variable (`MY_ENV_VAR`) directly within the `ansible.builtin.command` module. While this might work, it is not the recommended approach. Output: [code example] ## Correct Code The corrected code aligning with Rule 304 looks like this: [code example] In this improved version, the playbook uses the `ansible.builtin.shell` module to set the environment variable and leverages the `environment` keywo... --- ## Ansible troubleshooting — Error 305: command-instead-of-shell URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-305-command-instead-of-shell Description: Fix Ansible Lint Error 305 command-instead-of-shell — when to use command vs shell and why it matters for security and performance. ## Introduction Ansible Lint Rule 305 (`command-instead-of-shell`) flags tasks that use the `shell` module when the `command` module would suffice. The `shell` module invokes a full shell (`/bin/sh`) to execute commands, which introduces unnecessary overhead and potential security risks when shell features aren't needed. This article explains the difference, when each module is appropriate, and how to fix the error. ## Understanding the Difference ### ansible.builtin.command - Executes the command **directly** (no shell involved) - **No access to**: pipes (`|`), redirects (`>`, `>`), environment variable expansion (`$HOME`), wildcards (`*`), command chaining (`&&`, `||`, `;`) - **Faster**: no shell process overhead - **Safer**: no shell injection risk ### ansible.builtin.shell - Executes via `/bin/sh -c "your command"` - **Full shell features**: pipes, redirects, wildcards, env vars, subshells - **Slower**: spawns an extra shell process - **Higher risk**: vulnerable to shell injection if using untrusted input ## The Error ### Problematic Code [code example] ### Lint Output [code example] ### Fixed Code [code example] ## When to Use command (No Shell Needed) [code example] ## When shell IS Required These shell features require the `shell` module: ### Pipes [code example] ### Redirects [code example] ### Environment Variable Expansion [code example] ### Wildcards/Globbing [code example] ### Command Chaining [code example] ### Subshells [code example... --- ## Ansible troubleshooting — Error 306: risky-shell-pipe URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-306-risky-shell-pipe Description: Rule 306, risky-shell-pipe, advises setting pipefail to ensure reliable task execution in Ansible shell modules. With tested, real-world examples. ## Introduction Ansible, the renowned automation tool, simplifies the management and configuration of IT infrastructure. While Ansible empowers users with a wide range of modules to streamline tasks, it's vital to adhere to best practices for creating clean and predictable playbooks. Ansible-Lint, a popular linter for Ansible playbooks, enforces various rules to help you optimize your automation scripts. In this article, we delve into Rule 306, "`risky-shell-pipe`," in Ansible-Lint which emphasizes the importance of using the bash `pipefail` option when employing the Ansible shell module to create pipelines. Setting pipefail ensures that tasks fail as expected if the first command in a pipeline fails. ## Understanding Rule 306 Rule 306, "`risky-shell-pipe`," is a valuable guideline for Ansible playbook authors. It promotes the use of the pipefail option when creating pipelines with the Ansible shell module. When using pipelines to pass output from one command to another, it's crucial to set pipefail to ensure the reliability of task execution. The return status of a pipeline should reflect the exit status of the first command in the pipeline, ensuring that tasks fail if the initial command fails. ## Problematic Code Let's explore a problematic code snippet that Rule 306 can identify in your playbooks: [code example] In this code, the playbook creates a pipeline without setting the pipefail option. If the initial command (in this case, "false") fails, the task may not f... --- ## Ansible troubleshooting — Error 403: package-latest URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-403-package-latest Description: Using state: latest for package installations in Ansible can introduce unpredictability. Discover how to improve the code with a practical example to. ## Introduction Ansible is a powerful automation tool known for its role in provisioning, configuration management, and application deployment. Ensuring the integrity and stability of software installations is vital when managing packages through Ansible. To help you achieve this, Ansible provides a set of rules, including Rule 403, known as "package-latest." This rule emphasizes the importance of controlled, safe package management practices, promoting predictability in your automation tasks. ## Deciphering Rule 403 - "package-latest" Rule 403, or "package-latest," is a rule within Ansible's comprehensive rule set that aims to establish best practices for managing packages using package manager modules, such as `ansible.builtin.yum` and `ansible.builtin.apt`. These modules allow users to configure how Ansible installs software on target systems. The primary concern addressed by this rule is the use of the `state` parameter in package manager modules. In production environments, it is crucial to set the `state` to "present" and specify a target version for package installations. This practice ensures that packages are installed according to a predefined and tested version, adding a layer of control and predictability to your automation tasks. Conversely, setting the `state` to "latest" is discouraged, as it not only installs the desired software but also initiates an update process that can lead to unintended consequences. The update process can result in performance deg... --- ## Ansible troubleshooting — Error 404: no-relative-paths URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-404-no-relative-paths Description: Rule 404, no-relative-paths, ensures stability by discouraging the use of relative paths in Ansible copy and template modules. ## Introduction Ansible is renowned for its flexibility and efficiency in automating various IT tasks. When it comes to managing files and templates in Ansible playbooks, the "`copy`" and "`template`" modules are frequently used to handle file transfers and template rendering. However, mismanaging paths in these modules can lead to confusion and unexpected behavior. Ansible Rule 404, known as "`no-relative-paths`," guides users to maintain best practices for handling paths within these modules. ## Demystifying Rule 404 - "no-relative-paths" Rule 404, "`no-relative-paths`," is a vital component of Ansible's rule set, aimed at ensuring the proper handling of paths within the "`ansible.builtin.copy`" and "`ansible.builtin.template`" modules. These modules are commonly used to interact with local and remote files in Ansible playbooks. While paths are fundamental to these modules, using relative paths can result in errors, disorganized projects, and user confusion. The core principle emphasized by this rule is that the "`src`" argument in these modules should refer to local files and directories on the control node, not remote resources. Users are strongly advised to store files and templates in specific locations within the playbook or role directory: 1. Use the "`files/`" folder in the playbook or role directory for the "`copy`" module. 2. Use the "`templates/`" folder in the playbook or role directory for the "`template`" module. These dedicated folders provide a clear an... --- ## Ansible troubleshooting — Error 501: partial-become URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-501-partial-become Description: Rule 501, partial-become, ensures consistent privilege escalation in Ansible by verifying become_user aligns with become: true ## Introduction When working with Ansible, it's essential to ensure that privilege escalation is managed effectively, especially when changing users. Ansible provides the `become` directive for this purpose, which allows you to execute actions as a different user, typically a superuser like root. However, Rule 501, known as "`partial-become`" in Ansible Lint, emphasizes the importance of using this privilege escalation mechanism consistently and explicitly. ## The Purpose of Rule 501 Rule 501, "`partial-become`," checks whether privilege escalation is properly activated when changing users in Ansible playbooks and tasks. To execute a task as a different user using the `become_user` directive, you must explicitly set `become: true` to ensure it works as expected. This rule aims to make your Ansible playbooks more robust and predictable by ensuring that privilege escalation is consistently and explicitly defined at the appropriate levels, specifically the task or play level. By doing so, it minimizes the risk of errors and accidents when tasks are moved from one location to another, enhancing the reliability of your automation workflows. ## Common Scenarios Let's explore some common scenarios that Playbooknstrate how this rule works and what to do when privilege escalation is necessary. ## Problematic Scenario [code example] In this scenario, privilege escalation is partially implemented. The `become` directive is correctly set to `true`, but the `become_user` directiv... --- ## Ansible troubleshooting — Error 503: no-handler URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-503-no-handler Description: Rule 503, no-handler, in Ansible ensures tasks responding to changes are structured as handlers for efficient playbook management. ## Introduction In the realm of infrastructure automation with Ansible, efficient playbook execution is a top priority. However, this efficiency is often hampered when playbooks are not structured optimally. Rule 503, known as "`no-handler`" in Ansible Lint, focuses on promoting a structured approach to handling changes in playbook execution, resulting in smoother and more maintainable automation workflows. ## The Role of Handlers in Ansible Before delving into the specifics of Rule 503, it's essential to understand the role of handlers in Ansible. Handlers are special tasks designed to respond to specific events in playbook execution. They are executed only when triggered, which can occur when a task in the playbook sets a specific condition. This approach is especially useful when you want to respond to changes, restart services, or perform other actions based on specific conditions. ## The Problematic Scenario Rule 503, "`no-handler`," addresses scenarios where tasks in a playbook exhibit handler-like behavior but lack the structure of a proper handler. A typical situation involves tasks setting conditions, such as `when: result.changed`, which indicate that something in the playbook has changed and a follow-up action is required. Consider the following problematic code: [code example] In this code, the second task, "Second command to run," checks whether the `result.changed` condition is met, and if so, it proceeds to execute a task. While this approach can work, ... --- ## Ansible troubleshooting — Error 505: missing-import URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-505-missing-import Description: Fix Ansible Lint Error 505 missing-import — causes, examples, and best practices for import_tasks, include_tasks, and roles. ## Introduction Ansible Lint rule 505 (`missing-import`) flags playbooks and roles that reference files, tasks, or roles that cannot be found on the Ansible controller. This is a **syntax-check** level rule — meaning it catches errors that would cause your playbook to fail at runtime before you even run it. This article covers the root causes of this error, every common scenario that triggers it, how to fix each one, and best practices for organizing imports in Ansible projects. ## Understanding the Error When ansible-lint encounters a reference to a file that does not exist, it reports: [code example] This rule is tagged as `core` and `unskippable` — you cannot disable it because a missing file will always cause a runtime failure. ## Common Causes ### 1. Typo in Filename or Path The most frequent cause — a simple misspelling in the import path: [code example] ### 2. File Does Not Exist Yet Referencing a task file you planned to create but have not yet written: [code example] ### 3. Wrong Relative Path Ansible resolves relative paths differently depending on context: [code example] ### 4. Missing Role in requirements.yml When a playbook references a role that is not installed: [code example] ### 5. Case-Sensitive Filenames On case-sensitive filesystems, `Tasks/Setup.yml` is different from `tasks/setup.yml`: [code example] ## Error Examples ### Example 1: Missing include File **Playbook:** [code example] **Lint Output:** [code example] ### Example ... --- ## Ansible troubleshooting — Error 602: empty-string-compare URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-602-empty-string-compare Description: Ansible Rule 602, empty-string-compare, enhances playbook clarity by promoting direct length comparisons over empty string checks. ## Introduction In the world of automation, clarity and consistency are paramount. Ansible, the popular automation tool, allows you to define tasks and conditions to be executed on various systems. To ensure that your playbooks are easy to read and maintain, adhering to best practices and avoiding code patterns that might lead to confusion is essential. Ansible Rule 602, "`empty-string-compare`," specifically targets the comparison of empty strings within playbooks. Let's dive into why this rule exists and how you can adhere to it effectively. ## The Significance of Conditional Statements Conditional statements are at the heart of any Ansible playbook. They enable you to control when specific tasks are executed based on certain conditions. This provides the flexibility to create playbooks that adapt to various scenarios. Within these conditional statements, it's common to compare variables with values, including empty strings. An empty string comparison is typically used to check if a variable has been defined or has a value. However, this approach can introduce code that is less clear and might lead to ambiguity. ## Understanding Ansible Rule 602 Ansible Rule 602, "`empty-string-compare`," focuses on enforcing code clarity and consistency when it comes to using empty string comparisons within conditional statements. It recommends two specific alternatives for clarity: 1. **Use `when: var | length > 0` instead of `when: var != ""`:** Instead of checking if a variable i... --- ## Ansible troubleshooting — Error 702: meta-no-tags URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-702-meta-no-tags Description: Ansible Rule 702, meta-no-tags, ensures role metadata tags use lowercase letters and digits for consistency and clarity. ## Introduction Automation is a powerful ally for modern IT operations, and Ansible stands as one of the leading tools for managing complex tasks. When you're working with Ansible, you often organize your automation logic into roles. Roles encapsulate a collection of tasks, templates, and variables that help automate specific functions within your infrastructure. However, even in the realm of automation, there are rules and conventions to follow to ensure your work is both efficient and understandable. Ansible Rule 702, "`meta-no-tags`," focuses on a particular aspect of role management: metadata tags. ## Understanding Metadata Tags In Ansible, metadata tags are used to categorize and label roles and tasks. Tags help you filter and execute specific roles or tasks in your playbook. When it comes to organizing and naming these tags within the metadata of a role, Rule 702 comes into play. ## The Significance of Rule 702 **Rule 702, "`meta-no-tags`," checks role metadata for tags with special characters and uppercase letters. It enforces the convention of using only lowercase letters and numbers for tags in the `meta/main.yml` file in an Ansible Role.** This might seem like a minor detail, but adhering to this rule is essential for maintaining consistent and organized Ansible roles. ## Problematic Code vs. Correct Code Let's illustrate the difference between problematic code that violates Rule 702 and the correct code that aligns with the rule's recommendations. ### Prob... --- ## Ansible troubleshooting — Error 703: meta-incorrect URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-703-meta-incorrect Description: Ansible Rule 703, meta-incorrect, ensures role metadata fields like author, description, company, and license have defined values. ## Introduction In the world of automation and infrastructure management, Ansible has emerged as a powerful tool for simplifying complex tasks. It provides an efficient way to manage and configure systems. When working with Ansible, organization and documentation are key, and that's where metadata plays a vital role. Ansible Rule 703, "`meta-incorrect`," ensures that your role metadata adheres to certain standards. ## Understanding Role Metadata Roles are a fundamental concept in Ansible. They encapsulate a set of tasks, variables, and templates, making it easier to organize and reuse automation logic. Each role can have associated metadata, defined in the `meta/main.yml` file. Metadata helps describe the role and provides important information about it. ## The Significance of Rule 703 **Rule 703, "`meta-incorrect`," checks role metadata for fields with undefined or default values. It enforces the convention of setting appropriate values for specific metadata fields in the `meta/main.yml` file.** The metadata fields that should have defined values are: 1. `author` 2. `description` 3. `company` 4. `license` Rule 703 ensures that these fields are not left with placeholder or default values. Let's explore why adhering to this rule is essential. ## Problematic Code vs. Correct Code Let's compare problematic code that violates Rule 703 with the correct code that aligns with the rule's recommendations. ### Problematic Code Metadata fields for the role contain default va... --- ## Ansible troubleshooting — Error 704: meta-video-links URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-704-meta-video-links Description: How to solve Ansible Error 704: meta-video-links - A guide to ensuring proper video link formatting. With tested, real-world examples. ## Introduction Automation is a powerful tool in modern IT and infrastructure management, and Ansible is at the forefront of this revolution. When working with Ansible roles, ensuring that your metadata is structured correctly is essential. Ansible Rule 704, "`meta-video-links`," focuses on the proper formatting of video links in your role's metadata. It enforces the use of dictionaries for items in the `meta/main.yml` file and ensures that video links follow a specific format. ## The Importance of Role Metadata Roles are a fundamental concept in Ansible, allowing you to encapsulate a set of tasks, variables, and templates into reusable automation logic. Metadata is an integral part of roles, providing information about the role, such as its purpose and authorship. ## Understanding Rule 704 **Rule 704, "meta-video-links," checks the formatting of video links in the metadata of Ansible roles.** In particular, it enforces the use of dictionaries for items in the `video_links` section of your role's metadata. Each item in the `video_links` section should have two keys: 1. `url`: This key should contain a shared link from platforms like YouTube, Vimeo, or Google Drive. 2. `title`: This key should provide a title for the video link. Let's explore why adhering to this rule is crucial. ## Problematic Code vs. Correct Code To understand the rule better, let's compare problematic code that violates Rule 704 with the correct code that adheres to the rule's recommendations. #... --- ## Ansible troubleshooting — Error args URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-args Description: The args rule in Ansible validates task arguments against module documentation, ensuring correct parameter usage for reliable automation. ## Introduction In Ansible, the `args` rule is a critical aspect of ensuring that your playbook's task arguments align with the plugin's documentation. It's vital to maintain a proper structure and adhere to the required parameters for each module. Failure to do so can lead to unexpected behavior and issues in your automation workflow. This rule primarily serves as a validator, confirming that your task arguments are not only present but also correctly defined. It checks if the option names are valid and if they have the correct values. Additionally, it examines conditions related to these options, such as mutually exclusive, required together, required one of, and more. Here are some possible messages that this rule might generate: - `args[module] - missing required arguments: ...` - `args[module] - missing parameter(s) required by ...` Let's delve into some examples to understand this rule better. ## Problematic Code [code example] Output [code example] ## Correct Code [code example] It's essential to make sure that your task arguments align with the plugin documentation. Validating your module options using the `args` rule is a crucial step in maintaining a robust Ansible playbook and ensuring the success of your automation tasks. In some special cases, such as when using Jinja expressions, the linter may not fully validate all possible values and could produce a false positive. In such scenarios, you can use `# noqa: args[module]` to bypass the rule for speci... --- ## Ansible troubleshooting — Error avoid-implicit URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-avoid-implicit Description: The avoid-implicit rule in Ansible identifies and advises against implicit behaviors, promoting explicit instructions for predictable playbook execution. ## Introduction Ansible is a powerful automation tool, but its flexibility can sometimes lead to unintended and implicit behaviors in your playbooks. These implicit behaviors are often undocumented, making it challenging to understand what's happening behind the scenes. In this article, we'll explore the "`avoid-implicit`" rule in Ansible and how you can follow best practices to avoid these implicit behaviors. ## What is the "avoid-implicit" Rule? The "`avoid-implicit`" rule is a part of Ansible's linting tool that helps identify and flag the use of implicit behaviors within your playbooks. Implicit behaviors are actions that Ansible takes without explicit instructions, and they can lead to unpredictable outcomes or errors. ## Common Implicit Behaviors One common example of implicit behavior in Ansible is when using the `ansible.builtin.copy` module to write file content. While you might expect to provide content as a simple dictionary, Ansible can interpret this in unexpected ways. To avoid this, it's best to use an explicit Jinja template. ## Problematic Code Here's an example of problematic code and the correct way to address it: [code example] Output [code example] ## Correct Code In this code, the content is provided as a dictionary, which Ansible may interpret as file content, leading to unexpected results. It's always best to use an explicit Jinja template, as shown in the corrected code: [code example] By using explicit Jinja templates, you ensure that An... --- ## Ansible troubleshooting — Error galaxy URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-galaxy Description: The galaxy rule verifies that the version specified in galaxy.yml for an Ansible collection is at least 1.0.0, ensuring standard versioning for production. ## Introduction Ansible is a powerful automation and configuration management tool that allows you to streamline and simplify complex IT tasks. One of Ansible's key features is the use of collections, which are shareable units of automation, and can be hosted on Ansible Galaxy. Collections help automate various tasks efficiently. However, ensuring that your Ansible collections are well-maintained and follow best practices is crucial for seamless automation. In this article, we'll discuss the Ansible "`galaxy`" rule, which is designed to identify and address issues related to the quality and completeness of your Ansible collections. This rule serves as a helpful guide to maintaining and certifying your collections on Automation Hub or Galaxy NG. ## Collection Version One of the first aspects the "`galaxy`" rule checks is the collection version specified in your `galaxy.yml` file. It ensures that the collection's version is greater than or equal to `1.0.0`. This requirement ensures that your collection follows a standard versioning convention, with the goal of indicating that it's a production-ready release. For example: ## Problematic Code [code example] Output [code example] ## Correct Code [code example] ## Changelog Requirement The presence of a changelog file is crucial for transparency and documentation purposes. The "galaxy" rule checks for the existence of a changelog file in specific locations: `CHANGELOG.md` or `.rst` in the collection's root, or a `chang... --- ## Ansible troubleshooting — Error internal-error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-internal-error Description: Learn how to troubleshoot and resolve internal errors in Ansible playbooks, including examples of problematic and corrected code to guide you through the. ## Introduction In the world of automation and configuration management, Ansible shines as a powerful tool that simplifies the management of IT infrastructure. It allows users to define and execute tasks, known as playbooks, that automate various aspects of system administration. However, like any software, Ansible isn't immune to errors. One particularly challenging category of errors is the so-called "`internal-error`." These errors can be caused by internal bugs within Ansible or by custom rules set by users. They might leave you scratching your head, wondering what went wrong. This article delves into internal errors, how to handle them, and provides insights into common scenarios. ## The Nature of Internal Errors Internal errors in Ansible can be frustrating to troubleshoot. They are not always straightforward, and they can result from various sources. Here are some key points to understand: - **Internal Bugs:** Sometimes, internal errors are a direct result of bugs within Ansible itself. These bugs can manifest in a variety of ways and may not always provide clear, informative error messages. - **Custom Rules:** Users can create custom rules to enforce specific coding standards and practices. If these rules are too restrictive or contain errors themselves, they can trigger internal errors. - **Continued Processing:** When Ansible encounters an internal error, it doesn't simply halt and terminate the entire execution. Instead, it generates an error message but con... --- ## Ansible troubleshooting — Error key-order URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-key-order Description: The key-order rule ensures structured YAML readability. It emphasizes placing name first and block, rescue, always last for clarity and consistency." ## Ansible Playbook `key-order`: Keeping Your Playbooks Neat and Error-Free In the world of Ansible, maintaining well-structured and readable playbooks is essential. The `key-order` rule is your secret weapon for keeping your playbooks clean and less prone to errors. This rule offers key reordering recommendations to enhance your Ansible coding skills and streamline your playbook development. ## The Anatomy of `key-order` The `key-order` rule comes with some essential guidelines: 1. **"`name`" Comes First:** For plays, tasks, and handlers, the "`name`" key should always be the first one. This naming convention helps you quickly grasp the purpose of a specific block of code. 2. **"`block`," "`rescue`," and "`always`" Are Last:** In tasks, the "`block`," "`rescue`," and "`always`" keys should be positioned at the end. This arrangement reduces the likelihood of accidental misindentation errors, especially when dealing with complex playbooks. ## Spotting the Problem Let's take a look at a problematic code snippet: [code example] Here, we encounter a playbook where the "`name`" key isn't at the beginning, and the "`when`" key appears after the "`block`" key, violating the `key-order` rule. Ansible Lint Output [code example] ## The Correct Order Let's rectify the previous example and adhere to the `key-order` rule: [code example] Now, we have reordered the keys according to the `key-order` rule recommendations. ## Why Does `key-order` Matter? The `key-order` rule ... --- ## Ansible troubleshooting — Error load-failure URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-load-failure Description: The load-failure error in Ansible linting can stem from issues like unsupported encoding, non-standard YAML, or vault decryption problems. --- ## Introduction The "load-failure" error is a common issue that can occur during the linting process of Ansible playbooks. This error is triggered when the linter fails to process a file, indicating a potential issue with the file's content. There are several reasons why this error may occur, and it's essential to understand them to troubleshoot effectively. ### Possible Causes of load-failure: 1. **Unsupported Encoding:** Ansible only supports files with UTF-8 encoding. If a playbook contains a different encoding, the linter may fail to process it. 2. **Not an Ansible File:** If the file being processed is not a valid Ansible playbook or role file, it may result in a "load-failure" error. Ensure that the file follows the correct Ansible structure and format. 3. **Unsupported Custom YAML Objects:** If the playbook contains custom YAML objects with the prefix "`!!`", the linter may have difficulty parsing them. Avoid using unsupported YAML objects in your playbooks. 4. **Vault Decryption Issue:** In cases where the linter fails to decrypt an inline "`!vault`" block, it can trigger a "load-failure" error. This issue might be related to problems with the vault password or the encryption format. ### Handling the load-failure Error: The "`load-failure`" error is not skippable, meaning it cannot be added to the `warn_list` or `skip_list` to bypass linting. However, in situations where the error is related to vault decryption and cannot be avoided, you can add the offen... --- ## Ansible troubleshooting — Error loop-var-prefix URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-loop-var-prefix Description: The loop-var-prefix rule in Ansible promotes clear variable naming in loops to avoid ambiguity, especially in nested or multiple loop scenarios. ## Introduction When writing Ansible playbooks, it's important to maintain clarity and consistency in your code to ensure it's easy to understand and maintain. One common area where clarity can be improved is in handling loop variables, especially in nested loops. To address this, Ansible provides a rule called "`loop-var-prefix`" to help avoid conflicts and enforce clear variable naming in loops. ## Why is Variable Naming Important in Loops? In Ansible, loops are frequently used to iterate over lists of items and perform tasks. By default, Ansible uses the variable name "item" for loop iterations. While this is convenient, it can lead to ambiguity and confusion when you have nested loops or multiple loops in the same playbook. To address this issue, the "`loop-var-prefix`" rule encourages users to define their loop variables explicitly, providing a more descriptive name. Additionally, it suggests that loop variables should have a prefix, which can be configured according to your preferences. ## Configuring the Loop Variable Prefix The "`loop-var-prefix`" rule allows you to configure the loop variable prefix to match your coding standards. You can change the default behavior by using a regular expression to enforce variable naming conventions. For instance, if you want the loop variable to start with "`myrole_`", you can set the rule in your `.ansible-lint` configuration like this: [code example] With this configuration, loop variables should start with "myrole_" to e... --- ## Ansible troubleshooting — Error markupsafe URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-markupsafe Description: Resolve the No module named markupsafe error in Ansible by reinstalling Ansible, ansible-lint, and python-markupsafe via Homebrew. ## Introduction After upgrading Python to version 3.12 on your Mac using Homebrew, you encountered an error when trying to run Ansible: "`ERROR: No module named 'markupsafe'`". This issue arises because Ansible relies on certain Python modules, and in this case, it seems that the '`markupsafe`' module is missing or not properly installed. Let's go through the steps to resolve this issue: [code example] ### DL;DR [code example] ### Step 1: Identify the Problem The error message indicates that the 'markupsafe' module is not found. This module is a dependency for Ansible and needs to be installed. ### Step 2: Check for 'markupsafe' Installation First, let's check if the 'markupsafe' module is installed. Open your terminal and run: [code example] If the module is not installed, you will need to install it. If it's already installed, proceed to the next step. ### Step 3: Install 'markupsafe' Install the 'markupsafe' module using the following command: [code example] This command uses Homebrew package manager, `brew`, to install the '`markupsafe`' module. Otherwise you can use: [code example] This command uses Python's package manager, `pip`, to install the '`markupsafe`' module. ### Step 4: Verify 'markupsafe' Installation After installing 'markupsafe', verify that the installation was successful: [code example] If there are no errors, the '`markupsafe`' module is now installed correctly. ### Step 5: Reinstall Ansible and Ansible-Lint Now that '`markupsafe`'... --- ## Ansible troubleshooting — Error meta-runtime URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-meta-runtime Description: Fix the Ansible Lint meta-runtime error — requires_ansible version constraints in meta/runtime.yml for collections. With tested, real-world examples. ## Introduction The `meta-runtime` rule in Ansible Lint validates the `requires_ansible` key in a collection's `meta/runtime.yml` file. This key specifies which versions of `ansible-core` are compatible with the collection. If the version constraint references an unsupported or end-of-life Ansible version, ansible-lint raises a `schema[meta-runtime]` error. This article covers the rule, correct version constraints, and best practices for collection compatibility. ## Understanding meta/runtime.yml Every Ansible collection should include a `meta/runtime.yml` file that declares: - **`requires_ansible`**: The minimum ansible-core version required - **Plugin routing**: Redirects, deprecations, and removals for modules/plugins [code example] ## The Error ### Problematic Code [code example] ### Lint Output [code example] The error occurs because `ansible-core 2.9` does not exist (Ansible 2.9 was the monolithic package before the split). The `requires_ansible` key must reference valid `ansible-core` versions. ### Correct Code [code example] ## Supported ansible-core Versions As of 2026, the currently supported versions: | ansible-core | Status | End of Life | |---|---|---| | 2.16.x | Maintained | Nov 2025 | | 2.17.x | Maintained | May 2026 | | 2.18.x | Current | Nov 2026 | | 2.19.x | Current | May 2027 | | 2.20.x | Latest | Nov 2027 | **End of life (no longer valid for `requires_ansible`):** | ansible-core | EOL Date | |---|---| | 2.13.x | Nov 2023 | | 2.14.x | May ... --- ## Ansible troubleshooting — Error no-free-form URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-no-free-form Description: In Ansible, the no-free-form rule promotes clarity and reliability by discouraging free-form syntax in module calls within playbooks. ## Ansible Rule "no-free-form": Shifting from Free-Form to Full Syntax In the world of automation, precision and clarity are paramount. Ansible, the powerful automation tool, brings forth an array of features to make automation tasks simpler and more efficient. However, it also lays down specific rules to ensure the correctness and maintainability of your Ansible playbooks. One such rule is **"no-free-form,"** which enforces the use of full syntax over free-form syntax in module calling. ## What Is Free-Form Syntax? Free-form syntax, also known as inline or shorthand syntax, is a way to specify module parameters by simply listing them. While this might seem convenient, it can lead to subtle bugs and hinder the functionality of code editors and integrated development environments (IDEs) in providing feedback, autocompletion, and validation. Here's an example of problematic code with free-form syntax: [code example] In this code, the use of free-form syntax in the `ansible.builtin.command` and `ansible.builtin.raw` modules can create issues and hinder the editing experience. Output [code example] ## Adhering to the Rule "no-free-form" To adhere to **"no-free-form,"** it's important to switch to the full syntax for module calling. Here's the correct way to write the same code without using free-form syntax: [code example] In this corrected code, we've used the full syntax for the `ansible.builtin.command` and `ansible.builtin.raw` modules, making the code more readab... --- ## Ansible troubleshooting — Error no-prompting URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-no-prompting Description: Here's an example of problematic code in an Ansible playbook, including user prompts and a 5-minute pause, which violates best practices and can be. # Avoid Unnecessary Prompting and Pausing in Ansible Playbooks Ansible is a powerful automation tool designed to simplify complex IT tasks. While it's excellent for handling various configurations and deployments, it's important to create playbooks that can run unattended, particularly in Continuous Integration/Continuous Deployment (CI/CD) pipelines. This article discusses the Ansible playbook error "no-prompting," which helps ensure that your playbooks are suitable for automated, unattended execution. ## The Challenge: Prompts and Pauses Sometimes, playbooks include user prompts or unnecessary pauses. While these may be useful for manual interventions in some situations, they can become obstacles when you want your playbooks to execute automatically. For instance, consider a playbook that asks for user credentials via `vars_prompt` and includes tasks like `ansible.builtin.pause` to create wait times. In a CI/CD environment, these prompts and pauses can lead to stalled automation pipelines. ## The Solution: `no-prompting` Rule To prevent these issues, Ansible provides the `no-prompting` rule in Ansible-lint. This rule checks playbooks for the presence of `vars_prompt` or the `ansible.builtin.pause` module, which are prompts or pauses that can disrupt automation. By enabling this rule, you can identify and rectify any occurrences of these elements in your playbooks. ### Enabling the Rule To use the `no-prompting` rule, you need to enable it in your Ansible-lint config... --- ## Ansible troubleshooting — Error no-same-owner URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-no-same-owner Description: Learn to avoid pitfalls with Ansible no-same-owner rule, crucial for preventing unintended owner and group mismatches in file transfers. ## Avoiding Common Pitfalls in Ansible: no-same-owner Rule When working with Ansible to automate server configurations, it's important to ensure that your playbooks run smoothly and securely. One common pitfall to watch out for is preserving the owner and group of files during transfers between hosts. Ansible provides a helpful rule, `no-same-owner`, which checks for and prevents this issue. ### The Problem: Owner and Group Mismatches In many scenarios, you might have files on your source host with specific owners and groups. However, when transferring these files to a remote host, preserving the owner and group might not be appropriate. This discrepancy can lead to a range of problems, such as permission errors, security concerns, or even unintentional data leakage. Consider a situation where you are using Ansible to synchronize configuration files or extract archives on remote hosts. If you transfer the owner and group along with the files, you may inadvertently grant unnecessary access to sensitive data, potentially compromising security. ### The Solution: Applying `no-same-owner` Rule To address this issue, Ansible provides the `no-same-owner` rule. You can enable this rule in your Ansible-lint configuration. By doing so, you instruct Ansible to avoid transferring the owner and group during various operations, ensuring that your playbooks run smoothly without unintentionally transferring ownership information. Here's how you can configure this rule: [code example]... --- ## Ansible troubleshooting — Error only-builtins URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-only-builtins Description: Maintain consistency and simplicity in Ansible playbooks with the only-builtins rule, ensuring exclusive use of ansible.builtin actions. ## Avoid Non-Builtin Actions in Your Ansible Playbooks In the realm of Ansible playbooks, maintaining consistency and simplicity is key to a successful automation strategy. One way to achieve this is by adhering to the "`only-builtins`" rule, which emphasizes the usage of built-in actions from the `ansible.builtin` collection exclusively. ## Keeping It Builtin The "`only-builtins`" rule acts as a guardrail to ensure that you don't inadvertently wander into using non-built-in collections, plugins, or modules within your Ansible playbooks. While Ansible's ecosystem is rich with various extensions, sticking to the built-in collection can streamline your playbook's structure and maintainability. ### Enable the `only-builtins` Rule You can enable this rule in your Ansible-lint configuration. By doing so, you instruct Ansible to validate only builtin modules. Here's how you can configure this rule: [code example] ## Problematic Code [code example] In the problematic code above, we can see a playbook that attempts to deploy a Helm chart for Prometheus but uses the `kubernetes.core.helm` module, which is not part of the built-in `ansible.builtin` collection. Ansible Lint Output [code example] ## Correcting the Code To adhere to the "`only-builtins`" rule, you should rewrite the playbook as follows: [code example] In the corrected code, we replaced the non-built-in `kubernetes.core.helm` module with a simple `ansible.builtin.shell` module, ensuring that we are using on... --- ## Ansible troubleshooting — Error use-loop: Migrating from with_* to loop URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-use-loop Description: Fix the ansible-lint use-loop error by migrating from with_items, with_dict, and with_fileglob to the modern loop syntax. Includes conversion examples for. The `use-loop` rule in ansible-lint warns when you use the older `with_*` looping syntax instead of the modern `loop` keyword. While `with_*` still works, `loop` is the recommended syntax for all new playbooks. This guide shows you how to convert every `with_*` pattern to `loop`. ## Understanding the Error When ansible-lint finds `with_*` syntax, it produces: [code example] ### Why the Rule Exists - **`loop` is the modern standard** — introduced in Ansible 2.5 as a replacement for `with_*` - **Consistency** — one looping syntax instead of 20+ `with_*` variants - **Future-proofing** — `with_*` may eventually be deprecated - **Readability** — `loop` combined with filters is more explicit about data transformations ## Quick Conversion Reference | Old Syntax | New Syntax | |-----------|-----------| | `with_items: list` | `loop: "{{ list }}"` | | `with_list: list` | `loop: "{{ list }}"` | | `with_dict: dict` | `loop: "{{ dict \| dict2items }}"` | | `with_fileglob: pattern` | `loop: "{{ query('fileglob', pattern) }}"` | | `with_filetree: path` | `loop: "{{ query('filetree', path) }}"` | | `with_together: [a, b]` | `loop: "{{ a \| zip(b) \| list }}"` | | `with_nested: [a, b]` | `loop: "{{ a \| product(b) \| list }}"` | | `with_subelements: [list, key]` | `loop: "{{ list \| subelements(key) }}"` | | `with_sequence: ...` | `loop: "{{ range(start, end+1) \| list }}"` | | `with_random_choice: list` | `loop: "{{ [list \| random] }}"` | | `with_first_found: list` | `loop: "{{ query... --- ## Ansible troubleshooting — Error: name[casing] URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-name-casing Description: Fix the Ansible Lint name[casing] rule — all task and play names must start with an uppercase letter for consistent, readable playbook output. ## Introduction The `name[casing]` rule in Ansible Lint requires that all task and play names start with an uppercase letter. This ensures consistent, professional output in logs, Ansible Tower/AWX job output, and terminal displays. This article covers the rule, why it matters, how to fix violations, and how to auto-fix existing playbooks. ## The Rule Every `name:` field in plays, tasks, handlers, and blocks must start with an uppercase letter (A-Z). ### Problematic Code [code example] ### Lint Output [code example] ### Fixed Code [code example] ## Why Uppercase Matters ### 1. Professional Log Output Task names appear in playbook output, Tower/AWX job logs, and ARA records: [code example] ### 2. Consistency Across Teams Without a standard, you end up with mixed styles: [code example] [code example] ### 3. Sentence Case Is Natural English Task names read as sentences describing what the task does. English sentences start with uppercase: [code example] ## Where the Rule Applies | Location | Applies? | Example | |---|---|---| | Play name | ✅ Yes | `- name: Deploy webserver` | | Task name | ✅ Yes | `- name: Install packages` | | Handler name | ✅ Yes | `- name: Restart nginx` | | Block name | ✅ Yes | `- name: Database setup` | | Role name | ❌ No | Role names use snake_case | | Variable names | ❌ No | Variables use snake_case | ## Auto-Fix ansible-lint can automatically capitalize task names: [code example] ### Before Auto-Fix [code example] ### After Au... --- ## Ansible troubleshooting — Error: name[play] URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-name-play Description: The name rule in Ansible ensures clear and consistent naming conventions for tasks and plays in playbooks, enhancing readability and troubleshooting. ## Introduction In the world of Ansible, where automation and orchestration reign supreme, playbooks serve as the backbone of defining and executing tasks. Playbooks provide a structured way to describe configurations, deployments, and automation processes. They are your go-to tool for defining what needs to happen on remote servers, which is why it's crucial to ensure that playbooks are well-structured, readable, and adhere to best practices. However, even the most experienced Ansible users can make common mistakes in their playbooks, leading to potential errors and difficulties when troubleshooting. One of these common issues is related to the naming of plays within playbooks. ## The Role of Names in Playbooks In Ansible playbooks, names play a critical role. They serve as identifiers for executed operations on the console, in log files, and on web interfaces. When you glance at a name within a playbook, you should instantly understand what task or play is doing. A well-named task or play provides clarity and enhances the playbook's maintainability. ## The name Rule To ensure the quality and readability of Ansible playbooks, the Ansible community has developed a set of rules, often enforced by linters, to identify issues related to naming conventions. These rules, under the '`name`' category, help maintain a standardized and consistent naming structure within your playbooks. Here are some specific aspects addressed by the '`name`' rule: 1. **`name[casing]`:** This r... --- ## Ansible troubleshooting — Error: name[prefix] URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-name-prefix Description: Fix the Ansible Lint name[prefix] rule — prefix task names with file stems for clearer playbook organization and debugging. ## Introduction The `name[prefix]` rule in Ansible Lint recommends prefixing task names with the file stem (filename without `.yml`) in task files that are not `main.yml`. This opt-in rule improves traceability — when a task fails, the prefix immediately tells you which file contains the failing task, eliminating guesswork in complex roles with multiple task files. ## Why Task Naming Matters When a playbook fails, Ansible shows the task name in the output: [code example] In a simple role, this is clear enough. But in complex roles with multiple included task files: [code example] If a task named "Restart nginx" fails, which file is it in? `configure.yml`? `ssl.yml`? With the `name[prefix]` rule, the task would be named `ssl | Restart nginx`, immediately identifying the source file. ## The Rule ### Problematic Code File: `tasks/install.yml` [code example] ### Lint Output [code example] ### Correct Code [code example] ## Enabling the Rule The `name[prefix]` rule is **opt-in** — it's not active by default. Enable it in your `.ansible-lint` configuration: [code example] Or in YAML format with other settings: [code example] ## How the Prefix Is Determined The expected prefix is the **file stem** — the filename without the `.yml` or `.yaml` extension: | File Path | Expected Prefix | |---|---| | `tasks/install.yml` | `install \| ` | | `tasks/configure.yml` | `configure \| ` | | `tasks/ssl.yml` | `ssl \| ` | | `tasks/backup-db.yml` | `backup-db \| ` | | `handle... --- ## Ansible troubleshooting — Error: name[template] URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-name-template Description: The name[template] error in Ansible highlights issues with task naming, particularly involving improper use of Jinja templates. ## Introduction In the world of IT automation and configuration management, Ansible stands as a powerful tool. Ansible playbooks allow you to define a series of tasks, and these playbooks are designed to be human-readable. They are not just a set of instructions but also serve as documentation for the tasks they perform. One crucial aspect of creating effective and maintainable playbooks is naming conventions. A well-structured playbook with appropriately named tasks is not only easier to understand but also aids in troubleshooting. However, when it comes to naming tasks within Ansible playbooks, you might encounter a specific error called "`name[template]`." In this article, we will delve into the details of this error, what it means, why it's important, and how to address it. ## Understanding the "name[template]" Error In Ansible playbooks, each task should have a name associated with it. This name serves as a label for the task, allowing you to understand its purpose and function. The "`name[template]`" error specifically deals with how you structure the name of your tasks, especially when it involves Jinja templates. Jinja templates are dynamic placeholders that can be used within task names to provide more context or information. However, there are specific guidelines and best practices for using Jinja templates in task names. The "`name[template]`" error is triggered when these guidelines are not followed. ## Best Practices for Using Jinja Templates in Task Names ... --- ## Ansible troubleshooting — Error: no-jinja-when URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-no-jinja-when Description: Fix Ansible Lint no-jinja-when — why you should not use {{ }} in when clauses and how to write correct conditionals. Tested, copy-paste examples included. ## Introduction The `no-jinja-when` rule in Ansible Lint prevents using Jinja2 expressions (double curly braces `{{ }}`) inside `when`, `failed_when`, and `changed_when` clauses. While wrapping conditions in `{{ }}` may appear to work, it is an anti-pattern that can cause subtle bugs, double-evaluation issues, and unexpected behavior. This article explains the rule, demonstrates every common scenario, and shows the correct patterns. ## Why This Rule Exists Ansible processes `when` clauses differently from regular template strings. The `when` clause is **already implicitly a Jinja2 expression** — Ansible automatically evaluates it as Jinja2 without needing `{{ }}`. When you add `{{ }}` inside a `when` clause, you create a **nested expression**: [code example] This double-evaluation can cause problems: 1. **Type coercion issues**: The template renders to a string `"True"`, not a boolean `True` 2. **Undefined variable errors**: Behave differently with nested vs direct evaluation 3. **Performance**: Unnecessary template rendering pass 4. **Readability**: Misleading syntax that confuses other developers ## The Error ### Problematic Code [code example] ### Lint Output [code example] ### Correct Code [code example] ## Common Patterns: Wrong vs Right ### Simple Variable Check [code example] ### Boolean Comparison [code example] ### String Comparison [code example] ### Complex Conditions [code example] ### Variable is Defined [code example] ### Register and C... --- ## Ansible troubleshooting — Failed to connect to the host via ssh host localhost port 22 URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-failed-to-connect-to-the-host-via-ssh-host-localhost-port-22 Description: In Ansible troubleshooting, learn about the Failed to connect to the host via SSH error, common during local testing with ansible_connection local. ## Introduction In today's episode of Ansible Pilot, I'm Luca Berton, and we'll delve into Ansible troubleshooting, focusing on the common error "Failed to connect to the host via SSH: localhost port 22." This error often occurs when testing your code on your local machine using the `ansible_connection local` parameter. ## Understanding the Error The exact error message you might encounter in the terminal is: [code example] This error is a clear indication that Ansible failed to establish an SSH connection to the localhost on port 22. ## Live Demo Let's jump into a live Playbook to reproduce the Ansible connection failed problem and fix it in the inventory file. ### Error Code: `ping.yml` [code example] ### Error Execution Executing the playbook with the error: [code example] ### Fix Code: `ping.yml` [code example] ### Fix Execution Executing the fixed playbook: [code example] ## Links - Local playbooks ## Conclusion In conclusion, you now know how to troubleshoot the common Ansible error "Failed to connect to the host via SSH localhost port 22." By modifying the inventory file and setting `ansible_connection=local`, you can resolve this issue when testing Ansible code on your local machine. If you found this troubleshooting guide helpful, be sure to subscribe for more Ansible insights. --- ## Ansible troubleshooting — fatal template error while templating string URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-fatal-template-error-while-templating-string Description: Explore the FATAL template error while templating string in Ansible. Learn how to diagnose and resolve this runtime issue effectively. ## Introduction Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll be diving into Ansible troubleshooting, focusing on the "FATAL template error while templating string" runtime error. Join me as we explore how to reproduce, troubleshoot, and fix this challenging issue. ## The Demo Let's jump straight into a live Playbook to understand the error practically. In this example, we have a playbook (`template_error_string_error.yml`) attempting to create an empty file with a variable referencing `~/example.txt`. [code example] Executing this playbook (`ansible-playbook -i inventory template_error_string_error.yml`) results in a fatal error: [code example] ## Understanding the Error The error message is clear: "template error while templating string: unexpected '~'." The issue lies in the attempt to use the tilde (`~`) symbol in the variable, which is not a valid attribute for templating. ## Fixing the Code To resolve the issue, we need to correct our playbook. The fixed version (`template_error_string_fix.yml`) uses the correct variable format: [code example] Executing the fixed playbook (`ansible-playbook -i Playbook/inventory troubleshooting/template_error_string_fix.yml`) should now complete without errors: [code example] ## Conclusion In this tutorial, we walked through reproducing, troubleshooting, and fixing the "FATAL template error while templating string" error in Ansible. The key takeaway is to ensure that variables are formatted... --- ## Ansible Troubleshooting — Fix chgrp Failed Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-chgrp-failed Description: Fix the Ansible 'chgrp failed' error. Understand why group lookup fails, verify groups exist on remote hosts, create missing groups, and handle. ## Introduction The `chgrp failed: failed to look up group` error occurs when Ansible tries to set a file's group ownership to a group that doesn't exist on the remote host. This commonly happens with the `file`, `copy`, `template`, and `unarchive` modules. ## The Error [code example] [code example] ## Root Cause Ansible runs `chgrp` on the **remote host** to set file group ownership. The error means the specified group doesn't exist on that host. Common causes: | Cause | Example | |-------|---------| | Group not created yet | Playbook sets file group before creating the group | | Typo in group name | `group: wwww-data` instead of `www-data` | | Different group names across distros | `apache` (RHEL) vs `www-data` (Debian) | | NIS/LDAP not configured | Centralized group not available on this host | | User created without matching group | `useradd -N` skips creating private group | ## Fix 1: Create the Group First [code example] **Task order matters** — always create groups/users before setting file ownership. ## Fix 2: Verify Group Exists [code example] ### Manual Verification on Remote Host [code example] ## Fix 3: Handle Cross-Platform Group Names [code example] ### Common Group Name Differences | Service | RHEL/CentOS | Debian/Ubuntu | |---------|-------------|---------------| | Apache | `apache` | `www-data` | | Nginx | `nginx` | `www-data` | | PostgreSQL | `postgres` | `postgres` | | Docker | `docker` | `docker` | | Nobody | `nobody` | `nogroup` | ## Fi... --- ## Ansible troubleshooting — Kubernetes K8s or OpenShift OCP 401 Unauthorized URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-kubernetes-k8s-openshift-ocp-401-unauthorized Description: Explore troubleshooting steps for Kubernetes 401 Unauthorized errors in Ansible when interacting with Kubernetes or OpenShift clusters. ## Ansible troubleshooting - Kubernetes K8s/OpenShift OCP 401 Unauthorized Today we're going to talk about Ansible troubleshooting, specifically about the "Kubernetes 401 Unauthorized" message. This fatal error message happens when we are trying to execute some code against your Kubernetes K8s or OpenShift OCP cluster without any authentication tokens. These circumstances are usually related to Kubernetes K8s or OpenShift OCP authentication and usually are not related to Ansible Playbook or Ansible configuration. ## Playbook How to reproduce, troubleshoot, and fix the error: "Kubernetes 401 Unauthorized". The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the "Kubernetes 401 Unauthorized" and how to solve it! This Playbook is going to try to create an "example" namespace in a Kubernetes/OpenShift cluster. ### Ansible Playbook code [code example] ### error execution [code example] ### troubleshooting [code example] ### fix execution [code example] ## Conclusion Now you know better how to troubleshoot the Ansible "Kubernetes/OpenShift 401 Unauthorized" message. ## Related guide Related reading: Ansible-driven Kubernetes operations covers this in real-world detail. --- ## Ansible Troubleshooting — literal-compare Lint Rule (601) URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-601-literal-compare Description: Fix the ansible-lint literal-compare rule (601). Learn why comparing to True/False is redundant, how to write clean conditionals, and handle edge cases. ## Introduction The `literal-compare` rule (601) in ansible-lint flags redundant comparisons to `True` or `False` in `when` conditions. While technically correct, these comparisons add noise without value — and can introduce subtle bugs with string-to-boolean conversion. ## The Error [code example] [code example] ## The Fix [code example] For negative conditions: [code example] ## Why It Matters ### 1. Readability [code example] ### 2. Avoid String/Boolean Bugs Variables from inventory or extra-vars may be strings, not booleans: [code example] [code example] ### 3. Consistency Following lint rules ensures all team members write conditions the same way. ## Common Patterns ### Simple Boolean [code example] ### Boolean with bool Filter [code example] ### Compound Conditions [code example] ### Comparing to Specific Values (NOT Affected) These are fine — the rule only applies to `True`/`False` literals: [code example] ### Testing for None/Undefined [code example] ### is sameas Test (Strict Identity Check) If you truly need to distinguish `True` from truthy: [code example] This passes lint and tests identity, not equality. Use only when you need to distinguish `True` from `1` or `"yes"`. ## Suppressing the Rule If you have a legitimate reason: [code example] ## Quick Reference | Instead of | Write | |-----------|-------| | `when: x == True` | `when: x` | | `when: x == False` | `when: not x` | | `when: x != True` | `when: not x` | | `when: x != ... --- ## Ansible troubleshooting — Module Failure on Windows-target URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-module-failure-on-windows-target Description: Discover how to troubleshoot Module Failure on Windows-target in Ansible, focusing on resolving execution errors effectively. ## Introduction Today we’re going to talk about Ansible troubleshooting, specifically about the Module Failure on Windows-target. ## Playbook How to troubleshoot the Module Failure on Windows-target. ## error code [code example] ## error execution [code example] ## fix code [code example] ## fix execution [code example] code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the Module Failure on Windows-target and how to fix it. --- ## Ansible Troubleshooting — name[missing] Lint Rule (502) URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-502-name-missing Description: Fix ansible-lint rule 502 name[missing]. Learn why naming tasks matters, how to write good task names, handle edge cases with include_tasks and blocks,. ## Introduction Rule 502 (`name[missing]`) in ansible-lint requires every task and play to have a `name` field. Names are how you identify what happened in Ansible output, logs, AWX/Tower job reports, and debugging sessions. Without names, output looks like cryptic module calls instead of a readable execution log. ## The Error [code example] [code example] ## The Fix [code example] ## Why Names Matter ### Ansible Output Without Names [code example] Which task did what? Impossible to tell. ### Ansible Output With Names [code example] Now you can: - Debug failures instantly - Review AWX/Tower job output - Understand playbooks months later - Search logs for specific operations ## Writing Good Task Names ### Rules | Rule | Bad | Good | |------|-----|------| | Describe the **action** | `name: yum` | `name: Install nginx` | | Be specific | `name: Configure` | `name: Configure nginx virtual host` | | Use imperative mood | `name: Nginx is installed` | `name: Install nginx` | | Include the target | `name: Start service` | `name: Start nginx service` | | Don't repeat the module | `name: Copy file using copy` | `name: Deploy nginx config` | ### Examples [code example] ## Edge Cases ### Plays Need Names Too [code example] ### Handlers Need Names [code example] ### Blocks Inherit Names [code example] ### include_tasks and import_tasks [code example] ### Roles Tasks in `roles/*/tasks/main.yml` also need names: [code example] ## Suppressing the Rule [code exa... --- ## Ansible Troubleshooting — no-tabs Lint Rule (203) URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-203-no-tabs Description: Fix ansible-lint rule 203 (no-tabs). Understand why YAML forbids tab indentation, configure your editor to use spaces, detect and replace tabs. ## Introduction Ansible-lint rule 203 (`no-tabs`) flags tab characters (`\t`) in playbooks. YAML uses indentation to define structure — mixing tabs and spaces (or using tabs at all) causes parsing errors, invisible formatting bugs, and inconsistent behavior across editors. The fix is simple: always use spaces. ## The Error [code example] [code example] ## Why Tabs Break YAML YAML specification explicitly forbids tab characters for indentation: > "YAML does not allow the use of tabs for indentation." > — YAML Spec §4.2 | Issue | What Happens | |-------|-------------| | Tab in indentation | YAML parser error: `found character '\t' that cannot start any token` | | Tab in string value | May pass YAML parsing but ansible-lint flags it | | Mixed tabs/spaces | Looks aligned in one editor, broken in another | | Tab in Jinja2 expression | Template rendering errors | ## The Fix Replace all tabs with spaces (2 spaces is the Ansible/YAML convention): [code example] ## Find and Replace Tabs ### Using Command Line [code example] ### Using Python [code example] ## Configure Your Editor ### VS Code [code example] ### Vim [code example] ### .editorconfig (Any Editor) [code example] ## Prevention: Pre-commit Hook [code example] [code example] ## Exception: lineinfile Module Rule 203 **does not flag** tabs inside `ansible.builtin.lineinfile` content, because you may legitimately need to insert tab-separated content: [code example] ## yamllint Configuration Pair an... --- ## Ansible troubleshooting — passwordless account URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-passwordless-account Description: Explore the Fatal usermod error in Ansible troubleshooting with Luca Berton on Ansible Pilot, featuring practical solutions and Playbooknstrations. ## Introduction Today we're going to talk about Ansible troubleshooting and specifically about the "Fatal usermod: unlocking the user's password would result in a passwordless account." error. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the `usermod: unlocking the user's password would result in a passwordless account.` error and how to solve it! ## error code - passwordless_error.yml [code example] ## error verification Verify no user example in the target system: [code example] ## error execution output [code example] ## fix code - passwordless_fix.yml [code example] ## fix execution output [code example] ## fix verification [code example] code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the error: "usermod: unlocking the user's password would result in a passwordless account". --- ## Ansible Troubleshooting — syntax-check Rule (911) URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-911-syntax-check Description: Fix Ansible syntax-check errors (rule 911). Understand common causes — undefined variables, YAML indentation, missing colons — with examples and fixes.. ## Introduction Rule 911 (`syntax-check`) is ansible-lint's most critical rule — it's **unskippable**. If your playbook fails `ansible-playbook --syntax-check`, no other linting rules are evaluated. This guide covers the most common syntax errors and how to fix each one. ## The Rule Rule 911 runs `ansible-playbook --syntax-check` on every playbook. If syntax validation fails, all further linting stops. You cannot skip it: [code example] ## Common Syntax Errors ### 1. Undefined Variable in hosts **Error:** [code example] [code example] **Fix:** Add a `default()` filter: [code example] Or define the variable in inventory/group_vars. ### 2. Bad YAML Indentation **Error:** [code example] **Fix:** Align module under the task: [code example] ### 3. Missing Colon After Module Name **Error:** [code example] **Fix:** Add the colon: [code example] ### 4. Tab Characters YAML doesn't allow tabs for indentation: [code example] **Fix:** Replace tabs with spaces (2-space indentation is standard). ### 5. Duplicate Keys [code example] **Fix:** Remove the duplicate. ### 6. Missing Quotes Around Special Characters [code example] **Fix:** Quote the string: [code example] ### 7. Incorrect Variable Syntax [code example] **Fix:** Always quote Jinja2 expressions: [code example] ## How to Run Syntax Check ### Manual Check [code example] ### In CI/CD Pipeline [code example] ### With ansible-lint [code example] ## Pre-commit Hook [code example] ## Debuggin... --- ## Ansible troubleshooting — the "role not found" error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-role-not-found-error Description: Discover how to resolve the role not found error in Ansible by correctly specifying and locating roles for seamless playbook execution. ## Introduction Today we're going to talk about Ansible troubleshooting, specifically about the "role not found" error. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the `role not found errror` and how to solve it! ## error code - role.yml [code example] ## error execution [code example] ## fix code - requirements.yml [code example] ## fix execution [code example] code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the Ansible "role not found" error and how to fix it. --- ## Ansible troubleshooting — undefined variable URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-undefined-variable Description: Explore Ansible troubleshooting with Luca Berton as he addresses undefined variable errors in playbooks, offering practical solutions. ## Introduction Today we're going to talk about Ansible troubleshooting, specifically about the undefined variable errors. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the undefined variable error and how to solve it! ### error code - underfinedvariable_error.yml [code example] ### error execution [code example] ### fix code - underfinedvariable_fix.yml [code example] ### fix execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to troubleshoot the most common Ansible undefined variable error. --- ## Ansible troubleshooting — urlopen error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-urlopen-error Description: How to reproduce the urlopen error in Ansible, troubleshooting, and fix to be able to successfully open an URL in your playbook. ## Introduction Today we're going to talk about Ansible troubleshooting, specifically about` urlopen error`. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the `urlopen error` and how to solve it! ## error code - urlopen_error.yml [code example] ## error execution [code example] ## fix code - urlopen_fix.yml [code example] ## fix execution [code example] code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the Ansible `urlopen error` and solve it! --- ## Ansible troubleshooting — user module password_expiry_min bug and workaround URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-user-module-bug Description: Join Luca Berton on Ansible Pilot as we troubleshoot the user module bug, exploring effective workarounds through live Playbooknstrations. ## Introduction Today we're going to talk about Ansible troubleshooting, specifically about the user module bug and possible workaround. ## Demo The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the user module bug triage and possible workaround! ### error code - userbug_error.yml [code example] ### error execution [code example] We expected a `7` value for `Minimum number of days between password change` but we obtain `0`. ### Troubleshoot - bug report - user module can't handle password expiration parameters correctly #75017 - pull request - user module password expiration fixes #75390 ### workaround - userbug_workaround.yml [code example] ### workaround execution [code example] code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the Ansible user module bug. --- ## Ansible troubleshooting — VMware Unknown error while connecting to vCenter or ESXi URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-vmware-unknown-error-while-connecting-to-vcenter-or-esxi Description: Let’s troubleshoot together the Ansible fatal error “Unknown error while connecting to vCenter or ESXi API, [Errno -2] Name or service not known” to. ## Ansible troubleshooting - VMware Unknown error while connecting to vCenter or ESXi Today we’re going to talk about Ansible troubleshooting, specifically about the “Unknown error while connecting to vCenter or ESXi API, [Errno -2] Name or service not known” message and enable Ansible For VMware. This fatal error message happens when the Ansible controller is not able to connect to your VMware Infrastructure. The root cause might be a misspelled hostname in your Ansible Playbook, a connection problem connecting eventually using a secure VPN connection, or a configuration on the firewall on the target host. ## Playbook How to reproduce, troubleshoot, and fix the error: “Unknown error while connecting to vCenter or ESXi API [Errno -2] Name or service not known” In this Playbook, I’m going to reproduce the error and fix using the correct VMware hostname and verify the network configuration on a demo machine. Let’s suppose our infrastructure is accessible at the hostname “vmware.example.com”. Later in this Playbook, we’re going to see the misspelled “vm-ware.example.com”. ### error code - vm_info.yml [code example] - vars.yml [code example] - inventory [code example] ### error execution [code example] ### fix code - vars.yml [code example] ### fix execution [code example] ## Conclusion Now you know better how to troubleshoot the Ansible “VMware Unknown error while connecting to vCenter or ESXi” message and implement your Ansible For VMware automation. --- ## Ansible troubleshooting — Windows 10 Error 0x80370102 WSL: Windows Subsystem for Linux URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-windows-10-error-0x80370102-wsl Description: How to troubleshoot the Windows 10 WSL: Windows Subsystem for Linux - Error: 0x80370102 The virtual machine could not be started because a required. Today we're going to talk about Ansible troubleshooting, specifically about Windows Subsystem for Linux error 0x80370102. ## Windows Subsystem for Linux - Ubuntu distribution [code example] This is the full error message that you might encounter whether you run the Windows Subsystem for Linux - Ubuntu distribution. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the error 0x80370102 Windows Subsystem for Linux and how to solve it! Live Playbook of Error 0x80370102 Windows Subsystem for Linux and fix on Windows version 10.0.19043 Build 19043. ### error code - error reproducer WSL installation [code example] - error reproducer Ubuntu WSL [code example] Windows Subsystem for Linux version 2 need enabled Windows features: [code example] ### workaround - workaround for unsupported CPU or Virtualization environment [code example] ### workaround execution output [code example] code with ❤️ in GitHub ## Conclusion Now you know how to troubleshoot the Windows Subsystem for Linux error 0x80370102. --- ## Ansible troubleshooting — Windows 11 Error 0x80370102 WSL: Windows Subsystem for Linux URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-windows-11-error-0x80370102-wsl Description: How to troubleshoot the Windows 11 WSL: Windows Subsystem for Linux - Error: 0x80370102 The virtual machine could not be started because a required. Today we're going to talk about Ansible troubleshooting, specifically about Windows Subsystem for Linux error 0x80370102. ## Windows Subsystem for Linux - Ubuntu distribution [code example] This is the full error message that you might encounter whether you run the Windows Subsystem for Linux - Ubuntu distribution. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the error 0x80370102 Windows Subsystem for Linux and how to solve it! Live Playbook of Error 0x80370102 Windows Subsystem for Linux and fix on Windows version 11 Build 22000 release 210604-1624. ### error code - error reproducer WSL installation [code example] - error reproducer Ubuntu WSL [code example] Windows Subsystem for Linux version 2 need enabled Windows features: [code example] If unsupported CPU or Virtualization environment you got the error: [code example] ### workaround - workaround for unsupported CPU or Virtualization environment [code example] ### workaround execution output [code example] [code example] code with ❤️ in GitHub ## Conclusion Now you know how to troubleshoot the Windows Subsystem for Linux error 0x80370102. --- ## Ansible Troubleshooting Installation Issues on macOS and Python URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-installation-issues-on-macos-and-python Description: Learn how to resolve the ImportError for Jinja2 when installing Ansible on macOS using Homebrew, ensuring smooth automation setup. ## Introduction Ansible is a powerful automation tool used by IT professionals to manage and configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero-downtime rolling updates. However, installing and configuring Ansible can sometimes pose challenges, particularly on macOS systems managed by Homebrew. This guide provides a step-by-step solution to resolve a common issue related to the Jinja2 package dependency. ## The Problem: ImportError for Jinja2 Many users encounter the following error when trying to execute Ansible commands on their macOS: [code example] This error typically arises because the Jinja2 package is not found in the Python environment used by Ansible. Let’s walk through the steps to resolve this issue. ## Step 1: Remove Conflicting Ansible Installations First, remove any existing Ansible installations that might be causing conflicts. This includes binaries and related files: [code example] ## Step 2: Create and Activate a Virtual Environment Using a virtual environment is a good practice to avoid conflicts between system-wide and project-specific dependencies. Create and activate a virtual environment with the following commands: [code example] ## Step 3: Install Jinja2 and Ansible in the Virtual Environment With the virtual environment active, install Jinja2 and Ansible: [code example] ## Step 4: Verify the Installation Ensure that both Jinja2 and Ansible are installed and accessible: [... --- ## Ansible Troubleshooting: Destination Does Not Exist Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-destination-does-not-exist Description: To resolve the "destination does not exist" error, ensure the destination path exists and is accessible. Correct the playbook dest variable to a valid. ## Introduction Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll dive into troubleshooting Ansible, specifically focusing on the notorious "destination does not exist error." This error often occurs when attempting to download a file from a URL using Ansible, and it can be a stumbling block for many users. In this article, I'll walk you through the error, Playbooknstrate how to reproduce it, and provide a fix to ensure a smooth Ansible playbook execution. ## The `destination does not exist` Error Let's start by examining the error through a live Playbook. Below is a simplified Ansible playbook (`destinationdoesnotexist_error.yml`) that attempts to download a file using the `get_url` module: [code example] Upon execution, you might encounter the following error: [code example] The error message clearly indicates that the destination does not exist. ## Reproducing and Fixing the Error ### Reproducing the Error To reproduce the error, we can use the provided playbook (`destinationdoesnotexist_error.yml`). This playbook attempts to download the Ansible archive into the home directory, resulting in the "destination does not exist" error. ### Fixing the Error Let's address the issue by modifying the playbook. In the fixed version (`destinationdoesnotexist_fix.yml`), we adjust the destination path to include the current directory: [code example] Now, when you execute this playbook, you should observe a successful download without encounteri... --- ## Ansible Troubleshooting: Fix "Missing Module Parameter" Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-missing-module-parameter Description: Fix Ansible "missing required arguments" and typo-based parameter errors. Complete guide with common module parameters, debugging techniques. ## Introduction The "missing module parameter" error is one of the most common Ansible failures — and it's almost always a typo. A single misspelled parameter name causes Ansible to fail with a cryptic error message. This guide covers how to diagnose these errors quickly and prevent them. ## The Error ### Typo in Parameter Name [code example] **Error message:** [code example] ### Fix [code example] ## Common Typo Patterns | Module | Wrong | Correct | |--------|-------|---------| | `service` | `nme`, `nane` | `name` | | `apt/dnf` | `naem`, `packge` | `name` | | `copy` | `scr`, `souce` | `src` | | `copy` | `des`, `dest` | `dest` | | `file` | `paht`, `pth` | `path` | | `template` | `scr` | `src` | | `user` | `naem` | `name` | | `lineinfile` | `lien`, `lin` | `line` | ## Other Causes ### Missing Required Parameter Entirely [code example] ### Wrong Module for the Task [code example] ### Indentation Pushes Parameter Outside Module [code example] ## How to Diagnose ### Check Module Documentation [code example] ### Syntax Check [code example] ### Use ansible-lint ansible-lint catches many parameter issues before runtime: [code example] ### VS Code Ansible Extension The Red Hat Ansible extension provides: - **Autocomplete** for module parameters (prevents typos) - **Red underlines** for unknown parameters - **Hover docs** showing required vs optional parameters [code example] ## Required Parameters by Common Module | Module | Required Parameters | |-------... --- ## Ansible Troubleshooting: Fix failure downloading Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-failure-downloading Description: Fix the Ansible failure downloading error caused by incorrect URLs, moved resources, network issues, or certificate problems. Complete troubleshooting. ## Introduction The `failure downloading` error is one of the most common issues when working with Ansible modules that fetch content from the internet — including `get_url`, `unarchive`, `yum`, `apt`, and `uri`. This error occurs when Ansible cannot successfully download a resource from a specified URL. In this guide, you'll learn the root causes of download failures and how to fix each one systematically. ## Understanding the Error The `failure downloading` error appears when Ansible attempts to fetch a resource from a URL and the download fails. The error output typically includes: [code example] Or with the `yum` module: [code example] ## Common Causes and Solutions ### 1. Incorrect URL (HTTP 404) The most frequent cause — a misspelled URL or content that has been moved. **Diagnosis**: Try the URL in a browser or with `curl`: [code example] **Fix**: Verify the correct URL format: [code example] ### 2. SSL/TLS Certificate Issues Self-signed certificates or outdated CA bundles cause SSL verification failures. **Error message**: [code example] **Fix** (temporary — for testing only): [code example] **Fix** (proper — add custom CA): [code example] ### 3. Network Connectivity Issues The remote host cannot reach the download URL due to firewall rules, proxy requirements, or DNS issues. **Diagnosis**: [code example] **Fix** — configure proxy: [code example] ### 4. Authentication Required The resource requires credentials for access. **Error message**... --- ## Ansible Troubleshooting: Fix Missing amazon.aws.ec2_ami_info URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-resolving-the-case-of-the-missing-amazon-aws-ec2-ami-info-module Description: Fix the 'couldn't resolve module amazon.aws.ec2_ami_info' error in Ansible. Install AWS collections, configure authentication, pin versions. ## Introduction When running a playbook that uses AWS modules, you may see: [code example] This means the `amazon.aws` collection isn't installed. Here's how to fix it — and set up AWS authentication properly. ## Quick Fix [code example] Verify: [code example] ## Understanding the Error The full error typically includes: [code example] Three separate issues: | Error | Cause | Fix | |-------|-------|-----| | No inventory parsed | Missing `-i inventory` flag | Add inventory file or use `-i localhost,` | | Hosts list is empty | Playbook targets undefined group | Set `hosts: localhost` for local AWS API calls | | Couldn't resolve module | Collection not installed | `ansible-galaxy collection install amazon.aws` | ## Install AWS Collections ### Single Collection [code example] ### With Version Pinning [code example] ### Using requirements.yml (Recommended) [code example] [code example] ### Install Python Dependencies The AWS collections require `boto3` and `botocore`: [code example] Verify: [code example] ## Configure AWS Authentication ### Method 1: Environment Variables [code example] ### Method 2: AWS CLI Profile [code example] ### Method 3: In Playbook (Use Vault!) [code example] ### Method 4: IAM Instance Profile If running on EC2, attach an IAM role — no keys needed: [code example] ## Working Playbook Example [code example] ## Common AWS Collection Modules | Module | Purpose | |--------|---------| | `amazon.aws.ec2_ami_info` | Find AMI ... --- ## Ansible Troubleshooting: Handling Common Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-handling-common-errors Description: Fix the 'run_once may behave differently if strategy is free' warning. Understand run_once with serial, strategy, and delegate_to patterns. ## Ansible Troubleshooting: Handling Common Errors When working with Ansible, the popular open-source automation tool, it's not uncommon to encounter errors and issues. Troubleshooting is a crucial skill for DevOps engineers, system administrators, and IT professionals who use Ansible for managing infrastructure and automating tasks. In this article, we'll delve into various common Ansible errors and how to address them effectively. ## Introduction to Ansible Troubleshooting Ansible simplifies many aspects of system management and configuration automation. However, like any other software, it's not immune to errors. When things don't go as planned, understanding the root cause and finding a solution is vital. Here, we'll explore a collection of common Ansible errors and issues, along with tips on resolving them: ### Error 102: No Jinja2 in When Conditions Sometimes, you might encounter Error 102 when your Ansible playbook has a condition that lacks Jinja2 templating. To fix this, ensure that all your conditions contain the appropriate Jinja2 syntax. - Ansible troubleshooting - Error 102 No Jinja2 in when Conditions.md ### Error 104: Deprecated Bare Vars In Error 104, Ansible informs you of deprecated bare variables. It's a best practice to update your playbook to use a valid variable format, which typically involves enclosing variables in double curly braces. - Ansible troubleshooting - Error 104 Deprecated Bare Vars.md ### Error 105: Deprecated Module Usage Error... --- ## Ansible Troubleshooting: Resolving community.aws.ec2_instance Issues URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-the-community-aws-ec2-instance-module-dilemma Description: Resolve Ansible community.aws.ec2_instance module errors. Fix module not found, missing collections, inventory issues, and migration to. ## Introduction The `community.aws.ec2_instance` module is one of the most commonly used Ansible modules for AWS automation. However, due to Ansible's collection reorganization, users frequently encounter "module could not be resolved" errors when trying to manage EC2 instances. This guide explains why these errors occur and provides step-by-step solutions for every scenario. ## The Error When running a playbook with EC2 instance management, you may see: [code example] Or warnings like: [code example] ## Root Causes ### 1. Missing Collection The `community.aws` collection is not installed on your system. **Diagnosis**: [code example] **Fix**: [code example] ### 2. Module Migration (community.aws → amazon.aws) Starting with `community.aws` 7.0+, the `ec2_instance` module was migrated to the `amazon.aws` collection. The `community.aws.ec2_instance` now redirects to `amazon.aws.ec2_instance`. **Fix** — Update your playbook to use the new FQCN: [code example] Install both collections to ensure compatibility: [code example] ### 3. Incorrect Module Name Typos or using legacy module names that no longer exist: [code example] ### 4. Collection Version Mismatch Your installed collection version doesn't include the module you're trying to use. **Fix**: [code example] ### 5. Virtual Environment or Path Issues The collection is installed in a different Python environment or path than what Ansible is using. **Diagnosis**: [code example] **Fix**: [code example] ... --- ## Ansible Troubleshooting: Resolving the "Invalid Argument" Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-invalid-argument Description: Fix the Ansible file module \"Invalid Argument\" error when creating symlinks on Linux. Reproduce, diagnose, and resolve the fatal error with examples. ## Introduction Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll delve into Ansible troubleshooting, focusing on the infamous "Invalid Argument" error. This error commonly occurs when using the Ansible `file` module to create a symlink in a Linux environment. Let's explore how to reproduce, troubleshoot, and fix this issue. ## The Demo To better understand Ansible troubleshooting, let's dive into a live Playbook. We'll create a playbook (`invalidargument_error.yml`) that attempts to create a symbolic link using the `file` module. In this example, we're trying to symlink `/proc/cpuinfo` to `~/example`. [code example] Executing this playbook (`ansible-playbook -i inventory invalidargument_error.yml`) results in the following error: [code example] ## Understanding the Error The error is clear: "OSError: [Errno 22] Invalid argument." This occurs because the `file` module expects a valid source (`src`) and destination (`dest`) when creating a symlink. In our original playbook, we only provided the `path` and `dest` parameters, leading to the "Invalid argument" error. ## Verbose Execution Executing the playbook with increased verbosity (`-vvv`) provides a more detailed traceback, helping us pinpoint the issue: [code example] The output reveals the exact error in the `file` module, emphasizing the need for a valid source parameter. ## Fixing the Code To resolve the "Invalid Argument" error, we need to correct our playbook. The fixed playboo... --- ## Ansible Tutorial — Complete Beginner Guide 2026 URL: https://www.ansiblebyexample.com/articles/ansible-tutorial-complete-beginner-guide Description: Learn Ansible from scratch. Install, configure, write your first playbook, manage servers, and automate infrastructure. Complete beginner tutorial with. ## Introduction Ansible automates server configuration, application deployment, and infrastructure management. You write YAML playbooks describing the desired state, and Ansible makes it happen — no agents to install, no complex setup. This guide takes you from zero to automating real infrastructure. ## What Is Ansible? Ansible is an **agentless** automation tool. It connects to your servers via SSH (or WinRM for Windows), runs tasks, and disconnects. No software to install on managed hosts. **Key benefits:** - **Agentless** — uses SSH, nothing to install on remote hosts - **YAML-based** — human-readable configuration - **Idempotent** — safe to run multiple times (same result) - **Batteries included** — 3,000+ modules for every use case - **Free and open source** — backed by Red Hat ## Install Ansible [code example] ## Core Concepts [code example] | Concept | Description | |---------|-------------| | **Control Node** | Machine where Ansible runs (your laptop/CI server) | | **Managed Node** | Remote server being managed | | **Inventory** | List of managed hosts | | **Playbook** | YAML file with automation tasks | | **Play** | Maps hosts to tasks | | **Task** | Single action (install package, copy file, etc.) | | **Module** | Unit of code Ansible executes (apt, copy, service) | | **Role** | Reusable bundle of tasks, templates, files | | **Handler** | Task triggered by notifications (e.g., restart service) | ## Step 1: Create Inventory [code example] Or YAML format: ... --- ## Ansible Tutorial for Beginners: Complete Getting Started Guide URL: https://www.ansiblebyexample.com/articles/ansible-tutorial-for-beginners-complete-getting-started-guide Description: Complete Ansible tutorial for beginners. Learn inventory, playbooks, modules, roles, and variables with practical examples. Go from zero to automating. ## What is Ansible? **Ansible** is an open-source automation tool that lets you configure servers, deploy applications, and orchestrate complex workflows — all using simple YAML files called **playbooks**. Why developers love Ansible: - **Agentless** — no software to install on target machines, just SSH - **YAML-based** — human-readable, version-controllable - **Idempotent** — run playbooks multiple times safely - **Batteries included** — 3,000+ built-in modules for every task ## Prerequisites - A Linux/macOS machine (or Windows with WSL) — see How to Install Ansible - Basic terminal/command-line knowledge - SSH access to at least one remote host (or use `localhost`) ## Step 1: Install Ansible [code example] Or try our Ansible Playground — run playbooks in your browser with zero setup. ## Step 2: Create Your Inventory The **inventory** defines which hosts Ansible manages: [code example] Test connectivity: [code example] ## Step 3: Write Your First Playbook Create `first-playbook.yml`: [code example] Run it: [code example] ## Step 4: Understand Key Concepts ### Modules Modules are the units of work in Ansible. Common ones: | Module | Purpose | Example | |--------|---------|---------| | `ansible.builtin.apt` | Install packages (Debian) | `apt: name=nginx state=present` | | `ansible.builtin.yum` | Install packages (RHEL) | `yum: name=httpd state=present` | | `ansible.builtin.copy` | Copy files | `copy: src=file.txt dest=/tmp/` | | `ansible.builtin.template` ... --- ## Ansible ufw Module — Manage Firewall Rules on Ubuntu URL: https://www.ansiblebyexample.com/articles/open-firewall-ports-in-debian-like-systems-ansible-module-ufw Description: Open and close firewall ports on Ubuntu and Debian with community.general.ufw. Allow SSH, HTTP/HTTPS, rate limiting, and set default deny policies. The `community.general.ufw` module manages the Uncomplicated Firewall (UFW) on Debian, Ubuntu, and Linux Mint. Use it to open and close ports, set default policies, enable rate limiting, and toggle UFW — all idempotently from your Ansible playbooks. ## Module Overview `community.general.ufw` is part of the Ansible community collection and requires Ansible 2.9+. It controls UFW on Debian-based distributions (Debian, Ubuntu, Mint). ## Parameters The parameter list is pretty wide but this are the most important options for our use case to open firewall ports. The first set of parameters controls UFW program and the second the single rules. ### UFW program parameters - default _string_ (policy) - allow / deny / reject - logging _string_ - on / off / low / medium / high /full - **state** _string_ - enabled / present / absent / disabled Let's start with three UFW program parameters. The "default" parameter, also called as "policy", change the default policy for incoming or outgoing traffic. The "logging" parameter toggles UFW logging. Logged packets use the LOG_KERN syslog facility. The "state" parameter specify to enable or disable firewall. Four options are possible: - "enabled" reloads firewall and enables firewall on boot, - "disabled" unloads firewall and disables firewall on boot, - "reloaded" reloads firewall, - "reset" disables and resets firewall to installation defaults. ### rule-specific parameters - rule _string_ - allow / deny / limit / reject - name _string_ (a... --- ## Ansible UFW Module — Manage Ubuntu Firewall Rules URL: https://www.ansiblebyexample.com/articles/ansible-ufw-module-manage-ubuntu-firewall-rules Description: Ansible UFW Module guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible UFW Module — Manage Ubuntu Firewall Rules ## Introduction Manage Ubuntu Firewall Rules. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible UFW Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible unarchive — Extract Archives URL: https://www.ansiblebyexample.com/articles/ansible-unarchive-module-extract-tar-zip Description: Use the Ansible unarchive module to extract tar.gz, zip, and bz2 archives. Download and extract from URLs, set permissions, and manage extracted files. ## Introduction **Ansible unarchive** (`ansible.builtin.unarchive`) is the module for extracting compressed archives — `.tar.gz`, `.zip`, `.tar.bz2`, `.tar.xz` — onto a remote host. It can unpack an archive already on the control node, one already present on the remote host (`remote_src: true`), or download it directly from a URL and extract it in one task. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `src` | (required) | Archive path or URL | | `dest` | (required) | Extraction destination | | `remote_src` | `false` | Archive is on remote host (or URL) | | `owner` | — | Owner of extracted files | | `group` | — | Group of extracted files | | `mode` | — | Permissions of extracted files | | `creates` | — | Skip if this path exists (idempotency) | | `exclude` | — | List of files/dirs to exclude | | `include` | — | List of files/dirs to include (extract only these) | | `extra_opts` | — | Extra options for tar/unzip command | | `keep_newer` | `false` | Don't overwrite newer files on remote | | `list_files` | `false` | Return list of extracted files | | `validate_certs` | `true` | Validate SSL when downloading URLs | ## Common Patterns ### Download and Install Software [code example] ### Deploy Application Release [code example] ### Extract Specific Files Only [code example] ### Extract and List Files [code example] ### Strip Top-Level Directory Many archives contain a top-level directory (e... --- ## Ansible Undefined Variable Error — 12 Real Examples and Fixes URL: https://www.ansiblebyexample.com/articles/ansible-undefined-variable-error-examples-fixes Description: Fix Ansible undefined variable errors. Learn 12 real-world causes with solutions: typos, missing defaults, hostvars, conditionals, and Jinja2 scope issues. ## Introduction `AnsibleUndefinedVariable: 'variable_name' is undefined` is one of the most common Ansible errors. It means a variable you referenced doesn't exist at the point where Ansible tries to use it. This guide covers 12 real-world causes with exact fixes. ## Error Format [code example] ## 1. Simple Typo [code example] ## 2. Variable Not Defined Anywhere [code example] ## 3. Missing default() Filter [code example] ## 4. Variable from Another Host (hostvars) [code example] ## 5. Facts Not Gathered [code example] ## 6. Variable Scope in Blocks [code example] ## 7. Conditional Variable with when [code example] ## 8. Registered Variable When Task Skipped [code example] ## 9. Dict Key Missing [code example] ## 10. Variable in Role Defaults Not Overridden [code example] ## 11. Loop Variable Name Collision [code example] ## 12. Jinja2 Variable Scope in Loops [code example] ## Prevention Best Practices [code example] ## Ansible 13 Note In ansible-core 2.20, `INJECT_FACTS_AS_VARS` is deprecated. If you access facts as `ansible_distribution` instead of `ansible_facts['distribution']`, you'll get deprecation warnings now and undefined errors in ansible-core 2.24. ## Related Articles - Ansible Variables Guide - Ansible Error Handling - Ansible Jinja2 Templates - Ansible debug Module ## Conclusion Most undefined variable errors come from a few causes: typos, missing `default()` filters, skipped tasks with `register`, or accessing variables from o... --- ## Ansible Undefined Variable Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-undefined-variable-error-fix-and-solutions Description: Fix undefined variable errors from missing vars, typos, and scope issues in Ansible. With clear, copy-paste, step-by-step examples. # Ansible Undefined Variable Error — Fix and Solutions ## Introduction Fix undefined variable errors from missing vars, typos, and scope issues in Ansible. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Fix undefined variable errors from missing vars, typos, and scope issues in Ansible. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible until Retry — Retry Tasks Until Success URL: https://www.ansiblebyexample.com/articles/ansible-until-retry-retry-tasks-until-success Description: Use Ansible until loops to retry failed tasks with configurable retries, delay, and conditions. Handle flaky APIs, wait for services, and polling patterns. # Ansible until Retry — Retry Tasks Until Success ## Introduction Some tasks fail temporarily — APIs return 503 during deploys, services take time to start, DNS propagates slowly. Ansible's `until` loop retries a task until a condition is met or retries are exhausted. This is essential for reliable automation in environments where transient failures are normal. ## Basic Syntax [code example] ## Common Patterns ### Wait for Service to Start [code example] ### Wait for Port to Open [code example] ### Retry Flaky API Calls [code example] ### Wait for Cloud Instance [code example] ### Wait for File to Appear [code example] ### Wait for Command Output [code example] ## Advanced Conditions ### Multiple Conditions (AND) [code example] ### Complex Expressions [code example] ## Retry with Rescue (Fallback) [code example] ## Default Values | Parameter | Default | Description | |-----------|---------|-------------| | `retries` | 3 | Number of retry attempts | | `delay` | 5 | Seconds between retries | | `until` | (required) | Condition to check | ## Calculating Timeouts [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Task fails after all retries | Increase `retries` or `delay`; check if service actually starts | | "FAILED - RETRYING" floods output | Normal; use `-v` for less noise or callback plugin | | Condition never matches | Debug with `ansible.builtin.debug` to see actual values | | Retry on wrong condition | Ensure `regist... --- ## Ansible URI — POST & Token Auth Demo URL: https://www.ansiblebyexample.com/articles/token-based-authentication-in-rest-api-interact-with-webservice-ansible-module-uri Description: Use Ansible to send a POST request and retrieve a token from a server. Learn to automate login processes with Ansible's URI module. ## How to authenticate requests using the REST API token with Ansible? Also called Token Based Authentication in REST API. ## Ansible Token Based Authentication in REST API - ansible.builtin.uri - Interacts with webservices supports Digest, Basic, and WSSE HTTP authentication mechanisms Today we're talking about the Ansible module uri. The full name is `ansible.builtin.uri`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years and it works in a different variety of POSIX operating systems. It interacts with web services and supports Digest, Basic, and WSSE HTTP authentication mechanisms. If you need to download content, use the Ansible `ansible.builtin.get_url` module. For Windows targets, use the `ansible.windows.win_uri` module instead. ## Parameters - url string - (http|https)://host.domain[:port]/path - method string - "GET", "POST", "PUT", "PATCH", "DELETE" - user (url_username), password (url_password) string - username, password - force_basic_auth boolean - no,yes - Basic authentication header - status_code list/integer - [200, 202] - headers dictionary - custom HTTP headers, Content-Type - body_format string - raw, json, form-urlencoded, form-multipart - body raw - return_content boolean - no/yes - return the body of the response - timeout integer - 30 This module has some parameters to perform any tasks. The only required is "url", where you specify the API URL. The param... --- ## Ansible user — Change Password URL: https://www.ansiblebyexample.com/articles/change-user-password-ansible-module-user Description: Change user passwords on Linux with Ansible user module. SHA-512 hashing with password_hash filter, Vault encryption, bulk updates, and idempotent. ## Introduction Changing user passwords across multiple Linux servers is a common administrative task that Ansible automates securely. The `ansible.builtin.user` module requires passwords in hashed form (not plaintext), which Ansible's `password_hash` filter handles automatically. This article covers basic password changes, Vault-encrypted passwords, bulk updates, password policies, and idempotent management. ## Basic Password Change [code example] ### Execution [code example] ### Verify [code example] ## Understanding password_hash Linux stores passwords as hashes in `/etc/shadow`. Ansible requires pre-hashed passwords — the `password_hash` filter generates them: [code example] ### The Idempotency Problem Without a fixed salt, `password_hash` generates a random salt each run, causing `changed` every time: [code example] Or use `update_password: on_create` to only set the password when creating the user: [code example] ## Secure Passwords with Ansible Vault Never store plaintext passwords in playbooks. Use Ansible Vault: ### Create Encrypted Variable [code example] ### Use in Playbook [code example] ### Use Vault File [code example] [code example] [code example] ## Bulk Password Changes ### Multiple Users from a List [code example] ### Random Password Generation [code example] ## Password Expiry and Policies ### Force Password Change on Next Login [code example] ### Set Password Expiry [code example] ### Lock and Unlock Accounts [code exam... --- ## Ansible user — Remove Accounts URL: https://www.ansiblebyexample.com/articles/remove-user-account-ansible-module-user Description: How to remove user accounts with Ansible user module. Delete users, remove home directories, and manage accounts across Linux, macOS, and FreeBSD.. ## How to Remove a User Account with Ansible The `ansible.builtin.user` module with `state: absent` removes user accounts from Linux, macOS, and FreeBSD systems. Add `remove: true` to also delete the home directory and mail spool. ## Quick Example [code example] ## Parameters for User Removal | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `name` | string | — | Username to remove (required) | | `state` | string | present | Set to `absent` to delete | | `remove` | boolean | false | Remove home dir and mail spool | | `force` | boolean | false | Force removal even if user is logged in | ## Remove User and Home Directory [code example] This is equivalent to running `userdel --remove john` on Linux. **What gets removed:** - Home directory (e.g., `/home/john`) - Mail spool (e.g., `/var/mail/john`) - User entry from `/etc/passwd` and `/etc/shadow` - Group entry if it was a user-private group **What does NOT get removed:** - Files owned by the user outside their home directory - Cron jobs (remove separately) - systemd user services ## Remove User Without Deleting Files [code example] ## Force Remove Logged-In User [code example] ⚠️ **Use with caution** — forcing removal of a logged-in user can cause data loss. ## Remove Multiple Users [code example] ## Remove Users Not in a List [code example] ## Also Clean Up Cron Jobs [code example] ## Full Offboarding Playbook [code example] ## Windows Users For Windows hosts, us... --- ## Ansible user Module — Create Users URL: https://www.ansiblebyexample.com/articles/create-user-account-ansible-module-user Description: Complete guide to ansible.builtin.user module — create accounts, set passwords with SHA-512, manage groups, generate SSH keys, and handle bulk user. ## Introduction Managing user accounts is one of the most fundamental tasks in Linux system administration. The Ansible `ansible.builtin.user` module provides a declarative, idempotent way to create, modify, and remove user accounts across your entire infrastructure. This article covers everything from basic user creation to advanced scenarios including password hashing, SSH key generation, group management, and account expiration. ## Module Overview The `ansible.builtin.user` module is a builtin module shipped with Ansible core. It manages user accounts on Linux, macOS, FreeBSD, and SunOS systems. Under the hood it uses: - **Linux**: `useradd`, `usermod`, `userdel` - **FreeBSD**: `pw useradd` - **macOS**: `dscl create` For Windows targets, use `ansible.windows.win_user` instead. ## Parameters Reference | Parameter | Type | Description | |---|---|---| | `name` | string (required) | Username to create/manage | | `state` | string | `present` (default) or `absent` | | `password` | string | Hashed password (use `password_hash` filter) | | `uid` | integer | Numeric user ID | | `group` | string | Primary group | | `groups` | list | Additional groups | | `append` | boolean | Append to groups (`true`) or replace (`false`, default) | | `shell` | string | Login shell (e.g., `/bin/bash`) | | `home` | string | Home directory path | | `create_home` | boolean | Create home directory (`true` default) | | `comment` | string | GECOS field / user description | | `system` | boolean | Cre... --- ## Ansible user Module — Enable and Unlock URL: https://www.ansiblebyexample.com/articles/enable-user-account-ansible-module-user Description: Re-enable a locked Linux user account with Ansible: set password_lock: false, restore the /bin/bash shell, and verify access — with playbook examples. ## How to Enable a user account with Ansible? ## Ansible enable user account Today we're talking about the Ansible module `user`. The full name is ansible.builtin.user, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts. It supports a huge variety of Linux distributions, SunOS and macOS, and FreeBSD. For Windows, use the `ansible.windows.win_user` module instead. ## Parameters - name string - username - state string - present/absent - password_lock boolean - no/yes - shell string - "/bin/bash" This module has many parameters to perform any task. The only required is "name", which is the username. The parameter "state" allows us to create or delete a user. The "password_lock" parameter specifies to unlock the user password if locked. This parameter uses the `passwd` tool to change a password by changing it to a value that matches no possible encrypted value (it adds a ´!´ at the beginning of the password). To enable our user obviously we need to disable this parameter. The "shell" parameter specifies the user shell. Two very special are the `nologin` and `false` shell. Apply the value of "/bin/bash" is going to restore user access. ## Playbook Let's jump into a real-life Ansible Playbook to enable a user without password lock and with the appropriate shell. ### code - enable.yml [code example] ### output [code example] ### verification [code exampl... --- ## Ansible user Module — Linux Accounts URL: https://www.ansiblebyexample.com/articles/ansible-user-module-manage-linux-users Description: Use the Ansible user module to create, modify, and delete Linux users. Set passwords, SSH keys, groups, shells, and home directories. ## Introduction `ansible.builtin.user` manages user accounts on Linux and Unix systems. Create users, set passwords, manage group memberships, configure SSH keys, set shells, and control home directories — all idempotently. ## Basic Usage [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Username | | `state` | `present` | `present` or `absent` | | `uid` | — | User ID | | `group` | — | Primary group | | `groups` | — | Supplementary groups | | `append` | `false` | Append to groups (vs replace) | | `shell` | — | Login shell | | `home` | — | Home directory path | | `create_home` | `true` | Create home directory | | `password` | — | Hashed password | | `ssh_key_file` | — | SSH key file path | | `generate_ssh_key` | `false` | Generate SSH key pair | | `comment` | — | GECOS field (full name) | | `system` | `false` | Create system account | | `remove` | `false` | Remove home dir on `absent` | | `expires` | — | Account expiration (epoch) | | `password_lock` | — | Lock password | ## Create Users [code example] ## Set Password Passwords must be hashed. **Never use plaintext passwords.** [code example] Generate hash on command line: [code example] ## Group Management [code example] ⚠️ **Common mistake**: Forgetting `append: true` replaces all supplementary groups! ## SSH Keys [code example] ## Delete Users [code example] ## Account Expiration [code example] ## Practical Patterns ### Sudo... --- ## Ansible user Module — Linux Users URL: https://www.ansiblebyexample.com/articles/ansible-user-module-manage-linux-users-groups Description: Use the Ansible user module to create, modify, and remove Linux users. Set passwords, SSH keys, groups, shells, and home directories with practical. ## Introduction `ansible.builtin.user` manages Linux user accounts — create users, set passwords, manage groups, configure SSH keys, set shells, and remove accounts. For groups, use `ansible.builtin.group`. ## Create a User [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Username | | `state` | `present` | `present` or `absent` | | `uid` | — | User ID | | `group` | — | Primary group | | `groups` | — | Supplementary groups | | `append` | `false` | Append to groups (don't replace) | | `shell` | — | Login shell | | `home` | — | Home directory path | | `create_home` | `true` | Create home directory | | `comment` | — | GECOS field (full name) | | `password` | — | Hashed password | | `password_lock` | — | Lock password (disable login) | | `system` | `false` | System account | | `generate_ssh_key` | `false` | Generate SSH keypair | | `ssh_key_bits` | 4096 | SSH key size | | `ssh_key_type` | `rsa` | SSH key type | | `ssh_key_comment` | — | SSH key comment | | `expires` | — | Account expiry (epoch) | | `remove` | `false` | Remove home dir on `state: absent` | | `force` | `false` | Force remove on `state: absent` | ## Manage Groups [code example] ## Set Passwords [code example] ## SSH Keys [code example] ## Remove a User [code example] ## System Accounts [code example] ## Practical Patterns ### Provision Multiple Users [code example] ### Sudoers Access [code example] ### Deploy User wit... --- ## Ansible user Module — Users & Groups URL: https://www.ansiblebyexample.com/articles/ansible-user-module-manage-linux-users-and-groups Description: Complete guide to the Ansible user module — create users, set passwords, manage groups, SSH keys, and home directories. Includes group module examples. ## Create a User [code example] ## Create a User with Password [code example] Using Ansible Vault (recommended): [code example] ## Add User to Groups [code example] ## Create a Group [code example] ## Set Up SSH Key [code example] ## Create Multiple Users [code example] ## Remove a User [code example] ## System User (No Login) [code example] ## Set Password Expiration [code example] ## Full User Provisioning Playbook [code example] ## Parameters Reference | Parameter | Description | Example | |-----------|-------------|---------| | `name` | Username | `deploy` | | `state` | present/absent | `present` | | `password` | Hashed password | `"{{ pass \| password_hash('sha512') }}"` | | `groups` | Supplementary groups | `sudo,docker` | | `append` | Append to groups (don't replace) | `true` | | `shell` | Login shell | `/bin/bash` | | `home` | Home directory path | `/opt/myapp` | | `create_home` | Create home dir | `true` | | `remove` | Remove home on delete | `true` | | `system` | System account | `true` | | `uid` | User ID | `1500` | | `generate_ssh_key` | Create SSH keypair | `true` | | `ssh_key_type` | Key type | `ed25519` | | `expires` | Account expiry (unix timestamp) | `1735689600` | --- *Explore 800+ Ansible tutorials on AnsibleByExample.* --- ## Ansible User Provisioning — Onboarding and Offboarding URL: https://www.ansiblebyexample.com/articles/ansible-user-provisioning-onboarding-and-offboarding Description: Ansible User Provisioning guide with practical Ansible examples, parameters, and troubleshooting tips. With tested, real-world examples. # Ansible User Provisioning — Onboarding and Offboarding ## Introduction Onboarding and Offboarding. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible User Provisioning requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags... --- ## Ansible Vagrant — Automate Development Environments URL: https://www.ansiblebyexample.com/articles/ansible-vagrant-development-environments Description: Use Ansible with Vagrant for reproducible development environments. Vagrant provisioner configuration, multi-machine setups, synced folders, Ansible. ## Introduction Vagrant creates reproducible virtual machine environments. Combined with Ansible as the provisioner, you get local infrastructure that mirrors production — test playbooks, develop roles, and onboard developers with a single `vagrant up`. This guide covers the Ansible provisioner, multi-machine setups, and using Vagrant as your Ansible testing ground. ## Basic Setup ### Vagrantfile [code example] ### Playbook [code example] ### Inventory [code example] ## Ansible Local Provisioner Run Ansible inside the VM (no Ansible needed on host): [code example] ## Multi-Machine Environment [code example] ## Ansible Groups from Vagrant [code example] ## Testing Playbooks with Vagrant ### Development Workflow [code example] ### Makefile [code example] ## Vagrant + Molecule [code example] ## Synced Folders for Development [code example] ## Port Forwarding [code example] ## Libvirt Provider (Linux) [code example] ## Environment-Specific Variables [code example] ## Troubleshooting ### SSH Connection Issues [code example] ### Provisioning Failed [code example] ### Slow Synced Folders Use `rsync` or `nfs` instead of default VirtualBox shared folders: [code example] ## Related Articles - Ansible Molecule Testing - Ansible Docker Compose - Ansible Development Guide - Ansible Inventory Guide ## Conclusion Vagrant + Ansible gives you production-like infrastructure on your laptop. Use the `ansible` provisioner for multi-machine setups with pro... --- ## Ansible Vagrant — Manage Development Environments URL: https://www.ansiblebyexample.com/articles/ansible-vagrant-manage-development-environments Description: Ansible Vagrant guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Vagrant — Manage Development Environments ## Introduction Manage Development Environments. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Vagrant requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for sel... --- ## Ansible validate — Variables & Input URL: https://www.ansiblebyexample.com/articles/ansible-validate-variables-data-input Description: Validate variables, input data, and playbook parameters in Ansible using assert, argument_specs, jsonschema, and ansible-lint. Catch errors before they. ## Introduction Validation in Ansible means checking that variables, data, and inputs meet expected conditions before tasks execute. Without validation, a typo in a variable or a missing required value can silently propagate through your playbook and break production. Ansible provides multiple validation mechanisms: `assert` for runtime checks, `argument_specs` for role/module parameter validation, `ansible.utils.validate` for schema-based validation, and `ansible-lint` for static analysis. ## Validation Methods Overview [code example] ## Validate with assert The most common validation approach — check conditions and fail with a clear message. [code example] ## Validate with argument_specs (Roles) Define expected parameters for your role with types, defaults, and descriptions. [code example] [code example] ## Validate with ansible.utils.validate (JSON Schema) For complex data structures, validate against a JSON Schema. [code example] ## Validate Files Exist Before Using Them [code example] ## Validate Network Connectivity [code example] ## Validate with ansible-lint [code example] [code example] ## Validate Playbook Before Running (Check Mode) [code example] ## Common Mistakes [code example] ## Related Articles - Ansible assert Module - Ansible Error Handling - Ansible ansible-lint Guide - Ansible Playbook Best Practices - Ansible wait_for Module ## Conclusion Validate early, validate often. Use `assert` for quick runtime checks on variables and ho... --- ## Ansible validate_argument_spec — Roles URL: https://www.ansiblebyexample.com/articles/ansible-role-input-validation-with-validate-argument-spec Description: Validate role inputs with ansible.builtin.validate_argument_spec. Define required parameters, types, choices, and defaults with complete examples. ## Introduction Ensuring the integrity of inputs in automation workflows is crucial, especially in a dynamic and modular framework like Ansible. The Ansible `validate_argument_spec` function, part of the `ansible.builtin` collection, is a powerful tool for enforcing parameter validation directly within roles, improving both security and reliability. This article provides an end-to-end guide to using `validate_argument_spec` in Ansible roles to validate parameters, avoid errors, and maintain consistent data standards across tasks. By integrating `validate_argument_spec`, you can ensure that your Ansible roles receive correct, type-validated, and requirement-compliant inputs before executing automation tasks. --- ## Why Use `validate_argument_spec`? With `validate_argument_spec`, Ansible users can define parameter requirements such as types, default values, allowed choices, and required fields in a centralized argument specification. This provides several benefits: 1. **Error Prevention**: Catches invalid inputs early, preventing runtime failures. 2. **Readability and Consistency**: Centralizes the validation logic, making role parameters easier to understand and maintain. 3. **Reusable Validation Logic**: Creates modular validation that can be applied across multiple roles or tasks. --- ## How `validate_argument_spec` Works The `validate_argument_spec` function validates inputs against a structured argument specification. This spec defines the type, constraints, and o... --- ## Ansible Validated Content URL: https://www.ansiblebyexample.com/articles/ansible-validated-content Description: iscover how Ansible validated content simplifies automation with expert-driven, pre-built playbooks and roles, ensuring best practices and seamless. ## Introduction In the ever-evolving landscape of IT automation, staying ahead of the curve is essential for businesses of all sizes. Ansible, a leading automation platform, has taken a significant step forward in simplifying and streamlining automation with the introduction of Ansible validated content. This new initiative is designed to provide a trusted and expert-driven approach to automation across a wide array of use cases, spanning infrastructure, networking, cloud, security, and edge computing. Announced during AnsibleFest 2022, Ansible validated content is a game-changer for automation enthusiasts. It offers a comprehensive set of pre-built YAML content, such as playbooks and roles, that are specifically crafted to address the most common automation challenges. Whether you are an experienced automation architect or just embarking on your automation journey, Ansible validated content provides you with the tools and knowledge needed to succeed. ## The Two Pillars of Automation Success To excel in automation, two critical components are necessary: 1. **A Rich Ecosystem of Integrations**: Your IT portfolio comprises a diverse range of platforms, and your automation tools need to seamlessly integrate with them. This integration ensures that you can automate a wide variety of tasks across your IT environment. 2. **Subject Matter Expertise**: Building effective automation requires a deep understanding of how to interact with your platforms and systems. This expertise com... --- ## Ansible Variable Precedence Issues — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-variable-precedence-issues-fix-and-solutions Description: Understand and fix variable precedence problems across all 22 levels. Hands-on, tested examples and best practices for Ansible Variable Precedence Issues. # Ansible Variable Precedence Issues — Fix and Solutions ## Introduction Understand and fix variable precedence problems across all 22 levels. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Understand and fix variable precedence problems across all 22 levels. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Variables — Define, Use, and Override Vars URL: https://www.ansiblebyexample.com/articles/ansible-variables-define-use-override Description: Master Ansible variables: define in playbooks, inventory, group_vars, host_vars, extra_vars. Variable precedence, data types, and Jinja2 templating. ## Introduction Variables make playbooks reusable — define values once, use them everywhere. Ansible variables work in playbooks, templates, inventories, and command line. Understanding where to define them and how precedence works is key to writing clean automation. ## Define Variables ### In a Playbook [code example] ### In a Vars File [code example] ### In Inventory (group_vars / host_vars) [code example] [code example] ### On the Command Line [code example] ### With set_fact (Runtime) [code example] ### With register (Task Output) [code example] ## Use Variables [code example] ## Variable Precedence (Low to High) From lowest to highest priority: 1. Role defaults (`roles/x/defaults/main.yml`) 2. Inventory file group vars 3. Inventory `group_vars/all` 4. Inventory `group_vars/` 5. Inventory file host vars 6. Inventory `host_vars/` 7. Play `vars` 8. Play `vars_files` 9. Play `vars_prompt` 10. Task `vars` 11. `set_fact` / `register` 12. Role `vars` (`roles/x/vars/main.yml`) 13. Block `vars` 14. Include params 15. **Extra vars (`-e`)** ← **ALWAYS WINS** **In practice, remember three levels:** - **Defaults** (role defaults) — easily overridden - **Standard** (group_vars, host_vars, play vars) — normal usage - **Force** (extra vars `-e`) — always wins, use for CLI overrides ## Data Types [code example] ## Default Values [code example] ## Common Filters [code example] ## Practical Patterns ### Environment-Specific Config [code example] [code example... --- ## Ansible vars_prompt — Interactive Playbook Input URL: https://www.ansiblebyexample.com/articles/ansible-vars-prompt-interactive-playbook-input Description: Use vars_prompt to ask for user input when running playbooks. Collect passwords, versions, confirmations, and environment choices interactively. # Ansible vars_prompt — Interactive Playbook Input ## Introduction `vars_prompt` asks for variable values interactively when a playbook starts. Use it for deployment versions, environment selection, password entry, and confirmation prompts — situations where you want human input before automation runs. Unlike `--extra-vars`, prompts appear at runtime with custom messages and optional input hiding. ## Basic Usage [code example] ## Multiple Prompts [code example] ## Password Input [code example] ## Default Values [code example] ## Encryption Options [code example] Available `encrypt` values: - `sha512_crypt` — SHA-512 (recommended) - `sha256_crypt` — SHA-256 - `md5_crypt` — MD5 (legacy, avoid) - `bcrypt` — bcrypt (requires `passlib`) ## Practical Examples ### Deployment Workflow [code example] ### Environment Selection [code example] ### User Account Setup [code example] ## Override with extra-vars [code example] ## vars_prompt vs pause vs extra-vars | Feature | `vars_prompt` | `pause` | `--extra-vars` | |---------|--------------|---------|----------------| | When asked | Before play starts | During task execution | Command line | | Hidden input | ✅ `private: true` | ✅ `echo: false` | ❌ Visible in process list | | Default value | ✅ | ❌ | ✅ | | Encryption | ✅ Built-in | ❌ | ❌ | | Confirm input | ✅ `confirm: true` | ❌ | ❌ | | CI/CD friendly | Override with `-e` | ❌ Hangs | ✅ Native | ## Troubleshooting | Issue | Solution | |-------|----------| | Prompt h... --- ## Ansible Vault — Encrypt Secrets URL: https://www.ansiblebyexample.com/articles/ansible-vault-encrypt-secrets-playbooks Description: Encrypt passwords, API keys, and sensitive data with Ansible Vault. Create, edit, view, and decrypt vault files. String encryption, multi-vault, and best. ## Introduction Ansible Vault encrypts sensitive data — passwords, API keys, certificates, tokens — so you can safely store them in version control alongside your playbooks. Files are encrypted with AES-256, and you can encrypt entire files or individual variables (inline encryption). ## Create an Encrypted File [code example] `secrets.yml` (what you type inside the editor): [code example] The saved file looks like: [code example] ## Encrypt an Existing File [code example] ## View, Edit, Decrypt [code example] ## Encrypt a Single String Instead of encrypting the whole file, encrypt just one value: [code example] Output (paste this into your vars file): [code example] [code example] ### Use Inline Encrypted Variables [code example] ## Run Playbooks with Vault [code example] ### Password File [code example] ⚠️ **Never commit the password file.** Add it to `.gitignore`: [code example] ## Multi-Vault (Multiple Passwords) Use different passwords for different environments: [code example] ## Practical Examples ### Separate Secrets File [code example] `vars/main.yml`: [code example] `vars/secrets.yml` (encrypted): [code example] `playbook.yml`: [code example] ### Group Vars with Vault [code example] This pattern is recommended by Ansible documentation — Ansible automatically loads both `vars.yml` and `vault.yml` from group_vars directories. ### Encrypt Certificates [code example] ## CI/CD Integration [code example] ## Best Practices 1. **Separa... --- ## Ansible Vault — Encrypt Secrets in Playbooks (Complete Guide) URL: https://www.ansiblebyexample.com/articles/ansible-terminology-what-is-an-ansible-vault Description: Encrypt passwords, API keys, and sensitive files with Ansible Vault. Complete guide covering encrypt_string, vault files, multiple passwords. ## Introduction Ansible Vault encrypts sensitive data — passwords, API keys, certificates, and configuration files — so you can safely store them in version control alongside your playbooks. It uses AES-256 symmetric encryption and integrates seamlessly into playbook execution. This guide covers all Vault operations: encrypting strings, files, using multiple vault passwords, and best practices for managing secrets in production. ## How Ansible Vault Works Vault encrypts data using AES-256 in CTR mode with HMAC-SHA256 authentication. The encrypted content is stored as ASCII-armored text prefixed with `$ANSIBLE_VAULT;1.1;AES256`. **Key concepts:** - Vault encrypts **at rest** — decryption happens in memory during playbook execution - A single vault password (passphrase) encrypts/decrypts the content - Multiple vault IDs allow different passwords for different secrets - Vault integrates with `ansible-playbook`, `ansible`, and `ansible-vault` CLI tools ## Basic Operations ### Encrypt a File [code example] **Before encryption:** [code example] **After encryption:** [code example] ### Decrypt a File [code example] ### Edit an Encrypted File [code example] ### Change Vault Password [code example] ## Encrypt Individual Strings (encrypt_string) For encrypting a single variable value without encrypting the entire file: [code example] ### Use in Variable Files [code example] ## Using Vault in Playbooks ### Running a Playbook with Vault [code example] ### Playboo... --- ## Ansible Vault Create — Encrypt Files and Variables URL: https://www.ansiblebyexample.com/articles/ansible-vault-create-encrypt-files-and-variables Description: Create encrypted files with ansible-vault create. Manage vault passwords, encrypt existing files, and protect secrets in Ansible projects. # Ansible Vault Create — Encrypt Files and Variables ## Introduction `ansible-vault create` generates a new encrypted file in one step — opening your editor with a blank file, then encrypting the saved content with AES-256. This is the starting point for managing secrets in Ansible: vault-encrypted files store passwords, API keys, certificates, and any sensitive data that must live in version control without being readable. ## Basic Usage [code example] When you run `ansible-vault create`, it: 1. Prompts for a vault password (or reads from file) 2. Opens your `$EDITOR` with a blank file 3. Encrypts the saved content 4. Writes the encrypted file to disk ## Create group_vars Secrets [code example] [code example] ## Variable Naming Convention [code example] This lets you `grep` for variable usage without decrypting vault files. ## Other Vault Commands [code example] ## Using Encrypted Files in Playbooks [code example] [code example] ## Password File Setup [code example] ## Multi-Vault with Vault IDs [code example] ## Project Structure [code example] ## CI/CD Integration [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "Decryption failed" | Wrong vault password; check password file | | "is not a vault encrypted file" | File wasn't created with `ansible-vault create/encrypt` | | "No vault secrets found" | Pass `--ask-vault-pass` or `--vault-password-file` | | Editor doesn't open | Set `$EDITOR` environment variable | | "input ... --- ## Ansible Vault Decrypt — Unlock Encrypted Files and Variables URL: https://www.ansiblebyexample.com/articles/ansible-vault-decrypt-unlock-encrypted-files-and-variables Description: Decrypt Ansible Vault encrypted files and variables. Use ansible-vault decrypt, view, and edit commands. Manage vault passwords in CI/CD pipelines. # Ansible Vault Decrypt — Unlock Encrypted Files and Variables ## Introduction Ansible Vault encrypts sensitive data — passwords, API keys, certificates — within your automation codebase. This guide covers all decryption workflows: viewing encrypted content, editing in-place, decrypting files permanently, and automating vault access in CI/CD pipelines. ## Quick Reference [code example] ## View Encrypted Content [code example] ## Edit Encrypted Files [code example] ## Decrypt Files Permanently [code example] > ⚠️ **Warning:** `ansible-vault decrypt` permanently removes encryption. The file becomes readable by anyone with file access. Use `view` or `edit` instead for temporary access. ## Decrypt Inline Variables [code example] ## Vault Password Methods ### Interactive Prompt [code example] ### Password File [code example] ### Password Script [code example] [code example] ### Environment Variable [code example] ## Multiple Vault IDs [code example] ## CI/CD Integration ### GitHub Actions [code example] ### GitLab CI [code example] ### Jenkins [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | `Decryption failed` | Wrong password | Verify password matches encryption | | `is not vault encrypted` | File is plaintext | No decryption needed | | `Vault password client script had nonzero exit` | Script error | Check script permissions and output | | `ERROR! vault-id not found` | Mismatched vault ID | Use matching `--vaul... --- ## Ansible Vault encrypt_string vs vault file — Secrets Management URL: https://www.ansiblebyexample.com/articles/ansible-vault-encrypt-string-vs-file Description: Compare Ansible Vault encrypt_string and vault files. Learn when to use inline encryption vs file encryption with practical examples and best practices. ## Introduction Ansible Vault encrypts sensitive data so you can safely commit secrets to version control. You can encrypt entire files or individual strings inline. Each approach has different workflows, git diff behavior, and team collaboration implications. This guide helps you choose the right one. ## Quick Comparison | Feature | `encrypt_string` (inline) | Vault file (full file) | |---------|--------------------------|----------------------| | Encrypted unit | Single variable value | Entire file | | Git diff | ❌ Unreadable (binary blob per value) | ❌ Unreadable (entire file) | | Variable names visible | ✅ Yes (only value encrypted) | ❌ No (everything encrypted) | | Mix with plaintext | ✅ Same file | ❌ Separate file required | | Edit workflow | Re-encrypt each string | `ansible-vault edit file.yml` | | Multiple vault IDs | ✅ Per-string | ✅ Per-file | | Best for | Few secrets mixed with non-secrets | Many secrets, dedicated secret files | ## encrypt_string — Inline Encryption [code example] ### Use in Variables File [code example] ### Advantages [code example] ## Vault File — Full File Encryption [code example] ### Directory Pattern (Recommended) [code example] [code example] ### Advantages [code example] ## Running Playbooks [code example] ## Multiple Vault IDs [code example] ## When to Use Which ### Use encrypt_string when: - You have **few secrets** mixed with many plain variables - Team members need to see variable **names** without vault access ... --- ## Ansible Vault Guide: Encrypt and Manage Secrets Securely URL: https://www.ansiblebyexample.com/articles/ansible-vault-unveiled-your-key-to-securing-automation-secrets Description: Complete Ansible Vault guide: encrypt files, strings, and variables. Learn vault create, edit, encrypt_string, multiple vault IDs, and integration with. ## Introduction Ansible Vault provides built-in encryption for protecting sensitive data in your automation workflows — passwords, API keys, certificates, and any secret that shouldn't exist in plaintext. Unlike external secrets managers, Vault is included with Ansible and requires zero additional infrastructure. This guide covers all Vault operations from basic file encryption to advanced multi-vault setups and CI/CD integration. ## Quick Start ### Encrypt a File [code example] You'll be prompted for a vault password. The file is encrypted in-place using AES-256. ### Decrypt a File [code example] ### View Encrypted File [code example] ### Edit Encrypted File [code example] Opens the decrypted file in your `$EDITOR`, then re-encrypts on save. ## Creating Vault-Encrypted Files ### New Encrypted File [code example] This opens your editor with an empty file. Add your secrets: [code example] ### Encrypt Individual Strings Use `encrypt_string` to encrypt a single value inline: [code example] Output: [code example] Paste this directly into your variables file — only this value is encrypted, making the file partially readable: [code example] ## Using Vault in Playbooks ### Password Prompt [code example] ### Password File [code example] The password file is a plain text file containing just the password: [code example] ### Password from Script The password file can be an executable script: [code example] [code example] ### Set Default in ansible.c... --- ## Ansible Vault ID — Multi-Password Vault Management URL: https://www.ansiblebyexample.com/articles/ansible-vault-id-multi-password-vault-management Description: Manage multiple Ansible Vault passwords with vault IDs. Separate dev/prod secrets, use password files, prompt labels, and client scripts. # Ansible Vault ID — Multi-Password Vault Management ## Introduction Ansible Vault encrypts sensitive data — passwords, keys, tokens. But real projects need multiple vault passwords: one for dev, one for staging, one for production. Vault IDs solve this by labeling encrypted content with an identifier, so Ansible knows which password to use for each secret. ## Basic Vault ID Usage [code example] ## Password Sources ### Prompt (Interactive) [code example] ### Password File [code example] ### Client Script [code example] [code example] ## ansible.cfg Configuration [code example] ## Per-Environment Secrets Structure [code example] [code example] ## Inline Encrypted Variables [code example] Output (paste into vars file): [code example] The `prod` label after `AES256;` tells Ansible which vault ID decrypts it. ## Mixing Encrypted and Unencrypted [code example] ## Rekeying [code example] ## CI/CD Integration [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | "Decryption failed" | Wrong vault ID or password for the file | | "No vault secrets found" | Missing `--vault-id` or `vault_identity_list` | | Can't decrypt inline var | Vault ID label in `$ANSIBLE_VAULT` header must match | | Password file not found | Check path; use absolute path in `ansible.cfg` | | Multiple prompts annoying | Use password files or vault client script | ## Best Practices 1. **One vault ID per environment** — `dev`, `staging`, `prod` with different pas... --- ## Ansible Vault Password Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-vault-password-error-fix-and-solutions Description: Resolve vault decryption failures from wrong passwords, file format, and encoding. Tested on real machines with clear, copy-paste examples. # Ansible Vault Password Error — Fix and Solutions ## Introduction Resolve vault decryption failures from wrong passwords, file format, and encoding. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve vault decryption failures from wrong passwords, file format, and encoding. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible Vault: Encrypt Secrets in Playbooks and Variables URL: https://www.ansiblebyexample.com/articles/ansible-vault-encrypt-secrets-in-playbooks-and-variables Description: Complete guide to Ansible Vault — encrypt files, variables, and strings. Learn create, edit, view, encrypt, decrypt commands with practical examples for. ## What is Ansible Vault? Ansible Vault encrypts sensitive data — passwords, API keys, certificates, SSH keys — so you can safely store them in version control alongside your playbooks. ## Create an Encrypted File [code example] Inside the editor: [code example] ## Encrypt an Existing File [code example] ## Decrypt a File [code example] ## Edit an Encrypted File [code example] ## Encrypt a Single String [code example] Output: [code example] Paste this directly into your playbook or vars file. ## Using Vault in Playbooks ### Encrypted Variables File [code example] [code example] ### Inline Encrypted Variables [code example] ## Running Playbooks with Vault [code example] ### Password File [code example] ### Password from Script [code example] [code example] ## Multiple Vault IDs Use different passwords for different environments: [code example] ## Change Vault Password [code example] ## Common Error: "no vault secrets found" [code example] **Fix:** Provide the vault password: [code example] ## Best Practices 1. **Never commit `.vault_pass`** — add to `.gitignore` 2. **Use `no_log: true`** on tasks using vault variables 3. **Separate secrets from code** — put encrypted vars in `group_vars/*/vault.yml` 4. **Use vault IDs** for multi-environment setups 5. **Rotate vault passwords** periodically with `ansible-vault rekey` 6. **Use `encrypt_string`** for individual values instead of encrypting entire files ## Project Structure [code example] [... --- ## Ansible VMware — Add Disk to VM URL: https://www.ansiblebyexample.com/articles/add-a-new-hard-disk-to-vmware-vsphere-virtual-machine-ansible-module-vmware-guest-disk Description: Learn how to add a disk to a VMware VM using an Ansible playbook. This guide includes the YAML configuration, variables, and execution steps for easy. ## Introduction - **Module**: `community.vmware.vmware_guest_disk` - **Purpose**: Manage disks related to virtual machines in a given vCenter infrastructure The Ansible module `vmware_guest_disk` is part of the community-supported collection of modules for interacting with VMware. It manages disks associated with virtual machines within a specified vCenter infrastructure. ## Parameters Overview - **Connection Details**: - `hostname` (string) - `username` (string) - `password` (string) - `datacenter` (string) - `validate_certs` (boolean) - **SCSI Controller Details**: - `scsi_controller` (string) - `unit_number` (string) - `scsi_type` (string) - **Disk Size**: - `size_kb` / `size_mb` / `size_gb` / `size_tb` (string) - **Disk Mode**: - `disk_mode` (string: `persistent`, `independent_persistent`, `independent_nonpersistent`) To add a disk to a VMware vSphere Virtual Machine using the `vmware_guest_disk` module, you must first establish a connection to VMware vSphere or VMware vCenter. This is done using parameters such as `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once connected, you can specify the desired disk configuration to add a new disk to the virtual machine. The required parameters are `datacenter` and `unit_number`. The `datacenter` parameter identifies the datacenter to which the virtual machine belongs. The disk must be connected to a SCSI controller inside the virtual machine, so parameters like `scsi_con... --- ## Ansible VMware community.vmware venv URL: https://www.ansiblebyexample.com/articles/configure-a-python-virtual-environment-for-ansible-vmware-ansible-collection-community-vmware Description: Learn how to set up a Python Virtual Environment for Ansible VMware, ensuring seamless integration and management of your VMware infrastructure with. ## How to configure a Python Virtual Environment for Ansible VMware? Using a Python Virtual Environment is a convenient way to maintain up-to-date the Python dependency of the Ansible collection community.vmware without interfere with your Linux system/ This initial configuration sometimes is a roadblock for some VMware users to start using Ansible. I'm Luca Berton and welcome in today's episode of Ansible Pilot. ## Links - Ansible collection community.vmware - Python pyVmomi - VMware vSphere Automation SDK for Python ## Playbook Configure a Python Virtual Environment for Ansible VMware: - pyVmomi - requests - VMware vSphere Automation SDK for Python How to Python Virtual Environment for Ansible VMware. I'm going to show you how to configure a Python Virtual Environment for Ansible VMware to successfully use the Ansible collection `community.vmware` of modules and plugins to manages various operations related to virtual machines in the given ESXi or vCenter server. Ansible VMware modules are written on top of `pyVmomi` Python SDK for the VMware vSphere API that allows user to manage ESX, ESXi, and vCenter infrastructure. Other useful libraries are `requests` and `VMware vSphere Automation SDK for Python` used for some additional features such as list tags in the Ansible Dynamic Inventory `vmware_vm_inventory` plugin. ### code [code example] ### execution [code example] - requirements.txt [code example] code with ❤️ in GitHub ## Conclusion Now you know how to con... --- ## Ansible VMware ESXi Host Info URL: https://www.ansiblebyexample.com/articles/gather-info-about-all-vmware-esx-esxi-hosts-in-a-given-cluster-ansible-module-vmware-host-config-info Description: Discover how to gather info about VMware ESX/ESXi hosts in a cluster using Ansible. Follow our live Playbook and simple code examples to get started. ## How to Gather Info about all VMware ESX/ESXi Hosts in a given Cluster with Ansible? I’m going to show you a live Playbook and some simple Ansible code. ## Ansible Gather Info about all VMware ESX/ESXi Hosts in given Cluster - `community.vmware.vmware_host_config_info` - Gathers info about an ESXi host’s advanced configuration information Let’s talk about the Ansible module `vmware_host_config_info`. The full name is `community.vmware.vmware_host_config_info`, which means that is part of the collection of modules to interact with VMware, community-supported. The module's purpose is to gather info about an ESXi host’s advanced configuration information. ## Parameters - `hostname` string / port integer / username string / password string / datacenter string / validate_certs boolean — connection details - `cluster_name` string — Name of the cluster from which the ESXi host belongs to. - `esxi_hostname` string — ESXi hostname to gather information from. The following parameters are useful in order to Gather Info about all VMware ESX/ESXi Hosts in the given Cluster using the module `vmware_host_config_info`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `port`, `username`, `password`, `datacenter` and `validate_certs`. Once the connection is successfully established you could specify the full `esxi_hostname`, the ESX/ESXi hostname, or list all the hostnames in the curren... --- ## Ansible VMware Guest Operations — Clone Snapshot Migrate URL: https://www.ansiblebyexample.com/articles/ansible-vmware-guest-operations-clone-snapshot-migrate Description: Ansible VMware Guest Operations guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible VMware Guest Operations — Clone Snapshot Migrate ## Introduction Clone Snapshot Migrate. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible VMware Guest Operations requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ... --- ## Ansible VMware Tag Verification URL: https://www.ansiblebyexample.com/articles/vmware-folder-exists-using-ansible Description: Use Ansible community.vmware collection to verify, create, and manage VMware tags and categories. Complete playbook examples for tag lifecycle management. ## Introduction VMware tags organize virtual infrastructure — VMs, datastores, networks, and hosts — into logical groups for policy, search, and automation. The `community.vmware` collection provides modules to manage tags, categories, and tag assignments entirely through Ansible. This article covers tag verification, creation, bulk assignment, and integration with VM provisioning workflows. ## Prerequisites [code example] ### Connection Variables [code example] ## Verify and Create Tags ### Single Tag [code example] ### Multiple Tags in Bulk [code example] ## Assign Tags to VMs [code example] ### Tag Multiple VMs [code example] ## Query Tags ### Get Tag Info [code example] ### Get Category Info [code example] ## Integration with VM Provisioning [code example] ## Remove Tags [code example] ## Best Practices 1. **Use categories with cardinality** — `single` for mutually exclusive tags (Environment), `multiple` for additive (Application) 2. **Standardize naming** — agree on tag names before creating them 3. **Vault all vCenter credentials** — never hardcode passwords 4. **Tag at provisioning time** — include tagging in your VM creation workflow 5. **Use `state: set`** — replaces existing tags in a category; `state: add` appends 6. **Audit tags periodically** — query `vmware_tag_info` to find untagged VMs ## Related Articles - Ansible VMware vSphere Automation - Ansible Vault Guide - Ansible Variables Guide - Ansible Loops Guide ## Conclusion The `co... --- ## Ansible VMware VM Snapshot Check URL: https://www.ansiblebyexample.com/articles/checking-vmware-vm-snapshots Description: Learn how to use Ansible to check for VMware snapshots on virtual machines with the `vmware_vm_info` module. This guide includes step-by-step instructions. ## Introduction Virtual machine snapshots are a valuable tool in VMware environments, enabling administrators to create recovery points before making changes. However, performing operations on VMs with snapshots can lead to unintended consequences. This guide demonstrates how to use Ansible to check for VMware snapshots on virtual machines and output the results. --- ## The Use Case You want to: 1. Detect if a VMware virtual machine has snapshots. 2. Output a message indicating whether snapshots are present. By automating this process with Ansible, you can quickly assess the state of your VMs and avoid actions on machines with active snapshots. --- ## The Ansible Playbook Here’s a step-by-step playbook to detect VMware snapshots: ### Playbook Code [code example] --- ## Step-by-Step Breakdown ### 1. **Gather VM Information** The `vmware_vm_info` module fetches details about the specified virtual machine: - **Parameters:** - `hostname`, `username`, `password`: Credentials for connecting to VMware vCenter. - `datacenter`: The datacenter containing the VM. - `vm_names`: Specify the name of the virtual machine. - **Result Storage:** The result is stored in the `vm_info_result` variable. ### 2. **Check for Snapshots** The `set_fact` module checks if snapshots exist: - **Condition:** `vm_info_result.virtual_machines[0].snapshot.currentSnapshot is defined`. - **Output:** The `has_snapshot` variable is set to `true` if a snapshot exists and `false` otherwise. ### ... --- ## Ansible vmware_guest — Deploy VM URL: https://www.ansiblebyexample.com/articles/deploy-a-vmware-vsphere-virtual-machine-from-a-template-ansible-module-vmware-guest Description: How to automate the deployment of a virtual machine guest from “mytemplate” template using Ansible Playbook and vmware_guest module. ## How to Deploy a VMware vSphere Virtual Machine from a Template with Ansible? ## Ansible Deploy a VMware vSphere Virtual Machine from a Template - `community.vmware.vmware_guest` - Manages virtual machines in vCenter Let's talk about the Ansible module `vmware_guest`. The full name is `community.vmware.vmware_guest`, which means that is part of the collection of modules to interact with VMware, community-supported. It's a module pretty stable and out for years. It manages virtual machines in vCenter. ## Parameters The module `vmware_guest` has a very long list of parameters to customize all your needs to create a VMware vSphere Virtual Machine. Please refer to the manual for the full list. ## Links - community.vmware.vmware_guest ## Playbook How to Deploy a VMware vSphere Virtual Machine from a Template with Ansible. I'm going to show you how to deploy a Virtual Machine named "myvm" from a template "mytemplate" without any customization. ### code - vm_deploy_template.yml [code example] - vars.yml [code example] - inventory [code example] ### execution [code example] ### idempotency [code example] ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to Deploy a VMware vSphere Virtual Machine from a Template with Ansible. --- ## Ansible vmware_guest_snapshot Module URL: https://www.ansiblebyexample.com/articles/take-a-vmware-virtual-machine-snapshot-ansible-module-vmware-guest-snapshot Description: How to automate taking snapshots named “Ansible Managed Snapshot” to a VMware Virtual Machine “myvm” Ansible Playbook and vmware_guest_snapshot module. ## How to Take a VMware Virtual Machine Snapshot with Ansible? ## Ansible Take a VMware Virtual Machine Snapshot - `community.vmware.vmware_guest_snapshot` - Manages virtual machines snapshots in vCenter Let's talk about the Ansible module `vmware_guest_snapshot`. The full name is `community.vmware.vmware_guest_snapshot`, which means that is part of the collection of modules to interact with VMware, community-supported. It manages virtual machine snapshots in vCenter. ## Parameters - hostname string / username string / password string / datacenter string / validate_certs boolean - connection details - state string - present / absent / revert / remove_all - remove_children boolean - no/yes - snapshot_name string description string - Name/description of the virtual machine to work with - memory_dump boolean - no/yes - memory snapshots take time and resource The following parameters are useful in order to Take a VMware Virtual Machine Snapshot using the module `vmware_guest_snapshot`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the desired snapshot state, in this case, "present" to take a snapshot. You could also `revert` or `remove` a snapshot with the same Ansible module. If you want to remove a snapshot you could also remove all the dependent ... --- ## Ansible vs Bash Scripts — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-bash-scripts-detailed-comparison Description: When to use Ansible over Bash scripts: idempotency, scale, readability, and maintainability. Tested on real machines with clear, copy-paste examples. # Ansible vs Bash Scripts — Detailed Comparison ## Introduction When to use Ansible over Bash scripts: idempotency, scale, readability, and maintainability. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion When to use Ansible over Bash scripts: idempotency, scale, readability, and maintainability. Start with the fundamentals, implement best pra... --- ## Ansible vs CDKTF — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-cdktf-detailed-comparison Description: Ansible vs CDK for Terraform: declarative YAML vs imperative TypeScript for infrastructure. With tested, real-world examples. # Ansible vs CDKTF — Detailed Comparison ## Introduction Ansible vs CDK for Terraform: declarative YAML vs imperative TypeScript for infrastructure. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible vs CDK for Terraform: declarative YAML vs imperative TypeScript for infrastructure. Start with the fundamentals, implement best practices fr... --- ## Ansible vs Chef — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-chef-detailed-comparison Description: Compare Ansible and Chef for configuration management: simplicity vs power, YAML vs Ruby DSL. With tested, real-world examples. # Ansible vs Chef — Detailed Comparison ## Introduction Compare Ansible and Chef for configuration management: simplicity vs power, YAML vs Ruby DSL. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Chef for configuration management: simplicity vs power, YAML vs Ruby DSL. Start with the fundamentals, implement best practices... --- ## Ansible vs Chef: Which Automation Tool Should You Use? URL: https://www.ansiblebyexample.com/articles/ansible-vs-chef-which-automation-tool-should-you-use Description: Ansible vs Chef compared — YAML vs Ruby, agentless vs agent-based, push vs pull. Understand the key differences to choose the right automation tool for. ## Ansible vs Chef at a Glance | Feature | Ansible | Chef | |---------|---------|------| | **Architecture** | Agentless (push) | Agent-based (pull) | | **Language** | YAML | Ruby (DSL) | | **Learning curve** | Easy | Steep (Ruby required) | | **Master server** | Not required | Chef Server required | | **Communication** | SSH / WinRM | HTTPS (agent → server) | | **Testing** | Molecule | Test Kitchen (ChefSpec, InSpec) | | **Community** | Very large, growing | Declining since Progress acquisition | | **License** | GPL (open source) | Apache 2.0 | ## Side-by-Side Example ### Install and start nginx **Ansible:** [code example] **Chef:** [code example] ### Create a user **Ansible:** [code example] **Chef:** [code example] ## Why Teams Choose Ansible Over Chef ### 1. No Ruby Required Ansible uses YAML — readable by developers, sysadmins, and even non-technical team members. Chef requires Ruby proficiency, which narrows who can contribute. ### 2. No Infrastructure Overhead Ansible needs nothing on target hosts (just SSH). Chef requires: - Chef Server (or hosted Chef) - Chef Workstation - Chef Client (agent) on every node - Bookshelf (cookbook storage) ### 3. Faster to Start [code example] ### 4. Better for Orchestration Ansible handles multi-host orchestration natively — rolling updates, serial execution, delegation. Chef focuses on single-node convergence. ## Why Teams Might Choose Chef - **Mature testing ecosystem** — ChefSpec, InSpec, Test Kitchen - **Complianc... --- ## Ansible vs CloudFormation — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-cloudformation-detailed-comparison Description: Ansible vs AWS CloudFormation: multi-cloud vs AWS-native, YAML differences, state management. Tested on real machines with clear, copy-paste examples. # Ansible vs CloudFormation — Detailed Comparison ## Introduction Ansible vs AWS CloudFormation: multi-cloud vs AWS-native, YAML differences, state management. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible vs AWS CloudFormation: multi-cloud vs AWS-native, YAML differences, state management. Start with the fundamentals, implement best... --- ## Ansible VS Code Extension — Dev Setup URL: https://www.ansiblebyexample.com/articles/elevating-ansible-development-with-visual-studio-code Description: Complete guide to setting up VS Code for Ansible development. Install the Red Hat extension, configure YAML, enable Lightspeed AI, and master keyboard. Visual Studio Code (VS Code) is the most popular editor for Ansible development, thanks to Red Hat's official Ansible extension that provides syntax highlighting, auto-completion, linting, and AI-powered code generation through Ansible Lightspeed. ## Why VS Code for Ansible? While you can write Ansible playbooks in any text editor, VS Code offers specific advantages: - **Ansible-aware syntax highlighting** that distinguishes modules, parameters, and Jinja2 expressions - **Real-time ansible-lint integration** that catches errors as you type - **Intelligent auto-completion** for module names, parameters, and values - **Ansible Lightspeed AI** that generates task code from natural language descriptions - **Integrated terminal** for running playbooks without leaving the editor - **YAML schema validation** specific to Ansible playbook structure ## Prerequisites Before setting up VS Code for Ansible: - **VS Code** 1.70.1 or later (download from code.visualstudio.com) - **Python 3.9+** installed on your system - **Ansible** installed (`pip install ansible` or system package) - **ansible-lint** recommended (`pip install ansible-lint`) ## Installing the Red Hat Ansible Extension ### Step-by-Step Installation 1. Open VS Code and click the **Extensions** icon in the sidebar (or press `Ctrl+Shift+X` / `Cmd+Shift+X`) 2. Search for **"Ansible"** in the Extensions marketplace 3. Find the extension published by **Red Hat** (verify the publisher name) 4. Click **Install** ### Post-I... --- ## Ansible VS Code Extension with MCP Server — AI-Powered Development URL: https://www.ansiblebyexample.com/articles/ansible-vs-code-extension-with-mcp-server-ai-powered-development Description: Red Hat's Ansible VS Code extension embeds an MCP server for AI-assisted playbook creation, context-aware linting, and compliant-by-design scaffolding. # Ansible VS Code Extension with MCP Server — AI-Powered Development ## Introduction Red Hat's Ansible VS Code extension now embeds a **Model Context Protocol (MCP) server** that enables AI-assisted playbook development. Write automation in natural language, get context-aware linting, and scaffold compliant playbooks — all inside your editor. ## Features ### Natural Language to Playbook [code example] ### Context-Aware Linting The MCP server provides: - **FQCN suggestions** — auto-complete fully qualified collection names - **Deprecation warnings** — flag modules marked for removal - **Best practice hints** — suggest handlers over inline restarts - **Security checks** — warn on `no_log: false` for sensitive tasks ### Compliant-by-Design Scaffolding [code example] ## Installation [code example] ### Enable MCP Server [code example] ## AI-Assisted Workflows ### 1. Explain Existing Playbook Select code → Right-click → "Ansible: Explain This" ### 2. Fix Linting Issues AI suggests fixes for ansible-lint violations with one-click apply. ### 3. Generate Tests "Generate Molecule tests for this role" — creates converge.yml, verify.yml, and assertions. ### 4. Refactor to Role Select inline tasks → "Ansible: Extract to Role" — creates full role structure. ## MCP Tool Integration The embedded MCP server exposes: | Tool | Description | |------|-------------| | `ansible.lint` | Run ansible-lint with AI-enhanced suggestions | | `ansible.explain` | Explain playbook/ta... --- ## Ansible vs Crossplane — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-crossplane-detailed-comparison Description: Compare Ansible and Crossplane for Kubernetes-native infrastructure management. With clear, copy-paste, step-by-step examples. # Ansible vs Crossplane — Detailed Comparison ## Introduction Compare Ansible and Crossplane for Kubernetes-native infrastructure management. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Crossplane for Kubernetes-native infrastructure management. Start with the fundamentals, implement best practices from day one, and ite... --- ## Ansible vs Docker — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-docker-detailed-comparison Description: Ansible vs Docker: configuration management vs containerization. How they complement each other. Tested on real machines with clear, copy-paste examples. # Ansible vs Docker — Detailed Comparison ## Introduction Ansible vs Docker: configuration management vs containerization. How they complement each other. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible vs Docker: configuration management vs containerization. How they complement each other. Start with the fundamentals, implement best p... --- ## Ansible vs Flatpak — Configuration vs App Packaging URL: https://www.ansiblebyexample.com/articles/ansible-vs-flatpak-application-packaging-compared Description: Compare Ansible and Flatpak — infrastructure automation vs application packaging. When to use each, how they complement each other, and managing Flatpak. # Ansible vs Flatpak — Configuration vs App Packaging ## Introduction Ansible and Flatpak solve fundamentally different problems. Ansible automates infrastructure configuration and orchestration. Flatpak packages and distributes desktop applications in a sandboxed, distro-agnostic format. They don't compete — they complement each other. ## Quick Comparison | Aspect | Ansible | Flatpak | |--------|---------|---------| | **Purpose** | Infrastructure automation | Application packaging | | **Scope** | Servers, networks, cloud | Desktop applications | | **Model** | Push-based, agentless | Pull-based, per-user | | **Format** | YAML playbooks | OCI-like bundles | | **Isolation** | None (configures the OS) | Sandboxed (bubblewrap) | | **Target** | Sysadmins, DevOps | Desktop users, app devs | | **Dependencies** | Python + SSH | OSTree, bubblewrap | | **Updates** | On-demand or scheduled | Auto-update via Flathub | ## When to Use Each **Use Ansible when:** - Configuring servers, networks, and cloud infrastructure - Deploying applications to servers (web apps, databases, services) - Managing system packages (apt, yum, dnf) - Enforcing security policies across a fleet - Orchestrating multi-host workflows **Use Flatpak when:** - Distributing desktop applications (Firefox, LibreOffice, VS Code) - Providing sandboxed, distro-independent app packaging - Users need to install apps without root access - You want automatic application updates ## Managing Flatpak with Ansible The real ... --- ## Ansible vs GitHub Actions: Automation for Different Use Cases URL: https://www.ansiblebyexample.com/articles/ansible-vs-github-actions-automation-for-different-use-cases Description: Ansible vs GitHub Actions compared — when to use each for CI/CD, infrastructure automation, and deployment. Learn how they differ and how to use them. ## Ansible vs GitHub Actions at a Glance | Feature | Ansible | GitHub Actions | |---------|---------|---------------| | **Primary purpose** | Infrastructure automation | CI/CD pipelines | | **Runs on** | Any machine (control node) | GitHub-hosted or self-hosted runners | | **Targets** | Remote servers via SSH | The runner itself (or via SSH) | | **Language** | YAML playbooks | YAML workflows | | **Trigger** | Manual / scheduled / API | Git events (push, PR, schedule) | | **State** | Stateless | Stateless | | **Cost** | Free (open source) | Free tier + paid minutes | | **Secrets** | Ansible Vault | GitHub Secrets | ## When to Use Ansible - **Server configuration** — install packages, manage users, set permissions - **Multi-server orchestration** — rolling deployments across clusters - **Network device automation** — routers, switches, firewalls - **On-premise infrastructure** — servers not accessible from GitHub - **Ad-hoc operations** — run commands across 100 servers now - **Compliance and hardening** — enforce security baselines [code example] ## When to Use GitHub Actions - **CI/CD pipelines** — build, test, lint on every push - **Container builds** — build and push Docker images - **Code quality** — run tests, linters, security scans - **Release automation** — create releases, publish packages - **GitHub-native workflows** — PR checks, issue automation [code example] ## Using Both Together The best approach: **GitHub Actions for CI/CD, Ansible for deployment.** ... --- ## Ansible vs Jenkins: Key Differences and When to Use Each URL: https://www.ansiblebyexample.com/articles/can-ansible-replace-jenkins Description: Ansible vs Jenkins compared — learn the key differences, strengths, and when to use each tool. Can Ansible replace Jenkins for CI/CD and automation? Ansible and Jenkins are both powerful automation tools, but they serve distinct purposes in the DevOps ecosystem. This article explores whether **Ansible** can replace **Jenkins**, their differences, and scenarios where they complement each other. ## Can Ansible Replace Jenkins? The short answer is: **No, Ansible cannot fully replace Jenkins**. While Ansible is a versatile automation tool, Jenkins excels as a **Continuous Integration and Continuous Deployment (CI/CD)** platform. However, there are scenarios where Ansible can perform tasks traditionally managed by Jenkins, depending on the workflow. ### Key Differences Between Ansible and Jenkins | Feature | Ansible | Jenkins | |------------------------|----------------------------------------|----------------------------------------| | **Primary Purpose** | Configuration management and orchestration | CI/CD automation and pipeline orchestration | | **Execution** | Agentless, push-based | Server-client with agents or agentless | | **Focus Area** | Infrastructure as Code (IaC) | Software delivery pipelines | | **Scripting Language** | YAML | Groovy or UI-based declarative pipelines | | **Plugins** | Limited | Extensive plugin ecosystem | ## Strengths of Jenkins 1. **Continuous Integration (CI)**: Jenkins... --- ## Ansible vs Kubernetes — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-kubernetes-detailed-comparison Description: Compare Ansible and Kubernetes for application deployment and infrastructure management. Hands-on, tested examples and best practices for Ansible vs Kubernetes. # Ansible vs Kubernetes — Detailed Comparison ## Introduction Compare Ansible and Kubernetes for application deployment and infrastructure management. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Kubernetes for application deployment and infrastructure management. Start with the fundamentals, implement best practices fro... --- ## Ansible vs Nix — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-nix-detailed-comparison Description: Compare Ansible and Nix/NixOS for reproducible system configuration and deployments. Tested, copy-paste examples included. # Ansible vs Nix — Detailed Comparison ## Introduction Compare Ansible and Nix/NixOS for reproducible system configuration and deployments. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Nix/NixOS for reproducible system configuration and deployments. Start with the fundamentals, implement best practices from day one, and ... --- ## Ansible vs Pulumi — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-pulumi-detailed-comparison Description: Compare Ansible and Pulumi for infrastructure automation: YAML vs general-purpose languages. Tested on real machines with clear, copy-paste examples. # Ansible vs Pulumi — Detailed Comparison ## Introduction Compare Ansible and Pulumi for infrastructure automation: YAML vs general-purpose languages. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Pulumi for infrastructure automation: YAML vs general-purpose languages. Start with the fundamentals, implement best practices... --- ## Ansible vs Puppet — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-puppet-detailed-comparison Description: Ansible vs Puppet comparison: agentless vs agent-based, YAML vs DSL, push vs pull architecture. Tested on real machines with clear, copy-paste examples. # Ansible vs Puppet — Detailed Comparison ## Introduction Ansible vs Puppet comparison: agentless vs agent-based, YAML vs DSL, push vs pull architecture. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible vs Puppet comparison: agentless vs agent-based, YAML vs DSL, push vs pull architecture. Start with the fundamentals, implement best pra... --- ## Ansible vs Puppet vs Chef vs Salt — Configuration Management Compared (2026) URL: https://www.ansiblebyexample.com/articles/ansible-vs-puppet-vs-chef-vs-salt-comparison Description: Compare the top 4 configuration management tools. Architecture, agent model, language, learning curve, and which is best for your infrastructure. # Ansible vs Puppet vs Chef vs Salt — Compared ## Quick Comparison | Feature | Ansible | Puppet | Chef | Salt | |---------|---------|--------|------|------| | Agent | Agentless (SSH) | Agent required | Agent required | Agent (optional) | | Language | YAML | Puppet DSL (Ruby) | Ruby | YAML/Python | | Learning curve | Easy | Medium | Hard | Medium | | Architecture | Push | Pull | Pull | Push/Pull | | State management | No state file | Catalog-based | Cookbook-based | State modules | | Best for | Config + deploy | Compliance | Complex infra | Large scale | | Community | Largest | Large | Medium | Small | | Commercial | Red Hat AAP | Puppet Enterprise | Chef Automate | VMware | ## Ansible **Strengths:** - Zero installation on managed nodes - YAML playbooks — anyone can read them - Massive module library (3,500+) - Great for both config management AND deployment - Ad-hoc commands for quick tasks - Red Hat backing **Weaknesses:** - Slower at scale without tuning (SSH overhead) - No built-in drift detection - No native GUI (AWX/AAP costs money) **Best for:** Teams that want simplicity, quick adoption, and don't want agents everywhere. [code example] ## Puppet **Strengths:** - Mature, battle-tested (since 2005) - Excellent compliance/audit features - Strong drift detection and auto-correction - Good for Windows management **Weaknesses:** - Puppet DSL learning curve - Requires agent on every node - Puppet Server is resource-heavy - Slower development velocity **Best for:** ... --- ## Ansible vs Puppet: Configuration Management Compared URL: https://www.ansiblebyexample.com/articles/ansible-vs-puppet-configuration-management-compared Description: Ansible vs Puppet compared — agentless vs agent-based, YAML vs Puppet DSL, push vs pull. Learn the key differences and choose the right configuration. ## Ansible vs Puppet at a Glance | Feature | Ansible | Puppet | |---------|---------|--------| | **Architecture** | Agentless (push) | Agent-based (pull) | | **Language** | YAML | Puppet DSL (Ruby-based) | | **Learning curve** | Easy | Steeper | | **Master server** | Not required | Puppet Server required | | **Communication** | SSH / WinRM | HTTPS (agent → server) | | **Idempotent** | Yes | Yes | | **State model** | Procedural | Declarative | | **Reporting** | Basic (callbacks, ARA) | Built-in (Puppet Dashboard) | | **Scalability** | Good (with AWX/Tower) | Excellent (designed for scale) | | **Community** | Very large | Large | ## Ansible: Push-Based, Agentless Ansible connects to hosts via SSH, runs tasks, and disconnects. No software to install on managed nodes. [code example] **Pros:** - Zero agent installation or maintenance - Easy to start — pip install and go - YAML is readable by anyone - Great for ad-hoc tasks and orchestration **Cons:** - No continuous enforcement (runs only when triggered) - Push model requires network access to all hosts - Performance can degrade at very large scale without AWX ## Puppet: Pull-Based, Agent-Driven Puppet agents run on every managed node, checking in with Puppet Server every 30 minutes to enforce desired state. [code example] **Pros:** - Continuous enforcement — drift is auto-corrected every 30 min - Excellent reporting and compliance dashboards - Scales to tens of thousands of nodes - Strong type system prevents errors **... --- ## Ansible vs Rust — Automation vs Systems Programming URL: https://www.ansiblebyexample.com/articles/ansible-vs-rust-automation-vs-systems-programming Description: Compare Ansible and Rust — IT automation vs systems programming. Different tools for different jobs. When Ansible calls Rust binaries and when Rust. # Ansible vs Rust — Automation vs Systems Programming ## Introduction Ansible is a YAML-based IT automation tool. Rust is a systems programming language. They solve entirely different problems, but the comparison comes up because both are used in infrastructure tooling — Ansible automates infrastructure, while Rust is increasingly used to build the tools that manage infrastructure (like sudo-rs, ripgrep, and cloud-native CLIs). ## Quick Comparison | Aspect | Ansible | Rust | |--------|---------|------| | **Type** | Automation framework | Programming language | | **Language** | YAML (declarative) | Rust (compiled, imperative) | | **Use case** | Configure servers, deploy apps | Build CLIs, services, tools | | **Learning curve** | Low (YAML + SSH) | High (ownership, lifetimes) | | **Execution** | Interpreted via Python | Compiled to native binary | | **Speed** | Seconds per task (SSH overhead) | Nanoseconds (native code) | | **Dependencies** | Python + SSH on targets | None (static binaries) | | **Ecosystem** | 50K+ Galaxy roles/collections | 150K+ crates on crates.io | ## When to Use Each **Use Ansible when:** - Configuring servers (packages, files, services, users) - Orchestrating multi-host deployments - Managing cloud resources (AWS, Azure, GCP) - Running ad-hoc commands across a fleet - You need non-programmers to contribute **Use Rust when:** - Building high-performance CLI tools - Writing system daemons or services - Creating custom Ansible modules (as binaries) - ... --- ## Ansible vs SaltStack — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-saltstack-detailed-comparison Description: Ansible vs Salt comparison: agentless vs minion, YAML playbooks vs state files, speed vs simplicity. Tested on real machines with clear, copy-paste examples. # Ansible vs SaltStack — Detailed Comparison ## Introduction Ansible vs Salt comparison: agentless vs minion, YAML playbooks vs state files, speed vs simplicity. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Ansible vs Salt comparison: agentless vs minion, YAML playbooks vs state files, speed vs simplicity. Start with the fundamentals, imple... --- ## Ansible vs SaltStack: Push vs Pull Automation Compared URL: https://www.ansiblebyexample.com/articles/ansible-vs-saltstack-push-vs-pull-automation-compared Description: Ansible vs SaltStack compared — push vs pull, YAML vs YAML+Jinja, agentless vs minion-based. Learn the key differences in speed, scalability. ## Ansible vs SaltStack at a Glance | Feature | Ansible | SaltStack (Salt) | |---------|---------|-------------------| | **Architecture** | Agentless (push) | Agent-based (minions) + agentless option | | **Transport** | SSH | ZeroMQ (fast) or SSH | | **Language** | YAML | YAML + Jinja2 (states) | | **Speed** | Good | Very fast (ZeroMQ) | | **Master server** | Not required | Salt Master recommended | | **Scalability** | Good (AWX for scale) | Excellent (10,000+ nodes) | | **Learning curve** | Easy | Moderate | | **Event system** | No | Yes (event-driven automation) | | **Remote execution** | Ad-hoc commands | Salt functions (very fast) | ## Speed: Salt's Key Advantage Salt uses **ZeroMQ** for communication — a high-performance messaging library. Commands reach thousands of hosts in seconds: [code example] For 1,000 hosts, Salt can be 5-10x faster than Ansible's SSH-based approach. ## When to Choose Ansible - **Simple setup** — no master, no agents, just SSH - **Mixed environments** — Linux, Windows, network devices, cloud - **Team accessibility** — anyone who knows YAML can contribute - **Orchestration** — multi-step deployment workflows - **Small-medium scale** — under 5,000 hosts - **Existing SSH infrastructure** — no new ports to open ## When to Choose SaltStack - **Speed is critical** — real-time execution across thousands of hosts - **Event-driven automation** — react to system events automatically - **Very large scale** — 10,000+ managed nodes - **Continuous mon... --- ## Ansible vs Terraform — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/ansible-vs-terraform-detailed-comparison Description: Compare Ansible and Terraform for infrastructure automation. When to use each, and how to combine them. Tested, copy-paste examples included. # Ansible vs Terraform — Detailed Comparison ## Introduction Compare Ansible and Terraform for infrastructure automation. When to use each, and how to combine them. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare Ansible and Terraform for infrastructure automation. When to use each, and how to combine them. Start with the fundamentals,... --- ## Ansible vs Terraform — Key Differences Explained URL: https://www.ansiblebyexample.com/articles/are-ansible-and-terraform-the-same Description: Ansible vs Terraform comparison — understand when to use each tool, key differences in state management and execution, and how to combine them for. ## Introduction Ansible and Terraform are the two most popular Infrastructure as Code tools — but they solve different problems. Ansible excels at **configuration management and orchestration** (what happens *on* your servers), while Terraform excels at **infrastructure provisioning** (creating the servers themselves). Understanding when to use each — and how to combine them — is key to effective DevOps. ## Quick Comparison | Feature | Ansible | Terraform | |---------|---------|-----------| | **Primary purpose** | Configuration management, orchestration | Infrastructure provisioning | | **Language** | YAML (playbooks) | HCL (HashiCorp Configuration Language) | | **Approach** | Procedural + Declarative | Declarative | | **State management** | Stateless | Stateful (terraform.tfstate) | | **Agent** | Agentless (SSH/WinRM) | Agentless (API calls) | | **Execution** | Push-based | Plan → Apply | | **Strength** | Software config, app deployment | Cloud resource lifecycle | | **Idempotent** | Yes (module-dependent) | Yes (by design) | | **Rollback** | Manual (run previous playbook) | `terraform destroy` or previous state | | **Ecosystem** | 85+ collections, 30K+ modules | 3,000+ providers | | **License** | GPL v3 (fully open source) | BSL 1.1 (OpenTofu fork is open source) | ## What Ansible Does Best ### Configuration Management [code example] ### Application Deployment [code example] ### Orchestration and Multi-Step Workflows [code example] ## What Terraform Does Best ##... --- ## Ansible vs Terraform — Which Tool When? Complete Comparison (2026) URL: https://www.ansiblebyexample.com/articles/ansible-vs-terraform-comparison-which-tool Description: Comprehensive comparison of Ansible vs Terraform. When to use each, strengths, weaknesses, and how to use them together for complete infrastructure. # Ansible vs Terraform — Which Tool When? ## Quick Decision | Need | Use | |------|-----| | Provision cloud infrastructure (VMs, VPCs, databases) | **Terraform** | | Configure servers (install packages, manage services) | **Ansible** | | Deploy applications | **Ansible** | | Manage Kubernetes resources | **Either** (Terraform for cluster, Ansible for apps) | | Network device configuration | **Ansible** | | One-time ad-hoc tasks | **Ansible** | | Track infrastructure state | **Terraform** | ## Core Differences ### Approach **Terraform:** Declarative — "I want 3 EC2 instances" [code example] **Ansible:** Procedural (with declarative modules) — "Install nginx, then start it" [code example] ### State Management **Terraform:** Maintains a state file tracking all resources - Knows what exists, what changed, what to destroy - Can detect drift - State must be stored securely (S3, Terraform Cloud) **Ansible:** Stateless — no state file - Checks current state on each run - Idempotent modules ensure desired state - No drift detection built-in ### Language **Terraform:** HCL (HashiCorp Configuration Language) **Ansible:** YAML + Jinja2 ### Agent **Terraform:** Agentless (API calls to cloud providers) **Ansible:** Agentless (SSH/WinRM to servers) ## Where Each Excels ### Terraform Wins - **Cloud resource provisioning** (AWS, Azure, GCP) - **Infrastructure lifecycle** (create, update, destroy) - **Dependency graphing** (parallel resource creation) - **State tracking** (know... --- ## Ansible vs Terraform: Key Differences and When to Use Each URL: https://www.ansiblebyexample.com/articles/ansible-vs-terraform-key-differences-and-when-to-use-each Description: Ansible vs Terraform compared — learn the key differences in approach, language, state management, and use cases. When to use each tool and how they work. ## Ansible vs Terraform at a Glance | Feature | Ansible | Terraform | |---------|---------|-----------| | **Primary purpose** | Configuration management | Infrastructure provisioning | | **Language** | YAML (playbooks) | HCL (HashiCorp Configuration Language) | | **Approach** | Procedural (step-by-step) | Declarative (desired state) | | **State management** | Stateless (no state file) | Stateful (terraform.tfstate) | | **Agent** | Agentless (SSH/WinRM) | Agentless (API calls) | | **Idempotent** | Yes (module-dependent) | Yes (built-in) | | **Cloud support** | Good (via collections) | Excellent (native providers) | | **OS configuration** | Excellent | Not designed for this | | **Learning curve** | Lower (YAML) | Moderate (HCL + state) | | **Drift detection** | Limited | Built-in (`terraform plan`) | ## When to Use Ansible Ansible excels at **configuring what's already running**: - Installing and configuring software packages - Managing users, files, and permissions - Deploying applications and code - Running ad-hoc commands across servers - Orchestrating multi-step workflows - Network device configuration - Security hardening and compliance [code example] ## When to Use Terraform Terraform excels at **creating and destroying infrastructure**: - Provisioning cloud resources (VMs, networks, databases) - Managing DNS records and load balancers - Creating Kubernetes clusters - Setting up cloud IAM policies - Multi-cloud infrastructure [code example] ## Using Ansible and ... --- ## Ansible VSCode Extension — Install URL: https://www.ansiblebyexample.com/articles/streamline-your-ansible-development-with-visual-studio-code-a-step-by-step-guide-to-installing-the-ansible-extension Description: Install and configure the Red Hat Ansible extension for Visual Studio Code. Syntax highlighting, autocompletion, linting, and playbook execution. ## Introduction Visual Studio Code with the Red Hat Ansible extension is the best IDE setup for Ansible development. It provides syntax highlighting, auto-completion, inline documentation, ansible-lint integration, and Jinja2 template support — all in one editor. This guide covers installation, configuration, and productivity tips. ## Prerequisites | Requirement | Minimum Version | Install Command | |-------------|----------------|-----------------| | VS Code | 1.85+ | Download | | Python | 3.9+ | `sudo dnf install python3` or `brew install python` | | Ansible | 2.14+ | `pip install ansible` | | ansible-lint | 6.0+ | `pip install ansible-lint` | ## Step 1: Install the Ansible Extension 1. Open VS Code 2. Click the Extensions icon (⇧⌘X / Ctrl+Shift+X) 3. Search for **"Ansible"** 4. Install **"Ansible"** by Red Hat (not the community one) Or install from the command line: [code example] ### What the Extension Provides | Feature | Description | |---------|-------------| | Syntax highlighting | YAML + Jinja2 color coding | | Auto-completion | Module names, parameters, and values | | Hover documentation | Module docs on mouse hover | | ansible-lint integration | Real-time linting in the editor | | YAML validation | Schema-based YAML validation | | Go to definition | Navigate to role/task definitions | | Code snippets | Quick templates for tasks, plays, roles | ## Step 2: Install Python Dependencies [code example] ### Windows Setup [code example] ## Step 3: Configure ... --- ## Ansible vyos_command Module — Run Commands on VyOS Routers URL: https://www.ansiblebyexample.com/articles/ansible-vyos-command-module-run-commands-on-vyos-routers Description: Execute operational commands on VyOS network routers with Ansible. Hands-on, tested examples and best practices for Ansible vyos_command Module. # Ansible vyos_command Module — Run Commands on VyOS Routers ## Introduction The `vyos.vyos.vyos_command` module execute operational commands on VyOS network routers with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install vyos.vyos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `vyos.vyos.vyos_command` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` befor... --- ## Ansible vyos_config Module — Manage VyOS Router Configuration URL: https://www.ansiblebyexample.com/articles/ansible-vyos-config-module-manage-vyos-router-configuration Description: Deploy and manage VyOS router and firewall configuration with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible vyos_config Module — Manage VyOS Router Configuration ## Introduction The `vyos.vyos.vyos_config` module deploy and manage VyOS router and firewall configuration with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install vyos.vyos` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `vyos.vyos.vyos_config` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` ... --- ## Ansible Wait for Port to be Open — Complete Guide URL: https://www.ansiblebyexample.com/articles/ansible-wait-for-port-to-be-open-complete-guide Description: Wait for a service port to become available after restart using wait_for module. Tested on real machines with clear, copy-paste examples. # Ansible Wait for Port to be Open — Complete Guide ## Introduction Wait for a service port to become available after restart using wait_for module. This guide provides practical examples, best practices, and production-ready patterns. ## Quick Start [code example] ## Method 1: Basic Approach [code example] ## Method 2: Advanced Pattern [code example] ## Production Example [code example] ## Best Practices 1. **Test in check mode first** — always run `--check --diff` before applying 2. **Use variables** — parameterize for reuse across environments 3. **Handle errors** — use block/rescue/always for graceful failures 4. **Idempotency** — ensure repeated runs produce the same result 5. **Documentation** — add comments explaining why, not what ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Task fails | Missing prerequisites | Check dependencies are met | | Not idempotent | State not checked | Add conditional checks | | Permission denied | Insufficient privileges | Use `become: true` | | Timeout | Network or resource issue | Increase timeout values | ## Conclusion Wait for a service port to become available after restart using wait_for module. Use check mode for validation, handle errors gracefully, and always test in non-production first. --- ## Ansible wait_for — Ports Files Conditions URL: https://www.ansiblebyexample.com/articles/ansible-wait-for-ports-files-conditions Description: Use the Ansible wait_for module to wait for ports to open, files to appear, services to start, and processes to complete. Deployment orchestration. ## Introduction `ansible.builtin.wait_for` pauses playbook execution until a condition is met — a port opens, a file appears, a string shows up in a log, or a process finishes. Essential for deployment orchestration where services take time to start. ## Wait for Port [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `port` | — | TCP port to check | | `host` | `127.0.0.1` | Host to check | | `timeout` | `300` | Max seconds to wait | | `delay` | `0` | Seconds to wait before first check | | `sleep` | `1` | Seconds between checks | | `state` | `started` | `started`, `stopped`, `present`, `absent`, `drained` | | `path` | — | File path to check | | `search_regex` | — | Regex to search in file or port output | | `msg` | — | Custom timeout error message | | `connect_timeout` | `5` | Connection timeout per check | | `exclude_hosts` | — | Hosts to exclude (for `drained`) | | `active_connection_states` | — | Connection states for `drained` | ## Wait for Port to Close [code example] ## Wait for File [code example] ## Wait for SSH [code example] ## Deployment Patterns ### Rolling Deployment [code example] ### Database Migration [code example] ### Multi-Service Startup [code example] ## Troubleshooting ### Timeout Too Short Default is 300s (5 min). Java apps may need more: [code example] ### Checking Remote Port from localhost Use `delegate_to`: [code example] ## Related Articles - Ansible service Module - ... --- ## Ansible wait_for vs uri vs assert — Health Check Patterns URL: https://www.ansiblebyexample.com/articles/ansible-wait-for-vs-uri-vs-assert-health-checks Description: Compare Ansible wait_for, uri, and assert for health checks. Learn which module to use for port checks, HTTP endpoints, and post-deployment validation. ## Introduction After deploying a service, you need to verify it's actually running. Ansible offers several modules for this: `wait_for` checks ports and files, `uri` makes HTTP requests, and `assert` validates conditions. Each targets a different layer of the health check stack. This guide shows which to use and how to combine them. ## Quick Comparison | Module | Checks | Waits/Retries | Best For | |--------|--------|--------------|----------| | `wait_for` | Port open, file exists, string in file | ✅ Built-in timeout | TCP port readiness | | `uri` | HTTP endpoint, status code, body | ⚠️ Use `until` for retries | HTTP/API health checks | | `assert` | Any condition expression | ❌ No waiting | Validating gathered data | | `wait_for_connection` | SSH/connection ready | ✅ Built-in timeout | After reboot | ## wait_for — Port and File Checks [code example] ## uri — HTTP Health Checks [code example] ## assert — Validate Conditions [code example] ## wait_for_connection — After Reboot [code example] ## Combined Health Check Pattern [code example] ## Common Mistakes [code example] ## Related Articles - Ansible wait_for Module - Ansible uri Module - Ansible assert Module - Ansible block vs rescue vs always ## Conclusion **wait_for** for TCP port and file readiness (fastest, lowest-level check). **uri** + **until** for HTTP endpoint health checks (most common post-deploy validation). **assert** for validating complex conditions after data gathering. **wait_for_connecti... --- ## Ansible wait_for_connection — Host Ready URL: https://www.ansiblebyexample.com/articles/ansible-wait-for-connection-wait-for-host-to-become-reachable Description: Use ansible.builtin.wait_for_connection to wait for a host to become reachable after reboot, provisioning, or network changes. Handle SSH and WinRM. # Ansible wait_for_connection — Wait for Host to Become Reachable ## Introduction `ansible.builtin.wait_for_connection` waits until Ansible can successfully connect to a host. Unlike `wait_for` (which checks ports), `wait_for_connection` verifies the full Ansible connection stack — SSH authentication, Python availability, and module execution. It's essential after reboots, cloud instance launches, and network reconfigurations. ## Basic Usage [code example] ## After Manual Reboot [code example] ## After Cloud Provisioning [code example] ## After Kernel Upgrade [code example] ## After Network Changes [code example] ## Windows (WinRM) [code example] ## wait_for_connection vs wait_for vs reboot | Feature | `wait_for_connection` | `wait_for` | `reboot` | |---------|----------------------|-----------|---------| | Checks | Full Ansible connection | Port/file/string | Reboot + reconnect | | Verifies Python | ✅ | ❌ | ✅ | | Verifies auth | ✅ | ❌ | ✅ | | Use case | After reboot/provision | Port readiness | Safe reboot | | Runs on | Controller | Remote (or local) | Remote | ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `timeout` | 600 | Max seconds to wait | | `delay` | 0 | Seconds before first attempt | | `sleep` | 1 | Seconds between attempts | | `connect_timeout` | 5 | Per-attempt connection timeout | ## Rolling Reboot Pattern [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Times out | In... --- ## Ansible wait_for_connection — Wait for Host to Come Online URL: https://www.ansiblebyexample.com/articles/ansible-wait-for-connection-wait-for-host-to-come-online Description: Ansible wait_for_connection guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible wait_for_connection — Wait for Host to Come Online ## Introduction Wait for Host to Come Online. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible wait_for_connection requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **... --- ## Ansible wait_for: Wait for Ports, Files, Conditions URL: https://www.ansiblebyexample.com/articles/time-management-in-ansible-using-declarative-playbooks-for-delayed-tasks Description: Learn the Ansible wait_for module: wait for ports, files, conditions. Covers timeout, delay, parameters, real-world examples, and troubleshooting. ## Introduction Time management is essential in infrastructure automation. Whether you need to wait for a service to start, pause between deployments, or delay execution until a port is open, Ansible provides several mechanisms for controlling timing in your playbooks. This guide covers the three main approaches: `ansible.builtin.wait_for` (condition-based waiting), `ansible.builtin.pause` (simple delays), and async tasks with polling. ## The wait_for Module The `ansible.builtin.wait_for` module waits for a condition to be met before continuing. It can wait for: - A **timeout** (simple sleep) - A **port** to become available - A **file** to exist or contain specific content - A **connection** to be established ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `timeout` | int | 300 | Maximum seconds to wait | | `delay` | int | 0 | Seconds to wait before starting checks | | `port` | int | — | TCP port to poll | | `host` | string | 127.0.0.1 | Host to check | | `path` | string | — | File path to check for | | `search_regex` | string | — | Regex to match in file or port output | | `state` | string | started | `started`, `stopped`, `present`, `absent`, `drained` | | `sleep` | int | 1 | Seconds between checks | | `connect_timeout` | int | 5 | Timeout for each connection attempt | | `msg` | string | — | Custom failure message | ## Basic Examples ### Simple Sleep (Wait N Seconds) [code example] **Note**: When using `... --- ## Ansible when — Conditional Tasks URL: https://www.ansiblebyexample.com/articles/ansible-when-conditional-run-tasks Description: Control task execution with Ansible when conditional. Test facts, variables, registered results, and combine multiple conditions with and/or logic. ## What Does `when` Do in Ansible? The `when` keyword controls whether a task runs. It evaluates a Jinja2 expression — if true, the task executes; if false, it's skipped. Use it to target specific operating systems, check variable values, act on command output, or implement conditional logic. ## Basic Syntax [code example] ## Test Variables [code example] ## Operating System Conditions [code example] ## Registered Results [code example] ## Multiple Conditions ### AND (all must be true) [code example] ### OR (any must be true) [code example] ### NOT [code example] ### Complex Combinations [code example] ## Conditional with Loops [code example] ## Conditional with Blocks [code example] ## Common Tests [code example] ## Troubleshooting ### "Conditional check failed" The variable is undefined. Use `default()`: [code example] ### Boolean Variable Issues [code example] ### when Doesn't Need {{ }} [code example] ## Related Articles - Ansible set_fact Module - Ansible Facts Guide - Ansible Handlers - Ansible register Variables - Ansible Blocks ## Conclusion `when` is how you make Ansible smart — run tasks only when they apply. Common patterns: OS-family branching (`ansible_os_family`), environment checks (`env == "production"`), and acting on command results (`register` + `when: result.rc != 0`). Use list format for multiple AND conditions, and `block` to apply one condition to many tasks. Remember: `when` already evaluates Jinja2 — don't wrap it i... --- ## Ansible win_acl Module — Manage Windows File Permissions URL: https://www.ansiblebyexample.com/articles/ansible-win-acl-module-manage-windows-file-permissions Description: Set NTFS file and folder permissions (ACLs) on Windows with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible win_acl Module. # Ansible win_acl Module — Manage Windows File Permissions ## Introduction The `ansible.windows.win_acl` module set NTFS file and folder permissions (ACLs) on Windows with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_acl` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--chec... --- ## Ansible win_certificate_store Module — Manage Windows Certificate Store URL: https://www.ansiblebyexample.com/articles/ansible-win-certificate-store-module-manage-windows-certificate-store Description: Import, export, and manage certificates in Windows certificate stores. Hands-on, tested examples and best practices for Ansible win_certificate_store Module. # Ansible win_certificate_store Module — Manage Windows Certificate Store ## Introduction The `ansible.windows.win_certificate_store` module import, export, and manage certificates in Windows certificate stores. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_certificate_store` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling... --- ## Ansible win_command vs win_shell URL: https://www.ansiblebyexample.com/articles/ansible-modules-win-command-vs-win-shell Description: win_command runs executables directly; win_shell runs PowerShell or cmd scripts. When to use each Ansible Windows module with practical examples. ## Ansible modules - win_command vs win_shell How to automate the execution of PowerShell or cmd.exe code on windows target hosts using Ansible Playbook with win_command and win_shell modules. What is the difference between win_command vs win_shell Ansible modules? These two Ansible modules are confused one for another but they're fundamentally different. Both modules allow you to execute win_command on a target host but in a slightly different way. ## win_command vs win_shell - `win_command` - Executes a command on a remote Windows node - it bypasses the Windows shell - always set changed to True - `win_shell` - Execute shell commands on Windows target hosts - redirections and win_shell's inbuilt functionality - always set changed to True The `win_command` and `win_shell` Ansible modules execute win_commands on the Windows target node. Generally speaking, is always better to use a specialized Ansible module to execute a task. However, sometimes the only way is to execute a Windows PowerShell or cmd.exe via the `win_command` or `win_shell` module. Let me reinforce again, you should avoid as much as possible the usage of `win_command`/`win_shell` instead of a better module. Both modules execute PowerShell or cmd.exe commands on Windows target nodes but in a sensible different way. The `win_command` modules execute win_commands on the target machine without using the target win_shell, it simply executes the win_command. The target `win_shell` is for example sending any P... --- ## Ansible win_copy — Copy Files to Windows URL: https://www.ansiblebyexample.com/articles/copy-files-to-windows-remote-hosts-ansible-module-win-copy Description: Copy files and folders to Windows remote hosts using ansible.windows.win_copy. Playbook examples with src, dest, content, remote_src, and backup options. ## Introduction Copying files to Windows remote hosts is a fundamental task in Windows automation with Ansible. The `ansible.windows.win_copy` module provides a reliable way to transfer files from the Ansible controller to Windows targets over WinRM. In this guide, you'll learn how to use `win_copy` effectively, including copying single files, directories, creating files from content, handling large files, and troubleshooting common issues. ## The ansible.windows.win_copy Module The full module name is `ansible.windows.win_copy`, part of the `ansible.windows` collection for managing Windows hosts. This module has been stable for years and is the standard way to copy files to Windows targets. ### Key Characteristics - Transfers files over **WinRM** (not SSH) - Supports single files, directories, and inline content - Uses checksums to determine if transfer is needed (idempotent) - **Not efficient for large files** — use `win_get_url` instead for files hosted on web servers - Opposite operation: `ansible.windows.win_fetch` (remote → controller) - Linux equivalent: `ansible.builtin.copy` ## Parameters Reference | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `dest` | path | Yes | — | Remote absolute path (use `\` for Windows paths) | | `src` | path | No* | — | Local source file/directory path | | `content` | string | No* | — | Text content to write directly to file | | `backup` | boolean | No | `false` | Cr... --- ## Ansible win_domain Module — Create Windows Active Directory Domain URL: https://www.ansiblebyexample.com/articles/ansible-win-domain-module-create-windows-active-directory-domain Description: Promote Windows Server to domain controller and create AD domains. Hands-on, tested examples and best practices for Ansible win_domain Module. # Ansible win_domain Module — Create Windows Active Directory Domain ## Introduction The `ansible.windows.win_domain` module promote Windows Server to domain controller and create AD domains. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_domain` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — ru... --- ## Ansible win_domain_membership Module — Join or Leave Windows Domain URL: https://www.ansiblebyexample.com/articles/ansible-win-domain-membership-module-join-or-leave-windows-domain Description: Join Windows hosts to Active Directory domain or remove membership. Tested on real machines with clear, copy-paste examples. # Ansible win_domain_membership Module — Join or Leave Windows Domain ## Introduction The `ansible.windows.win_domain_membership` module join Windows hosts to Active Directory domain or remove membership. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_domain_membership` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **T... --- ## Ansible win_dsc Module — Run PowerShell DSC Resources URL: https://www.ansiblebyexample.com/articles/ansible-win-dsc-module-run-powershell-dsc-resources Description: Execute PowerShell Desired State Configuration resources with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible win_dsc Module — Run PowerShell DSC Resources ## Introduction The `ansible.windows.win_dsc` module execute PowerShell Desired State Configuration resources with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_dsc` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check... --- ## Ansible win_environment Module — Manage Windows Environment Variables URL: https://www.ansiblebyexample.com/articles/ansible-win-environment-module-manage-windows-environment-variables Description: Set, modify, and remove Windows environment variables with Ansible. Hands-on, tested examples and best practices for Ansible win_environment Module. # Ansible win_environment Module — Manage Windows Environment Variables ## Introduction The `ansible.windows.win_environment` module set, modify, and remove Windows environment variables with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_environment` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in che... --- ## Ansible win_feature Module — Manage Windows Server Features URL: https://www.ansiblebyexample.com/articles/ansible-win-feature-module-manage-windows-server-features Description: Install and remove Windows Server roles and features with Ansible. Hands-on, tested examples and best practices for Ansible win_feature Module. # Ansible win_feature Module — Manage Windows Server Features ## Introduction The `ansible.windows.win_feature` module install and remove Windows Server roles and features with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_feature` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run wit... --- ## Ansible win_file — Create Windows Dir URL: https://www.ansiblebyexample.com/articles/create-a-directory-on-windows-like-systems-ansible-module-win-file Description: Create directories on Windows with Ansible win_file module. Set permissions, create nested paths, and manage folder structures with playbook examples. ## How to create a directory in Windows-like systems with Ansible? ## Ansible create a directory > `ansible.windows.win_file` Creates, touches, or removes files or directories Today we're talking about the Ansible module `win_file`. The full name is `ansible.windows.win_file`, which means that is part of the collection of modules to interact with windows machines. It's a module pretty stable and out for years. It creates, touches, or removes files or directories. For Linux targets, use the `ansible.builtin.file` module instead ## Main Parameters - `path` path - file path - `state` string - `file`/`absent`/`directory`/`touch` This module has some parameters to perform different tasks. The only required is "path", where you specify the filesystem path of the file you're going to edit. The state defines the type of object we are modifying, the default is "file" but for our use case, we need the "directory" option. ## Links - ansible.windows.win_file ## Playbook How to create an "example" directory/folder in the Desktop of the user on Windows-like systems with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to create a directory in Windows-like systems with Ansible. --- ## Ansible win_file — Files & Dirs URL: https://www.ansiblebyexample.com/articles/create-an-empty-file-in-windows-like-systems-ansible-module-win-file Description: Create files, directories, and symlinks on Windows with ansible.windows.win_file. Set permissions, manage paths, and clean up temp files. ## How to create an empty file in Windows-like systems with Ansible? ## Ansible creates an empty file - `ansible.windows.win_file` - Creates, touches, or removes files or directories Today we're talking about the Ansible module `win_file`. The full name is `ansible.windows.win_file`, which means that is part of the collection of modules to interact with windows machines. It's a module pretty stable and out for years. It creates, touches, or removes files or directories. For Linux targets, use the ansible.builtin.file module) instead. ## Parameters - path path - file path - state string - file/absent/directory/touch This module has some parameters to perform any tasks. The only required is "path", where you specify the filesystem path of the file you're going to edit. The state defines the type of object we are modifying, the default is "file" but for our use case, we need the "touch" option. ## Links - ansible.windows.win_file ## Playbook Create an empty file in Windows-like systems with Ansible playbook ### code [code example] ### execution [code example] ### idempotency not valid [code example] ### before execution ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to create an empty file in Windows-like systems with Ansible. --- ## Ansible win_file — Windows Files Dirs URL: https://www.ansiblebyexample.com/articles/ansible-win-file-module-windows-files-directories Description: Use the Ansible win_file module to create, delete, and manage files and directories on Windows hosts. Includes examples for directory creation, symlinks,. ## Introduction The `ansible.windows.win_file` module manages files and directories on Windows targets — create directories, delete files, create symbolic links, and set attributes. It's the Windows equivalent of `ansible.builtin.file` for Linux. Every Windows automation playbook uses it for directory setup, cleanup, and file organization. ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `path` | ✅ | — | Target file or directory path | | `state` | ❌ | `file` | `file`, `directory`, `touch`, `absent`, `link` | | `force` | ❌ | `false` | Force creation of symlinks | **State values:** | State | Description | |-------|-------------| | `directory` | Create directory (and parents) if it doesn't exist | | `touch` | Create empty file or update timestamp | | `absent` | Delete file or directory recursively | | `file` | Assert file exists (fail if not) | | `link` | Create symbolic link (requires `src`) | ## Create Directories [code example] ## Create Empty Files [code example] ## Delete Files and Directories [code example] ## Symbolic Links [code example] ## Practical Patterns ### Application Deployment Directory Setup [code example] ### IIS Site Setup [code example] ### Cleanup Old Releases [code example] ### Check File Exists Before Acting [code example] ## win_file vs Other Windows File Modules | Module | Use For | |--------|---------| | `win_file` | Create/delete dirs, touch files, symlinks | | `w... --- ## Ansible win_firewall_rule Module — Manage Windows Firewall Rules URL: https://www.ansiblebyexample.com/articles/ansible-win-firewall-rule-module-manage-windows-firewall-rules Description: Create, modify, and delete Windows Defender Firewall rules with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible win_firewall_rule Module — Manage Windows Firewall Rules ## Introduction The `ansible.windows.win_firewall_rule` module create, modify, and delete Windows Defender Firewall rules with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_firewall_rule` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in... --- ## Ansible win_get_url — Download Files on Windows Hosts URL: https://www.ansiblebyexample.com/articles/ansible-win-get-url-download-files-on-windows-hosts Description: Download files to Windows hosts with ansible.windows.win_get_url. Handle proxies, checksums, authentication, and TLS for remote file downloads. # Ansible win_get_url — Download Files on Windows Hosts ## Introduction The `ansible.windows.win_get_url` module downloads files from HTTP, HTTPS, and FTP URLs to Windows remote hosts. It's the Windows equivalent of `ansible.builtin.get_url` — handles authentication, proxy settings, checksum validation, and TLS certificate handling. ## Quick Reference [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `url` | (required) | URL to download | | `dest` | (required) | Destination path on Windows host | | `checksum` | — | Verify file integrity (algorithm:hash) | | `checksum_url` | — | URL containing checksum | | `force` | false | Re-download even if file exists | | `headers` | — | Custom HTTP headers | | `url_username` | — | HTTP basic auth username | | `url_password` | — | HTTP basic auth password | | `proxy_url` | — | HTTP proxy URL | | `proxy_username` | — | Proxy auth username | | `proxy_password` | — | Proxy auth password | | `validate_certs` | true | Validate SSL certificates | | `timeout` | 10 | Connection timeout in seconds | | `use_default_credential` | false | Use Windows default credential | | `use_proxy` | true | Use system proxy settings | ## Common Patterns ### Download and Install MSI [code example] ### Download with Authentication [code example] ### Download Through Corporate Proxy [code example] ### Download with Custom Headers (Bearer Token) [code example] ### Conditional Download (Only If Abs... --- ## Ansible win_get_url — Windows Files URL: https://www.ansiblebyexample.com/articles/download-a-file-in-windows-like-systems-ansible-module-win-get-url Description: Download files from HTTP/HTTPS on Windows with ansible.windows.win_get_url. Proxy, authentication, checksum verification, and retry examples. ## How to download a file in Windows-like systems with Ansible? ## Ansible download a file in Windows-like systems - ansible.windows.win_get_url - Downloads file from HTTP, HTTPS, or FTP to node Let's talk about the Ansible module `win_get_url`. The full name is `ansible.windows.win_get_url`, which means that is part of the collection of modules of Ansible to interact with Windows nodes. It downloads files from HTTP, HTTPS, or FTP to node For Linux targets, use the `ansible.builtin.get_url` Ansible module instead. ## Parameters - `url` string - URL - `dest` string - path - `force` string - no/yes - `checksum_algorithm`, `checksum`, `checksum_url` string - checksum_algorithm, checksum, checksum_url - `force_basic_auth`/`url_username`/`url_password`/`use_gssapi` - HTTP basic auth/GSSAPI-Kerberos - `headers` dictionary - custom HTTP headers - `http_agent` string - "`ansible-httpget`" - `proxy_url`, `proxy_username`, `proxy_password`, `proxy_use_default_credential` - proxy The parameters of the `win_get_url` module. The two required parameters are `url` and `dest`. The `url` parameter specifies the URL of the resource you're going to download. The `dest` parameter specifies the filesystem path where the resource is going to be saved on the target node. Let's deep dive into the "force" parameter. If "dest" is a file, Ansible is going to download every time the file. If "dest" is a directory the default behavior is not to replace a file, until you toggle to `yes` the force pa... --- ## Ansible win_hostname Module — Set Windows Computer Hostname URL: https://www.ansiblebyexample.com/articles/ansible-win-hostname-module-set-windows-computer-hostname Description: Change the hostname/computer name on Windows hosts with Ansible. Hands-on, tested examples and best practices for Ansible win_hostname Module. # Ansible win_hostname Module — Set Windows Computer Hostname ## Introduction The `ansible.windows.win_hostname` module change the hostname/computer name on Windows hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_hostname` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run wit... --- ## Ansible win_owner Module — Set Windows File Ownership URL: https://www.ansiblebyexample.com/articles/ansible-win-owner-module-set-windows-file-ownership Description: Change file and folder ownership on Windows hosts with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible win_owner Module — Set Windows File Ownership ## Introduction The `ansible.windows.win_owner` module change file and folder ownership on Windows hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_owner` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` b... --- ## Ansible win_package Module — Install Windows Software Packages URL: https://www.ansiblebyexample.com/articles/ansible-win-package-module-install-windows-software-packages Description: Install MSI, EXE, and MSIX packages on Windows hosts with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible win_package Module. # Ansible win_package Module — Install Windows Software Packages ## Introduction The `ansible.windows.win_package` module install MSI, EXE, and MSIX packages on Windows hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_package` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run ... --- ## Ansible win_path Module — Manage Windows PATH Variable URL: https://www.ansiblebyexample.com/articles/ansible-win-path-module-manage-windows-path-variable Description: Add and remove directories from Windows system or user PATH variable. Tested on real machines with clear, copy-paste examples. # Ansible win_path Module — Manage Windows PATH Variable ## Introduction The `ansible.windows.win_path` module add and remove directories from Windows system or user PATH variable. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_path` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--che... --- ## Ansible win_ping — Test Windows Host URL: https://www.ansiblebyexample.com/articles/test-windows-host-availability-ansible-module-win-ping Description: Use the Ansible win_ping module to test WinRM connectivity and PowerShell availability on Windows hosts. Complete guide with playbook examples,. ## Introduction Before running any automation against Windows hosts, you need to verify that Ansible can connect and execute commands. The `win_ping` module is the standard connectivity test for Windows managed nodes — it verifies WinRM access and that PowerShell is available to execute Ansible modules. This is the Windows equivalent of the Linux `ping` module. ## What Does win_ping Actually Test? Unlike network ICMP ping, `win_ping` tests the **entire Ansible communication chain**: 1. **WinRM connectivity** — Can Ansible reach the Windows host over WinRM (HTTP/HTTPS)? 2. **Authentication** — Are the credentials valid? 3. **PowerShell execution** — Is PowerShell available and functional? 4. **Module execution** — Can Ansible transfer and execute a module on the remote host? If `win_ping` succeeds, your Windows host is fully ready for Ansible automation. ## Module Reference **Full name:** `ansible.windows.win_ping` **Collection:** `ansible.windows` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `data` | string | `pong` | Text to return in the response | ### Return Values | Key | Type | Description | |-----|------|-------------| | `ping` | string | The value of the `data` parameter (default: `pong`) | ## Basic Playbook [code example] Run it: [code example] Expected output: [code example] ## Ad-Hoc Command For a quick test without a playbook: [code example] Or test a single host: [code example] #... --- ## Ansible win_reboot — Automate Windows Reboots Safely URL: https://www.ansiblebyexample.com/articles/automating-windows-reboots-with-ansible Description: Reboot Windows machines with Ansible win_reboot module. Handle pending updates, wait for reconnection, set timeouts, and verify post-reboot state. ## Introduction In the fast-paced world of IT administration, automation stands as a pivotal tool for efficiency, reliability, and scalability. Among the various automation tools available, Ansible has emerged as a leader, especially for its simplicity and versatility. This article delves into a specific application of Ansible: rebooting Windows machines using the `ansible.windows.win_reboot` module. Whether you need to apply Windows Updates, finalize software installations, or perform routine maintenance, automating reboots with Ansible ensures consistency across your entire Windows fleet. ## Why Automate Windows Reboots? Regular reboots of Windows servers and workstations are essential for: - **Applying system updates** — Many Windows patches require a reboot to take effect - **Clearing memory leaks** — Long-running servers benefit from periodic restarts - **Finalizing software installations** — Some applications require a reboot to complete setup - **Maintaining system health** — Reboots ensure services start cleanly Manually rebooting machines, especially in large environments with dozens or hundreds of servers, is time-consuming and error-prone. Ansible's `win_reboot` module automates this reliably. ## Prerequisites Before using `ansible.windows.win_reboot`, ensure your environment is properly configured: 1. **WinRM connectivity** — Ansible communicates with Windows hosts over WinRM (Windows Remote Management) 2. **ansible.windows collection** — Install it with ... --- ## Ansible win_reboot — Reboot Windows URL: https://www.ansiblebyexample.com/articles/reboot-windows-hosts-ansible-module-win-reboot Description: Reboot Windows servers safely with ansible.windows.win_reboot. Complete guide with pre/post delays, timeout tuning, rolling reboots, conditional. ## Introduction Rebooting Windows servers is required after system updates, driver installations, domain joins, and configuration changes. The `ansible.windows.win_reboot` module handles the entire reboot cycle — initiating the restart, waiting for the host to go down, and verifying it's back online and responsive. For Linux/Unix targets, use `ansible.builtin.reboot` instead. ## The ansible.windows.win_reboot Module Part of the `ansible.windows` collection. The module: 1. Sends a reboot command to the Windows host 2. Waits for the host to become unreachable 3. Polls until the host responds to WinRM 4. Runs a test command to verify the system is fully operational 5. Returns the elapsed time **Requirement**: The connection user must have `SeRemoteShutdownPrivilege`. ### Install the Collection [code example] ## Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `reboot_timeout` | int | 600 | Max seconds to wait for reboot to complete | | `msg` | string | "Reboot initiated by Ansible" | Message shown to logged-in users | | `pre_reboot_delay` | int | 2 | Seconds to wait before rebooting | | `post_reboot_delay` | int | 0 | Seconds to wait after reboot before testing | | `connect_timeout` | int | 5 | WinRM connection timeout per attempt | | `test_command` | string | (detect logon screen) | Command to verify system is ready | | `boot_time_command` | string | (Get-CimInstance...) | Command to detect boot time | #... --- ## Ansible win_regedit — Registry Keys URL: https://www.ansiblebyexample.com/articles/add-windows-registry-on-windows-like-systems-ansible-module-win-regedit Description: Learn how to use Ansible win_regedit module to add, change, or remove Windows registry key-values efficiently and accurately with simple Ansible code. ## How to Add Windows Registry key-value on Windows-like systems with Ansible? Changing registry values manually can be time-consuming and error-prone. Ansible includes built-in capabilities for managing individual key-value pairs in an idempotent way. ## Ansible adds Windows Registry on Windows-like systems - `ansible.windows.win_regedit` - Get information about Windows registry keys Let's talk about the Ansible module `win_regedit`. The full name is `ansible.windows.win_regedit`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years and it works in Windows and Windows Server operating systems. It adds, changes, or remove registry keys and values. ## Parameters - `path` string - The full registry key path including the hive to search for - `name` string - Name of the registry entry in the path parameters. - `type` string - `string` / `none` / `binary` / `dword` / `expandstring` / `multistring` / `qword` - `data` string - Value of the registry entry - `state` string - `present` / `absent` The only mandatory parameter is "path" which is the full registry key path including the hive to search for. Almost mandatory is also the "name" of the name of the registry entry in the path parameters. Another important parameter is the "`type`" specify the datatype of the value: `string`, `dword`, `qword`, `binary`, `multistring`, etc. Some values could either be represented as a decimal n... --- ## Ansible win_regedit — Remove Registry URL: https://www.ansiblebyexample.com/articles/remove-windows-registry-path-or-key-on-windows-like-systems-ansible-module-win-regedit Description: How to automate the deletion of the Windows Registry “Test” path with one key “hello” under a specific hive Windows-like systems with Ansible Playbook. ## How to Remove Windows Registry key on Windows-like systems with Ansible? Changing registry values manually can be time-consuming and error-prone. Ansible includes built-in capabilities for managing individual key-value pairs in an idempotent way. ## Ansible remove Windows Registry on Windows-like systems - `ansible.windows.win_regedit` - Get information about Windows registry keys Let's talk about the Ansible module `win_regedit`. The full name is `ansible.windows.win_regedit `, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years and it works in Windows and Windows Server operating systems. It adds, changes, or removes registry keys and values. ## Parameters - path string - The full registry key path including the hive to search for - name string - Name of the registry entry in the path parameters. - state string - present/absent The only mandatory parameter is "path" which is the full registry key path including the hive to search for. You might like to specify a single "name" of the name of the registry entry. If you want to delete all the paths, basically all the Windows Registry tree but if you want only the single entry you need also to specify the "name" of it. Please be careful! The essential parameter for our use-case is "state" to specify if we would like to add or modify ("present" option) or remove ("absent" option). ## Playbook How to Remove Windows Registr... --- ## Ansible win_scheduled_task Module — Manage Windows Scheduled Tasks URL: https://www.ansiblebyexample.com/articles/ansible-win-scheduled-task-module-manage-windows-scheduled-tasks Description: Create, modify, and delete Windows Task Scheduler tasks with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible win_scheduled_task Module — Manage Windows Scheduled Tasks ## Introduction The `ansible.windows.win_scheduled_task` module create, modify, and delete Windows Task Scheduler tasks with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_scheduled_task` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test i... --- ## Ansible win_service Module — Manage Windows Services URL: https://www.ansiblebyexample.com/articles/ansible-win-service-module-manage-windows-services Description: Start, stop, configure, and manage Windows services with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible win_service Module. # Ansible win_service Module — Manage Windows Services ## Introduction The `ansible.windows.win_service` module start, stop, configure, and manage Windows services with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_service` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--che... --- ## Ansible win_share Module — Manage Windows File Shares URL: https://www.ansiblebyexample.com/articles/ansible-win-share-module-manage-windows-file-shares Description: Create and manage Windows SMB/CIFS network file shares with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible win_share Module. # Ansible win_share Module — Manage Windows File Shares ## Introduction The `ansible.windows.win_share` module create and manage Windows SMB/CIFS network file shares with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_share` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--che... --- ## Ansible win_stat — Check Dir Exists URL: https://www.ansiblebyexample.com/articles/check-if-a-directory-exists-on-windows-like-systems-ansible-module-win-stat Description: Discover how to check if a directory exists on Windows-like systems using Ansible ansible.windows.win_stat module. Follow along with a practical. ## How to check if a directory/folder exists on Windows-like systems with Ansible? ## Ansible check directory exists on Windows-like systems - `ansible.windows.win_stat` - Get information about Windows files Let's talk about the Ansible module `win_stat`. The full name is `ansible.windows.win_stat`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It gets information about Windows files. For Linux target use the `ansible.builtin.stat` module instead. ## Parameters & Return Values ### Mandatory Parameters - path string ### Main Return Values - stat complex - isdir The only mandatory parameter is "path" which is the filesystem full path of the object to check. The module returns a complex object, the property that is interesting for us is "isdir". This attribute is "true" if the object is a directory ## Links - ansible.windows.win_stat ## Playbook How to check if the "example" directory/folder exists on the Desktop of the user on Windows-like systems with Ansible Playbook. ### code [code example] ### directory doesn't exist execution [code example] ### directory exist execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to check if a directory exists on Windows-like systems with Ansible. --- ## Ansible win_stat — Verify Windows File URL: https://www.ansiblebyexample.com/articles/check-if-a-file-exists-on-windows-like-systems-ansible-module-win-stat Description: Discover how to check if a file exists on Windows systems with Ansible's win_stat module. This guide includes a live Playbook example and execution. ## How to Check if a file exists on Windows-like systems with Ansible? ## Ansible check file exists on Windows-like systems - `ansible.windows.win_stat` - Get information about Windows files Today we're talking about the Ansible module `win_stat`. The full name is `ansible.windows.win_stat`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It gets information about Windows files. For Linux target use the `ansible.builtin.stat` module instead. ## Parameters & Return Values ### Mandatory Parameters - path string ### Main Return Values - stat complex - exists The only mandatory parameter is "path" which is the filesystem full path of the object to check. You could also retrieve the checksum of the file in the most popular hash algorithm, just in case. The module returns a complex object, the property that is interesting for us is "exists". This attribute is "true" if the object exists. ## Links - ansible.windows.win_stat ## Playbook How to check if the file "example.txt" exists on the Desktop of the user on Windows-like systems with Ansible Playbook. ### code [code example] ### file doesn't exist execution [code example] ### file exist execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to check if a file exists on Windows-like systems with Ansible. --- ## Ansible win_template Module — Deploy Templates to Windows Hosts URL: https://www.ansiblebyexample.com/articles/ansible-win-template-module-deploy-templates-to-windows-hosts Description: Render Jinja2 templates and deploy to Windows remote hosts with Ansible. Hands-on, tested examples and best practices for Ansible win_template Module. # Ansible win_template Module — Deploy Templates to Windows Hosts ## Introduction The `ansible.windows.win_template` module render Jinja2 templates and deploy to Windows remote hosts with Ansible. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_template` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode... --- ## Ansible win_uri Module — Make HTTP Requests from Windows URL: https://www.ansiblebyexample.com/articles/ansible-win-uri-module-make-http-requests-from-windows Description: Send HTTP/HTTPS requests from Windows hosts for API calls and downloads. Hands-on, tested examples and best practices for Ansible win_uri Module. # Ansible win_uri Module — Make HTTP Requests from Windows ## Introduction The `ansible.windows.win_uri` module send HTTP/HTTPS requests from Windows hosts for API calls and downloads. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install ansible.windows` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `ansible.windows.win_uri` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--... --- ## Ansible win_user — Change Password URL: https://www.ansiblebyexample.com/articles/change-local-user-password-on-windows-like-systems-ansible-module-win-user Description: Learn to automate Windows user password changes with Ansible win_user module. Easily update passwords and manage user accounts on Windows-like systems. ## How to change user passwords on Windows-like systems with Ansible? Password change is a mundane task that every System Administrator needs to perform regularly for your user base. Using Ansible you could simplify your workflow and maintain consistent your IT infrastructure fleet. , ## Ansible changes local user password > `ansible.windows.win_user` Manages local Windows user accounts Today we're talking about the Ansible module `win_user`. The full name is `ansible.windows.win_user`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It manages local Windows user accounts. For Linux target use the `user` module instead. ## Parameters - `name` _string_ - user name - `state` _string_ - present/absent - `password` _string_ - clear text password - `update_password` _string_ - `always` / `on_create` The only required is "name", which is the user name. The "state" parameter allows us to create or delete a user, in our use case the default it's already set to "present" to create a user. The "password" set the password in clear text. So easily specify what password assign to the user, no hash function is needed. The "update_password" parameter specifies when the module will update the user password. "always" option will update passwords if they differ, "on_create" will only set the password for newly created users. ## ... --- ## Ansible win_user — Create Local Users URL: https://www.ansiblebyexample.com/articles/create-a-local-user-on-windows-like-systems-ansible-module-win-user Description: Learn how to automate the creation and management of local user accounts on Windows systems using Ansible’s win_user module. Follow our detailed. ## How to Create a local user on Windows-like systems with Ansible? ## Ansible creates the user account > `ansible.windows.win_user` Manages local Windows user accounts Today we're talking about Ansible module `win_user`. The full name is `ansible.windows.win_user`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It manages local Windows user accounts. For Linux target use the `user` module instead. ## Parameters - `name` _string_ - user name - `state` _string_ - present/absent - `password` _string_ - cleartext password - `description` _string_ - description of the group - `groups` _list_ - list of groups to adds or removes - `update_password` _string_ - always / on_create - `password_never_expires` _boolean_ - no / yes - `password_expired` _string_ - yes - change at next login / no - `account_locked` / account_disabled - no /yes The only required is "name", which is the user name. The "state" parameter allows us to create or delete a user, in our use case the default it's already set to "present" to create a user. The "password" set the password in cleartext. So easily specify what password assign to the user, no hash function are needed. The "description" parameter allows you to specify a description of the user, it's not mandatory but sometimes is useful. The "groups" parameter allows you to add or remove the... --- ## Ansible win_user Unhandled Exception — Password Complexity Fix URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-unhandled-exception-while-executing-module-win-user Description: Troubleshoot the Ansible win_user unhandled exception error caused by Windows password complexity requirements. Fix password policy violations with. ## Introduction The "Unhandled exception while executing module win_user" error is one of the more confusing Ansible errors because it doesn't clearly tell you what's wrong. The root cause is almost always that the password you're setting doesn't meet Windows password complexity requirements. This article explains the error, Windows password policy, and multiple solutions. ## The Error ### Problematic Playbook [code example] ### Error Output [code example] ## Understanding Windows Password Policy Windows Server (and domain-joined workstations) enforce password complexity by default: | Requirement | Default Setting | |---|---| | Minimum length | 8 characters (Server 2022: 14 for new installs) | | Complexity | Enabled | | History | Remember 24 passwords | | Maximum age | 42 days | | Minimum age | 1 day | ### Complexity Requirements When enabled, passwords must contain characters from **3 of 4** categories: 1. **Uppercase** letters (A-Z) 2. **Lowercase** letters (a-z) 3. **Digits** (0-9) 4. **Special characters** (!@#$%^&* etc.) Additionally: - Cannot contain the username or parts of the full name - Must meet minimum length ## Solutions ### Solution 1: Use a Complex Password [code example] ### Solution 2: Generate Passwords with Ansible [code example] ### Solution 3: Use Ansible Vault for Passwords [code example] ### Solution 4: Check Policy Before Creating User [code example] ## Common win_user Operations ### Create User with Full Options [code example]... --- ## Ansible Windows — Complete WinRM Guide URL: https://www.ansiblebyexample.com/articles/ansible-for-windows-complete-winrm-setup-and-automation-guide Description: Complete guide to using Ansible for Windows automation. Set up WinRM, configure Windows hosts, and use win_copy, win_service, win_chocolatey, and more. ## Ansible + Windows Overview Ansible manages Windows hosts using **WinRM** (Windows Remote Management) or **PSRP** (PowerShell Remoting Protocol) instead of SSH. The control node still runs on Linux/macOS. ## Step 1: Prepare the Windows Host Run this PowerShell script **on each Windows host** (as Administrator): [code example] Or use the official Ansible setup script: [code example] ### Fix: LocalAccountTokenFilterPolicy If you get authentication errors with local admin accounts: [code example] ### Fix: Network Connection Type If you see "WinRM firewall exception will not work since one of the network connection types on this machine is set to public": [code example] ## Step 2: Configure Ansible Inventory [code example] ### Install pywinrm on Control Node [code example] ## Step 3: Test Connectivity [code example] Expected output: [code example] ## Common Windows Modules ### Copy Files (win_copy) [code example] ### Manage Services (win_service) [code example] ### Install Software with Chocolatey [code example] ### Run PowerShell Commands [code example] ### Manage Windows Features [code example] ### Windows Reboot [code example] ### Manage Files and Directories [code example] ### Download Files [code example] ## WinRM vs PSRP | Feature | WinRM | PSRP | |---------|-------|------| | Protocol | HTTP/HTTPS | PowerShell Remoting | | Port | 5985/5986 | 5985/5986 | | Performance | Good | Better for large payloads | | Setup | Standard | Requires `... --- ## Ansible Windows — WinRM Modules URL: https://www.ansiblebyexample.com/articles/can-ansible-be-used-to-manage-windows-systems Description: Manage Windows servers with Ansible over WinRM. Install packages, configure IIS, manage users, and automate updates with native Windows modules. Ansible is a highly flexible automation tool that can manage **Windows systems** alongside Linux and other platforms. This article explains how Ansible enables Windows automation, its prerequisites, and key use cases. ## Can Ansible Manage Windows Systems? Yes, Ansible can manage and automate Windows systems efficiently. Using **Windows Remote Management (WinRM)** or SSH, Ansible interacts with Windows machines to execute tasks like configuring services, installing software, and managing files. ## Setting Up Ansible for Windows ### 1. Enable WinRM on Windows Hosts WinRM allows Ansible to communicate with Windows machines. To enable it: 1. Open PowerShell as Administrator. 2. Execute the following commands: [code example] ### 2. Install Required Libraries on Ansible Control Node Install the **pywinrm** library to enable WinRM communication: [code example] ### 3. Configure Inventory for Windows Add Windows hosts to the Ansible inventory file: [code example] ## Windows Modules in Ansible Ansible provides a wide range of modules specifically for managing Windows systems. These modules simplify tasks such as service configuration, user management, and software installation. ### Examples of Windows Modules 1. **`win_service`**: Manage Windows services. [code example] 2. **`win_package`**: Install or uninstall software. [code example] 3. **`win_user`**: Manage user accounts. [code example] 4. **`win_shell`**: Run PowerShell or command-line comman... --- ## Ansible Windows Backup — win_copy & win_robocopy Playbook Guide URL: https://www.ansiblebyexample.com/articles/ansible-windows-backup-win-copy-win-robocopy-playbook Description: Back up Windows files and directories with Ansible using win_copy and win_robocopy modules. Complete playbooks for scheduled backups, incremental copies,. ## Introduction Backing up Windows systems with Ansible gives you repeatable, scheduled, and auditable file protection without agents or third-party backup software. The two primary modules are `ansible.windows.win_copy` for simple file copies and `community.windows.win_robocopy` for incremental, large-scale directory mirroring. Together they cover everything from copying a single config file to mirroring entire application directories to network shares. ## Module Comparison | Feature | `win_copy` | `win_robocopy` | |---------|-----------|---------------| | Collection | `ansible.windows` | `community.windows` | | Use case | Single files, small directories | Large directories, incremental sync | | Mirror mode | No | Yes (`/MIR`) | | Retry on failure | No | Yes (configurable) | | Exclude patterns | No | Yes | | Log file | No | Yes | | Bandwidth throttle | No | Yes (`/IPG:n`) | | Remote → remote | No | Yes | | Incremental | No (always full copy) | Yes (only changed files) | ## Prerequisites [code example] [code example] The target Windows hosts need WinRM configured. See Configure Windows for Ansible. ## Pattern 1: Simple File Backup with win_copy [code example] ### Key Parameters for win_copy | Parameter | Description | Example | |-----------|-------------|---------| | `src` | Source file/directory path | `C:\App\config.xml` | | `dest` | Destination path | `C:\Backups\config.xml` | | `remote_src` | Source is on the remote host (not control node) | `true` | | `force` ... --- ## Ansible Windows Backup — win_copy and Robocopy URL: https://www.ansiblebyexample.com/articles/ansible-windows-backup-win-copy-win-robocopy Description: Backup Windows 10, 11, Server 2019, and 2022 with Ansible. Use win_copy, win_robocopy, and scheduled tasks for automated file backup and disaster recovery. # Ansible Windows Backup — win_copy and Robocopy ## Introduction Automating Windows backups with Ansible eliminates manual file copying and ensures consistent backup procedures across Windows 10, 11, Server 2019, and Server 2022. This guide covers `ansible.windows.win_copy` for simple file transfers, `community.windows.win_robocopy` for incremental/mirror backups, and scheduled tasks for unattended backup automation. ## Prerequisites [code example] ## Simple File Backup with win_copy [code example] ## Incremental Backup with Robocopy `community.windows.win_robocopy` wraps Windows Robocopy for efficient incremental and mirror backups: [code example] ## Robocopy Flags Explained | Flag | Purpose | |------|---------| | `/MIR` | Mirror — copies new/changed files, deletes extras at destination | | `/Z` | Restartable mode — resumes interrupted transfers | | `/R:3` | Retry 3 times on failure | | `/W:5` | Wait 5 seconds between retries | | `/MT:8` | Use 8 threads for parallel copying | | `/XD` | Exclude directories | | `/XF` | Exclude files | | `/COPYALL` | Copy all file attributes (data, timestamps, security) | | `/LOG` | Write log to file | | `/NFL /NDL` | No file/directory listing (quiet mode) | ## Scheduled Backup Task [code example] ## Network Share Backup [code example] ## System State Backup [code example] ## Verify Backups [code example] ## Troubleshooting [code example] ## Related Articles - Ansible for Windows — WinRM Setup - Ansible win_copy Module - ... --- ## Ansible Windows Domain Controller — AD DS Setup URL: https://www.ansiblebyexample.com/articles/ansible-windows-domain-controller-ad-ds-setup Description: Ansible Windows Domain Controller guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Windows Domain Controller — AD DS Setup ## Introduction AD DS Setup. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group Policy management,... --- ## Ansible Windows DSC — Desired State Configuration URL: https://www.ansiblebyexample.com/articles/ansible-windows-dsc-desired-state-configuration Description: Ansible Windows DSC guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible Windows DSC — Desired State Configuration ## Introduction Desired State Configuration. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group ... --- ## Ansible Windows Hosts — Step-by-Step URL: https://www.ansiblebyexample.com/articles/configure-a-windows-host-for-ansible-ansible-winrm Description: Learn how to configure Windows hosts for Ansible using basic authentication and WinRM. Follow our step-by-step guide to set up and run your first playbook. ## How to configure a Windows Host for Ansible? I'll show you step by step on a freshly installed machine how to configure a "basic" authentication, use a Local Accounts for authentication and successfully execute a simple "win_ping" Ansible Playbook. This initial configuration sometimes is a roadblock for some Windows users to start using Ansible. ## Configure a Windows Host for Ansible - Windows 7, 8.1, 10, 11 - Windows Server 2008, 2008 R2, 2012, 2012 R2, 2016, 2019, 2022 - PowerShell 3.0+ and .NET 4.0+ - WinRM or OpenSSH (experimental) The supported nodes include all the modern releases of Windows Desktop and Server. The full list includes Windows 7, 8.1, 10, 11, and Windows Server 2008, 2008 R2, 2012, 2012 R2, 2016, 2019, 2022. Ansible requires PowerShell 3.0 or newer and at least .NET 4.0 to be installed on the Windows host. You need to upgrade only old Windows 7 and Windows Server 2008 nodes. The communication between Ansible Controller and the target node is executed via a WinRM listener that needs to be created and activated. Ansible 2.8 has added an experimental SSH connection for Windows-managed nodes for Windows 10+ clients and Windows Server 2019+. In this example, we're going to cover the WinRM connection method with "basic" authentication. Refer to manual for more WinRM wide range of configuration options. ## Links - Setting up a Windows Host - Windows Remote Management ## Playbook How to configure a Windows Host for Ansible connections. - Create a use... --- ## Ansible Windows IIS — Deploy Web Applications URL: https://www.ansiblebyexample.com/articles/ansible-windows-iis-deploy-web-applications Description: Ansible Windows IIS guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Windows IIS — Deploy Web Applications ## Introduction Deploy Web Applications. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group Policy m... --- ## Ansible Windows Package — MSI and EXE Installation URL: https://www.ansiblebyexample.com/articles/ansible-windows-package-msi-and-exe-installation Description: Ansible Windows Package guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible Windows Package — MSI and EXE Installation ## Introduction MSI and EXE Installation. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group Po... --- ## Ansible Windows Registry — Manage Registry Keys URL: https://www.ansiblebyexample.com/articles/ansible-windows-registry-manage-registry-keys Description: Ansible Windows Registry guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Windows Registry — Manage Registry Keys ## Introduction Manage Registry Keys. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group Policy ma... --- ## Ansible Windows Service — Manage Windows Services URL: https://www.ansiblebyexample.com/articles/ansible-windows-service-manage-windows-services Description: Ansible Windows Service guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Windows Service — Manage Windows Services ## Introduction Manage Windows Services. Ansible manages Windows hosts over WinRM, providing the same declarative automation as Linux. This guide covers the `ansible.windows` and `community.windows` collections for Windows automation. ## Prerequisites [code example] [code example] ## Basic Windows Tasks [code example] ## Configuration Management [code example] ## Software Installation [code example] ## Windows Updates [code example] ## PowerShell Integration [code example] ## Scheduled Tasks [code example] ## Firewall Rules [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | WinRM connection refused | Run `winrm quickconfig` on Windows host | | Certificate error | Set `ansible_winrm_server_cert_validation: ignore` | | Access denied | Check user has admin privileges | | Timeout | Increase `ansible_winrm_operation_timeout_sec` | | PowerShell execution policy | Set `Set-ExecutionPolicy RemoteSigned` | ## Best Practices 1. **Use WinRM over HTTPS** (port 5986) in production 2. **Store credentials in Ansible Vault** — never plaintext 3. **Test with `win_ping`** before running playbooks 4. **Use Chocolatey** for software management when possible 5. **Reboot handling** — use `win_reboot` module with proper timeout ## Conclusion Ansible provides comprehensive Windows automation through the `ansible.windows` and `community.windows` collections. From software installation to Group Poli... --- ## Ansible Windows WinRM — Remote Mgmt URL: https://www.ansiblebyexample.com/articles/ansible-windows-winrm-setup-remote-management-guide Description: Configure WinRM for Ansible Windows automation. Set up HTTPS listeners, authentication, GPO deployment, and troubleshoot common connection issues. # Ansible Windows WinRM Setup — Remote Management Guide ## Introduction Ansible manages Windows hosts through WinRM (Windows Remote Management) instead of SSH. Setting up WinRM correctly — with HTTPS, proper authentication, and firewall rules — is the critical first step for Windows automation. This guide covers everything from basic setup to enterprise GPO deployment. ## Prerequisites [code example] ## Quick WinRM Setup (PowerShell) Run on each Windows host as Administrator: [code example] ## Manual WinRM Configuration [code example] ## Ansible Inventory for Windows [code example] ## Authentication Methods [code example] ### Kerberos Setup [code example] [code example] ## Test Connection [code example] ## GPO Deployment (Enterprise) [code example] ## Common Windows Playbook [code example] ## WinRM Verification Commands [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Connection refused | Enable WinRM: `Enable-PSRemoting -Force` | | SSL certificate error | Add `ansible_winrm_server_cert_validation: ignore` | | Authentication failed | Check username format: `user` (local) vs `user@DOMAIN` (Kerberos) | | "Access denied" | User must be in local Administrators group | | Timeout errors | Check firewall port 5986, increase `ansible_winrm_operation_timeout_sec` | | Double-hop fails | Use CredSSP: `ansible_winrm_transport: credssp` | | Kerberos "Clock skew" | Sync time between controller and DC: `ntpdate dc01.example.com` | ## B... --- ## Ansible WinRM Connection Error — Fix and Solutions URL: https://www.ansiblebyexample.com/articles/ansible-winrm-connection-error-fix-and-solutions Description: Resolve Windows WinRM connection failures from config, certs, and auth. Tested on real machines with clear, copy-paste examples. # Ansible WinRM Connection Error — Fix and Solutions ## Introduction Resolve Windows WinRM connection failures from config, certs, and auth. This troubleshooting guide covers all common causes and their solutions. ## Quick Fix [code example] ## Common Causes ### Cause 1: Configuration Issue [code example] ### Cause 2: Permission Problem [code example] ### Cause 3: Missing Dependency [code example] ## Diagnostic Steps [code example] ## Solutions | Cause | Solution | |-------|----------| | Missing permissions | Add `become: true` to task | | Wrong credentials | Update vault or inventory vars | | Network issue | Check firewall, DNS, routing | | Version mismatch | Upgrade Ansible or collection | | Config error | Validate with `ansible-lint` | ## Prevention 1. **Use ansible-lint** — catch issues before they hit production 2. **Test in staging** — verify changes in non-prod first 3. **Pin versions** — lock Ansible and collection versions 4. **Monitor logs** — watch for warnings that precede errors 5. **Document fixes** — save time on recurring issues ## Conclusion Resolve Windows WinRM connection failures from config, certs, and auth. Start with `-vvv` verbosity to identify the root cause, then apply the targeted fix from the solutions table above. --- ## Ansible WinRM over SSH — PSRP URL: https://www.ansiblebyexample.com/articles/tunneling-winrm-via-ssh-with-psrp Description: Tunnel WinRM through SSH with PSRP for secure Ansible Windows automation. No HTTPS certificates needed. Configure SSH, PSRP, and firewall rules. ## Introduction WinRM (Windows Remote Management) is Ansible's default transport for Windows targets, but it requires opening ports 5985/5986 and managing certificates. An alternative approach tunnels WinRM through SSH using the PowerShell Remoting Protocol (PSRP) — combining WinRM's Windows-native capabilities with SSH's proven security model. ## Why Tunnel WinRM via SSH? | Approach | Ports Required | Encryption | Certificate Management | |----------|---------------|------------|----------------------| | WinRM HTTP | 5985 | None | None | | WinRM HTTPS | 5986 | TLS | Required | | **WinRM via SSH (PSRP)** | **22** | **SSH** | **SSH keys only** | | Native SSH | 22 | SSH | SSH keys only | Benefits of SSH tunneling: - **Single port** — only port 22 needed (often already allowed through firewalls) - **SSH key authentication** — no certificate management - **Existing infrastructure** — reuse SSH bastion hosts and jump servers - **Encryption** — SSH provides proven end-to-end encryption ## Prerequisites ### On the Windows Target #### 1. Install OpenSSH Server [code example] #### 2. Install PowerShell 7+ [code example] #### 3. Configure SSH for PowerShell Remoting Edit `C:\ProgramData\ssh\sshd_config`: [code example] Restart SSH: [code example] ### On the Ansible Controller [code example] ## Ansible Configuration ### Inventory with PSRP over SSH [code example] ### SSH Tunnel Method #### Option 1: Manual SSH Tunnel [code example] Then configure Ansible to conne... --- ## Ansible WinRM Setup — Windows Hosts URL: https://www.ansiblebyexample.com/articles/ansible-winrm-setup-configure-windows-hosts Description: Set up WinRM on Windows for Ansible automation. Configure HTTPS, authentication, firewall rules, and troubleshoot common connection issues. ## Introduction Ansible connects to Windows hosts via WinRM (Windows Remote Management) or PSRP (PowerShell Remoting Protocol). This guide covers WinRM setup, HTTPS configuration, authentication options, and troubleshooting. ## Quick Setup (PowerShell Script) Run on each Windows host as Administrator: [code example] This script: - Enables WinRM - Creates a self-signed HTTPS certificate - Opens firewall ports - Enables basic authentication ## Manual Setup ### Step 1: Enable WinRM [code example] ### Step 2: Configure WinRM [code example] ### Step 3: HTTPS (Production) [code example] ### Step 4: Firewall [code example] ### Step 5: LocalAccountTokenFilterPolicy Required for local admin accounts: [code example] ## Ansible Inventory Configuration ### Basic HTTP (Testing Only) [code example] ### HTTPS (Production) [code example] ### YAML Inventory [code example] ## Authentication Methods | Transport | Description | Use Case | |-----------|-------------|----------| | `basic` | Username + password (HTTP) | Testing only | | `ntlm` | Windows NTLM | Local accounts | | `kerberos` | Kerberos/AD | Domain environments | | `credssp` | CredSSP | Double-hop scenarios | | `certificate` | Client certificate | Passwordless | ### Kerberos (Active Directory) [code example] [code example] ### CredSSP [code example] [code example] ## PSRP — Alternative to WinRM PSRP (PowerShell Remoting Protocol) is faster and more reliable: [code example] [code example] ### PSRP v... --- ## Ansible WireGuard — Deploy Secure VPN Tunnels URL: https://www.ansiblebyexample.com/articles/ansible-wireguard-vpn-secure-tunnels Description: Deploy WireGuard VPN with Ansible. Generate key pairs, configure site-to-site tunnels, remote access VPN, full mesh topology, DNS routing, kill switch,. ## Introduction WireGuard is a modern VPN protocol — fast, simple, and cryptographically sound. Its configuration is just a single file per interface, making it perfect for Ansible automation. Deploy site-to-site tunnels, remote access VPNs, or full mesh networks with key generation, peer configuration, and routing all managed as code. ## Generate Key Pairs [code example] ## Site-to-Site VPN [code example] ### Config Template [code example] ### Inventory [code example] ## Remote Access VPN (Road Warriors) [code example] ## Full Mesh Network [code example] The `wg0.conf.j2` template above already handles full mesh — each node gets a `[Peer]` block for every other node. ## Monitoring [code example] ## Troubleshooting ### No Handshake [code example] ### Enable IP Forwarding [code example] ## Related Articles - Ansible iptables Module - Ansible Firewall Module - Ansible SSH Key Management - Ansible sysctl Module ## Conclusion WireGuard's simplicity makes it ideal for Ansible automation — each peer is a `[Peer]` block in a config file, and Ansible templates it from inventory. Generate keys once, define addresses in host_vars, and the template builds the full mesh automatically. Use WireGuard for site-to-site tunnels between datacenters, remote access VPN for developers, or overlay networks for container communication. Adding a node is adding a host to the inventory. --- ## Ansible WireGuard VPN — Deploy Secure Mesh Networks URL: https://www.ansiblebyexample.com/articles/ansible-wireguard-vpn-deploy-mesh-networks Description: Deploy WireGuard VPN with Ansible. Point-to-site, site-to-site, and full mesh topologies. Key generation, peer management, firewall rules, and dynamic. ## Introduction WireGuard is the modern VPN protocol — faster, simpler, and more secure than OpenVPN or IPsec. Ansible automates WireGuard deployment across your infrastructure: generate key pairs, template configurations, manage peers, configure firewall rules, and build full mesh networks — all from a single playbook. ## Prerequisites [code example] ## Key Concepts [code example] Each peer has: - **Private key** — kept secret, never shared - **Public key** — derived from private key, shared with peers - **Allowed IPs** — which traffic routes through this peer ## Point-to-Site VPN (Road Warrior) ### Generate Keys [code example] ### Configure Server [code example] [code example] ### Generate Client Configs [code example] [code example] ## Site-to-Site VPN [code example] [code example] ## Full Mesh VPN For connecting all servers directly to each other: [code example] [code example] ## Manage Peers Dynamically ### Add a Peer [code example] ### Remove a Peer [code example] ## Monitor WireGuard [code example] ## Troubleshooting ### No Handshake - Verify UDP port is open: `ss -ulnp | grep 51820` - Check firewall allows UDP 51820 - Verify endpoint IP/DNS resolves correctly - Check public keys match on both sides ### Can't Reach Remote Network [code example] ## Related Articles - Ansible Firewall Module - Ansible iptables Module - Ansible sysctl Module - Ansible SSH Key Management ## Conclusion Ansible automates WireGuard VPN deployment for any ... --- ## Ansible with Apache Kafka — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-apache-kafka-complete-automation-guide Description: Deploy Kafka brokers, topics, ACLs, and Schema Registry with Ansible automation. With clear, copy-paste, step-by-step examples. # Ansible with Apache Kafka — Complete Automation Guide ## Introduction Deploy Kafka brokers, topics, ACLs, and Schema Registry with Ansible automation. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Kafka brokers, topics, ACLs, and Schema Registry with Ansible automation. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with ArgoCD GitOps — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-argocd-gitops-complete-automation-guide Description: Integrate Ansible with ArgoCD for GitOps-driven infrastructure management. With clear, copy-paste, step-by-step examples. # Ansible with ArgoCD GitOps — Complete Automation Guide ## Introduction Integrate Ansible with ArgoCD for GitOps-driven infrastructure management. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Integrate Ansible with ArgoCD for GitOps-driven infrastructure management. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with AWX Operator on Kubernetes — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-awx-operator-on-kubernetes-complete-automation-guide Description: Deploy AWX on Kubernetes using the AWX Operator with Ansible. Hands-on, tested examples and best practices for Ansible with AWX Operator on Kubernetes. # Ansible with AWX Operator on Kubernetes — Complete Automation Guide ## Introduction Deploy AWX on Kubernetes using the AWX Operator with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy AWX on Kubernetes using the AWX Operator with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. ## Further reading To go deeper, Ansible for Kubernetes by Example expands on these patterns in production. --- ## Ansible with Ceph Storage — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-ceph-storage-complete-automation-guide Description: Deploy Ceph storage clusters with monitors, OSDs, and RGW using Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Ceph Storage — Complete Automation Guide ## Introduction Deploy Ceph storage clusters with monitors, OSDs, and RGW using Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Ceph storage clusters with monitors, OSDs, and RGW using Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Cert Manager — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-cert-manager-complete-automation-guide Description: Automate TLS certificate management with cert-manager and Ansible on K8s. With clear, copy-paste, step-by-step examples. # Ansible with Cert Manager — Complete Automation Guide ## Introduction Automate TLS certificate management with cert-manager and Ansible on K8s. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate TLS certificate management with cert-manager and Ansible on K8s. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Cloudflare — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-cloudflare-complete-automation-guide Description: Manage Cloudflare DNS, WAF rules, page rules, and workers with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Cloudflare — Complete Automation Guide ## Introduction Manage Cloudflare DNS, WAF rules, page rules, and workers with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Manage Cloudflare DNS, WAF rules, page rules, and workers with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Consul — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-consul-complete-automation-guide Description: Deploy HashiCorp Consul clusters for service discovery and KV config with Ansible. Hands-on, tested examples and best practices for Ansible with Consul. # Ansible with Consul — Complete Automation Guide ## Introduction Deploy HashiCorp Consul clusters for service discovery and KV config with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy HashiCorp Consul clusters for service discovery and KV config with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Datadog — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-datadog-complete-automation-guide Description: Install Datadog agents, configure checks, and manage monitors with Ansible. Hands-on, tested examples and best practices for Ansible with Datadog. # Ansible with Datadog — Complete Automation Guide ## Introduction Install Datadog agents, configure checks, and manage monitors with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Install Datadog agents, configure checks, and manage monitors with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with DigitalOcean — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-digitalocean-complete-automation-guide Description: Provision and manage DigitalOcean droplets, databases, and networks with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with DigitalOcean — Complete Automation Guide ## Introduction Provision and manage DigitalOcean droplets, databases, and networks with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Provision and manage DigitalOcean droplets, databases, and networks with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Elasticsearch — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-elasticsearch-complete-automation-guide Description: Deploy Elasticsearch clusters, configure indices, and manage lifecycle policies with Ansible. With clear, copy-paste, step-by-step examples. # Ansible with Elasticsearch — Complete Automation Guide ## Introduction Deploy Elasticsearch clusters, configure indices, and manage lifecycle policies with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Elasticsearch clusters, configure indices, and manage lifecycle policies with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with F5 BIG-IP — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-f5-big-ip-complete-automation-guide Description: Configure F5 BIG-IP load balancers, pools, and virtual servers with Ansible. Hands-on, tested examples and best practices for Ansible with F5 BIG-IP. # Ansible with F5 BIG-IP — Complete Automation Guide ## Introduction Configure F5 BIG-IP load balancers, pools, and virtual servers with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure F5 BIG-IP load balancers, pools, and virtual servers with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with FreeIPA Identity — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-freeipa-identity-complete-automation-guide Description: Automate FreeIPA deployment, users, groups, and DNS with Ansible. Hands-on, tested examples and best practices for Ansible with FreeIPA Identity. # Ansible with FreeIPA Identity — Complete Automation Guide ## Introduction Automate FreeIPA deployment, users, groups, and DNS with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate FreeIPA deployment, users, groups, and DNS with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with GitLab — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-gitlab-complete-automation-guide Description: Deploy self-hosted GitLab, runners, CI/CD pipelines, and backups with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with GitLab — Complete Automation Guide ## Introduction Deploy self-hosted GitLab, runners, CI/CD pipelines, and backups with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy self-hosted GitLab, runners, CI/CD pipelines, and backups with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Grafana — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-grafana-complete-automation-guide Description: Automate Grafana deployment, dashboards, datasources, and alerting with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Grafana — Complete Automation Guide ## Introduction Automate Grafana deployment, dashboards, datasources, and alerting with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate Grafana deployment, dashboards, datasources, and alerting with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Harbor Container Registry — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-harbor-container-registry-complete-automation-guide Description: Deploy Harbor private container registry with Ansible automation. Hands-on, tested examples and best practices for Ansible with Harbor Container Registry. # Ansible with Harbor Container Registry — Complete Automation Guide ## Introduction Deploy Harbor private container registry with Ansible automation. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Harbor private container registry with Ansible automation. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Helm Charts — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-helm-charts-complete-automation-guide Description: Deploy and manage Helm charts on Kubernetes clusters with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Helm Charts — Complete Automation Guide ## Introduction Deploy and manage Helm charts on Kubernetes clusters with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy and manage Helm charts on Kubernetes clusters with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. ## Related guide Related reading: running Ansible against Kubernetes clusters covers this in real-world detail. --- ## Ansible with Hetzner Cloud — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-hetzner-cloud-complete-automation-guide Description: Automate Hetzner Cloud servers, networks, and load balancers with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Hetzner Cloud — Complete Automation Guide ## Introduction Automate Hetzner Cloud servers, networks, and load balancers with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate Hetzner Cloud servers, networks, and load balancers with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Istio Service Mesh — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-istio-service-mesh-complete-automation-guide Description: Deploy and configure Istio service mesh on Kubernetes with Ansible. Hands-on, tested examples and best practices for Ansible with Istio Service Mesh. # Ansible with Istio Service Mesh — Complete Automation Guide ## Introduction Deploy and configure Istio service mesh on Kubernetes with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy and configure Istio service mesh on Kubernetes with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Jenkins — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-jenkins-complete-automation-guide Description: Configure Jenkins controllers, agents, plugins, jobs, and pipelines with Ansible. With clear, copy-paste, step-by-step examples. # Ansible with Jenkins — Complete Automation Guide ## Introduction Configure Jenkins controllers, agents, plugins, jobs, and pipelines with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure Jenkins controllers, agents, plugins, jobs, and pipelines with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Keycloak SSO — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-keycloak-sso-complete-automation-guide Description: Deploy Keycloak identity provider and configure SSO realms with Ansible. Hands-on, tested examples and best practices for Ansible with Keycloak SSO. # Ansible with Keycloak SSO — Complete Automation Guide ## Introduction Deploy Keycloak identity provider and configure SSO realms with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Keycloak identity provider and configure SSO realms with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Linode Akamai — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-linode-akamai-complete-automation-guide Description: Provision Linode instances, NodeBalancers, and object storage with Ansible. With clear, copy-paste, step-by-step examples. # Ansible with Linode Akamai — Complete Automation Guide ## Introduction Provision Linode instances, NodeBalancers, and object storage with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Provision Linode instances, NodeBalancers, and object storage with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Longhorn Storage — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-longhorn-storage-complete-automation-guide Description: Deploy Longhorn distributed block storage on Kubernetes with Ansible. Hands-on, tested examples and best practices for Ansible with Longhorn Storage. # Ansible with Longhorn Storage — Complete Automation Guide ## Introduction Deploy Longhorn distributed block storage on Kubernetes with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Longhorn distributed block storage on Kubernetes with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with LXC LXD Containers — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-lxc-lxd-containers-complete-automation-guide Description: Manage LXC and LXD system containers and profiles with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with LXC LXD Containers — Complete Automation Guide ## Introduction Manage LXC and LXD system containers and profiles with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Manage LXC and LXD system containers and profiles with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with MikroTik RouterOS — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-mikrotik-routeros-complete-automation-guide Description: Configure MikroTik routers and switches with Ansible network modules. Tested on real machines with clear, copy-paste examples. # Ansible with MikroTik RouterOS — Complete Automation Guide ## Introduction Configure MikroTik routers and switches with Ansible network modules. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure MikroTik routers and switches with Ansible network modules. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with MinIO Object Storage — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-minio-object-storage-complete-automation-guide Description: Deploy MinIO S3-compatible object storage clusters with Ansible. Hands-on, tested examples and best practices for Ansible with MinIO Object Storage. # Ansible with MinIO Object Storage — Complete Automation Guide ## Introduction Deploy MinIO S3-compatible object storage clusters with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy MinIO S3-compatible object storage clusters with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Molecule Testing — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-molecule-testing-complete-automation-guide Description: Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. Tested on real machines with clear, copy-paste examples. # Ansible with Molecule Testing — Complete Automation Guide ## Introduction Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Test Ansible roles with Molecule using Docker, Podman, and Vagrant drivers. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with MongoDB — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-mongodb-complete-automation-guide Description: Automate MongoDB installation, replica sets, sharding, users, and backups with Ansible. With tested, real-world examples. # Ansible with MongoDB — Complete Automation Guide ## Introduction Automate MongoDB installation, replica sets, sharding, users, and backups with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate MongoDB installation, replica sets, sharding, users, and backups with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with MySQL MariaDB — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-mysql-mariadb-complete-automation-guide Description: Automate MySQL and MariaDB deployment, users, grants, backups, and replication with Ansible. Tested, copy-paste examples included. # Ansible with MySQL MariaDB — Complete Automation Guide ## Introduction Automate MySQL and MariaDB deployment, users, grants, backups, and replication with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate MySQL and MariaDB deployment, users, grants, backups, and replication with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Nagios Monitoring — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-nagios-monitoring-complete-automation-guide Description: Automate Nagios Core deployment, plugins, and host monitoring with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Nagios Monitoring — Complete Automation Guide ## Introduction Automate Nagios Core deployment, plugins, and host monitoring with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate Nagios Core deployment, plugins, and host monitoring with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Netbox IPAM — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-netbox-ipam-complete-automation-guide Description: Integrate NetBox as dynamic inventory source and IPAM for Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Netbox IPAM — Complete Automation Guide ## Introduction Integrate NetBox as dynamic inventory source and IPAM for Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Integrate NetBox as dynamic inventory source and IPAM for Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with New Relic — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-new-relic-complete-automation-guide Description: Deploy New Relic infrastructure agents and APM with Ansible automation. Follow clear, copy-paste examples and real-world usage notes for Ansible with New Relic. # Ansible with New Relic — Complete Automation Guide ## Introduction Deploy New Relic infrastructure agents and APM with Ansible automation. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy New Relic infrastructure agents and APM with Ansible automation. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Nexus Repository Manager — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-nexus-repository-manager-complete-automation-guide Description: Configure Sonatype Nexus for Maven, npm, Docker, and PyPI with Ansible. Hands-on, tested examples and best practices for Ansible with Nexus Repository Manager. # Ansible with Nexus Repository Manager — Complete Automation Guide ## Introduction Configure Sonatype Nexus for Maven, npm, Docker, and PyPI with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure Sonatype Nexus for Maven, npm, Docker, and PyPI with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with NFS Server — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-nfs-server-complete-automation-guide Description: Deploy and manage NFS server exports and client mounts with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with NFS Server — Complete Automation Guide ## Introduction Deploy and manage NFS server exports and client mounts with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy and manage NFS server exports and client mounts with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with OpenStack — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-openstack-complete-automation-guide Description: Manage OpenStack resources including instances, networks, and volumes with Ansible. With clear, copy-paste, step-by-step examples. # Ansible with OpenStack — Complete Automation Guide ## Introduction Manage OpenStack resources including instances, networks, and volumes with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Manage OpenStack resources including instances, networks, and volumes with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Packer — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-packer-complete-automation-guide Description: Build machine images with Packer provisioned by Ansible playbooks. Follow clear, copy-paste examples and real-world usage notes for Ansible with Packer. # Ansible with Packer — Complete Automation Guide ## Introduction Build machine images with Packer provisioned by Ansible playbooks. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Build machine images with Packer provisioned by Ansible playbooks. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Palo Alto Networks — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-palo-alto-networks-complete-automation-guide Description: Manage Palo Alto firewalls, security policies, and NAT with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Palo Alto Networks — Complete Automation Guide ## Introduction Manage Palo Alto firewalls, security policies, and NAT with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Manage Palo Alto firewalls, security policies, and NAT with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with pfSense OPNsense — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-pfsense-opnsense-complete-automation-guide Description: Automate pfSense and OPNsense firewall configuration with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with pfSense OPNsense — Complete Automation Guide ## Introduction Automate pfSense and OPNsense firewall configuration with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate pfSense and OPNsense firewall configuration with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Podman — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-podman-complete-automation-guide Description: Manage Podman containers, pods, and systemd integration with Ansible. Hands-on, tested examples and best practices for Ansible with Podman. # Ansible with Podman — Complete Automation Guide ## Introduction Manage Podman containers, pods, and systemd integration with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Manage Podman containers, pods, and systemd integration with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with PostgreSQL — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-postgresql-complete-automation-guide Description: Automate PostgreSQL installation, configuration, users, databases, backups, and replication with Ansible. With tested, real-world examples. # Ansible with PostgreSQL — Complete Automation Guide ## Introduction Automate PostgreSQL installation, configuration, users, databases, backups, and replication with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate PostgreSQL installation, configuration, users, databases, backups, and replication with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Proxmox — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-proxmox-complete-automation-guide Description: Automate Proxmox VE virtual machines, containers, and storage with Ansible. Hands-on, tested examples and best practices for Ansible with Proxmox. # Ansible with Proxmox — Complete Automation Guide ## Introduction Automate Proxmox VE virtual machines, containers, and storage with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Automate Proxmox VE virtual machines, containers, and storage with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with RabbitMQ — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-rabbitmq-complete-automation-guide Description: Configure RabbitMQ brokers, exchanges, queues, users, and clustering with Ansible. With clear, copy-paste, step-by-step examples. # Ansible with RabbitMQ — Complete Automation Guide ## Introduction Configure RabbitMQ brokers, exchanges, queues, users, and clustering with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure RabbitMQ brokers, exchanges, queues, users, and clustering with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Redis — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-redis-complete-automation-guide Description: Deploy and configure Redis clusters, sentinel, and ACLs with Ansible automation. Hands-on, tested examples and best practices for Ansible with Redis. # Ansible with Redis — Complete Automation Guide ## Introduction Deploy and configure Redis clusters, sentinel, and ACLs with Ansible automation. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy and configure Redis clusters, sentinel, and ACLs with Ansible automation. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Samba Active Directory — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-samba-active-directory-complete-automation-guide Description: Configure Samba AD domain controller and file shares with Ansible. Tested on real machines with clear, copy-paste examples. # Ansible with Samba Active Directory — Complete Automation Guide ## Introduction Configure Samba AD domain controller and file shares with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Configure Samba AD domain controller and file shares with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Semaphore UI — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-semaphore-ui-complete-automation-guide Description: Set up Ansible Semaphore as a lightweight web UI for running playbooks. Hands-on, tested examples and best practices for Ansible with Semaphore UI. # Ansible with Semaphore UI — Complete Automation Guide ## Introduction Set up Ansible Semaphore as a lightweight web UI for running playbooks. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Set up Ansible Semaphore as a lightweight web UI for running playbooks. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Splunk — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-splunk-complete-automation-guide Description: Deploy Splunk forwarders, indexers, and configure inputs with Ansible. Follow clear, copy-paste examples and real-world usage notes for Ansible with Splunk. # Ansible with Splunk — Complete Automation Guide ## Introduction Deploy Splunk forwarders, indexers, and configure inputs with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Splunk forwarders, indexers, and configure inputs with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Terraform Integration — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-terraform-integration-complete-automation-guide Description: Combine Terraform provisioning with Ansible configuration in hybrid IaC workflows. Tested, copy-paste examples included. # Ansible with Terraform Integration — Complete Automation Guide ## Introduction Combine Terraform provisioning with Ansible configuration in hybrid IaC workflows. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Combine Terraform provisioning with Ansible configuration in hybrid IaC workflows. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. ## Related guide Related reading: choosing between Terraform and Ansible covers this in real-worl... --- ## Ansible with Vagrant — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-vagrant-complete-automation-guide Description: Use Vagrant with Ansible provisioner for local development environments. Tested on real machines with clear, copy-paste examples. # Ansible with Vagrant — Complete Automation Guide ## Introduction Use Vagrant with Ansible provisioner for local development environments. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Use Vagrant with Ansible provisioner for local development environments. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Vault Secrets Engine — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-vault-secrets-engine-complete-automation-guide Description: Integrate HashiCorp Vault for dynamic secrets and PKI with Ansible automation. With clear, copy-paste, step-by-step examples. # Ansible with Vault Secrets Engine — Complete Automation Guide ## Introduction Integrate HashiCorp Vault for dynamic secrets and PKI with Ansible automation. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Integrate HashiCorp Vault for dynamic secrets and PKI with Ansible automation. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with Zabbix Monitoring — Complete Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-zabbix-monitoring-complete-automation-guide Description: Deploy Zabbix server, agents, and configure monitoring with Ansible. Hands-on, tested examples and best practices for Ansible with Zabbix Monitoring. # Ansible with Zabbix Monitoring — Complete Automation Guide ## Introduction Deploy Zabbix server, agents, and configure monitoring with Ansible. This guide covers installation, configuration, and production-ready playbook patterns. ## Prerequisites [code example] ## Quick Start [code example] ## Installation Playbook [code example] ## Configuration Management [code example] ## Monitoring and Health Checks [code example] ## Backup and Recovery [code example] ## Troubleshooting | Issue | Cause | Fix | |-------|-------|-----| | Connection refused | Service not running | Check service status and logs | | Authentication failed | Wrong credentials | Verify vault-encrypted vars | | Timeout | Resource unavailable | Increase timeout, check network | | Idempotency issue | State mismatch | Add proper state checks | ## Best Practices 1. **Use Vault for credentials** — never hardcode passwords 2. **Template configs** — use Jinja2 for environment-specific values 3. **Health checks** — verify service after changes 4. **Backup before changes** — always create restore point 5. **Test with Molecule** — validate in isolated environment ## Conclusion Deploy Zabbix server, agents, and configure monitoring with Ansible. Follow the patterns above for production-ready automation with proper error handling, health verification, and backup strategies. --- ## Ansible with_items vs loop — Migration Guide URL: https://www.ansiblebyexample.com/articles/ansible-with-items-vs-loop-migration-guide Description: Ansible with_items vs loop guide with practical Ansible examples, parameters, and troubleshooting tips. Tested on real machines with clear, copy-paste examples. # Ansible with_items vs loop — Migration Guide ## Introduction Migration Guide. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible with_items vs loop requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective tas... --- ## Ansible Write to File — Append Lines and Generate Content URL: https://www.ansiblebyexample.com/articles/ansible-write-to-file-append-lines-and-generate-content Description: Write content to files on remote hosts with Ansible. Append lines, generate files, manage configuration blocks, and build files from variables and templates. # Ansible Write to File — Append Lines and Generate Content ## Introduction Writing content to files is one of the most common Ansible operations — deploying configs, appending log entries, generating environment files, or building dynamic content from variables. This guide covers all the ways to write to files: create, overwrite, append, insert at specific positions, and manage blocks of content. ## Create/Overwrite File [code example] ## Append a Line [code example] ## Insert at Specific Position [code example] ## Write a Block of Lines [code example] ## Write Variable to File [code example] ## Replace Lines (Find and Replace) [code example] ## Build File from Template [code example] [code example] ## Append to File (Idempotent) [code example] ## Write Command Output to File [code example] ## Truncate and Rewrite [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | Duplicate lines on re-run | Use `lineinfile` (idempotent) not `shell: echo >>` | | Line added but not where expected | Use `insertafter`/`insertbefore` | | Block appears twice | Check `marker` matches — use unique markers | | File not created | Add `create: true` to lineinfile/blockinfile | | Permissions wrong after write | Set `mode` explicitly | | Content has extra blank lines | Use `|-` in YAML to strip trailing newline | ## Best Practices 1. **Use `lineinfile` for single lines** — idempotent, won't duplicate 2. **Use `blockinfile` for sections** — markers prevent dupl... --- ## Ansible Write Variable — copy vs template URL: https://www.ansiblebyexample.com/articles/write-a-variable-to-a-file-ansible-module-copy-vs-template Description: Write Ansible variables to files using copy content parameter or template module. Compare approaches for configs, JSON output, and dynamic content. ## How to write a variable to file with Ansible? From a simple value or the result of complex command execution on the target node often we have the need to write the result to a file. ## Ansible modules: copy vs template - `ansible.builtin.copy` It deals with whitespace and newlines. The quotes are important. - `ansible.builtin.template` For advanced formatting or if the content contains a variable, use the `ansible.builtin.template` module. The `copy` and `template` Ansible modules have the ability to write variables to a file. Long story short: use the `template` module instead of the `copy` module. Both modules write variables to a file but the template module is the safer way for advanced formatting or if the content contains a variable. Preferred also by the early adopter of Ansible, the `copy` module that deals with whitespace and newlines but performs poorly with quotes and escapes contents. On the other hand, the `template` module is the best option for advanced formatting or if the content contains a variable. ### Ansible module copy - Write Variable to a File - Ansible Playbook task: [code example] The main advantage to use the Ansible copy module to Write Variable to a File is that you could write it all in one Ansible Playbook file. In this example, the parameter `content` specifies the name of the `fruit` variable to be written to the `dest` parameter, the path of the destination file. ### Ansible module template - Write Variable to a File - Ansible Pl... --- ## Ansible XFS User Quotas Config URL: https://www.ansiblebyexample.com/articles/troubleshooting-configure-user-quotas-on-xfs-file-systems-using-ansible Description: Learn how to resolve the error when configuring user quotas in Ansible on XFS file systems and ensure quota management is correctly set up. ## Troubleshooting: Configure User Quotas on XFS File Systems Using Ansible Learn how to resolve the common error related to user quota configuration on XFS file systems with Ansible. --- ### Error Summary When attempting to configure user quotas on an XFS file system with Ansible, you might encounter the following error: [code example] This error occurs because the root file system `/` is not mounted with the necessary options (`usrquota` and `grpquota`) required to enable quota tracking. --- ### Root Cause The XFS file system requires specific mount options (`usrquota`, `grpquota`) for quotas to function. Without these options, the kernel cannot track or enforce disk usage limits. --- ### Solution: Enable Quota Support for XFS #### 1. **Verify Current Mount Options** Use the `mount` command to confirm the current mount options for the root file system: [code example] Example output: [code example] #### 2. **Update `/etc/fstab` to Add Quota Options** Edit `/etc/fstab` to include the `usrquota` and `grpquota` options: [code example] #### 3. **Remount the File System** Apply the updated mount options by remounting the file system: [code example] #### 4. **Enable Quota Management** Use the `xfs_quota` tool to enable quotas on the file system: [code example] #### 5. **Set User Quotas** Set specific disk usage limits for a user (e.g., `devops`): [code example] #### 6. **Verify Quota Configuration** Check the quota status for all users: [code example] --- ... --- ## Ansible XML Module — Parse and Modify XML Files URL: https://www.ansiblebyexample.com/articles/ansible-xml-module-parse-and-modify-xml-files Description: Ansible XML Module guide with practical Ansible examples, parameters, and troubleshooting tips. With clear, copy-paste, step-by-step examples. # Ansible XML Module — Parse and Modify XML Files ## Introduction Parse and Modify XML Files. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible XML Module requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selecti... --- ## Ansible YAML Indentation Errors: How to Find and Fix Them URL: https://www.ansiblebyexample.com/articles/indentation-error-ansible-troubleshooting Description: Complete guide to fixing Ansible YAML indentation errors. Learn common indentation mistakes, how to read error messages, and tools to prevent YAML. Indentation errors are the most common Ansible problem — and the most frustrating. YAML relies entirely on whitespace for structure, so a single misaligned space can break an entire playbook. This guide covers how to read YAML error messages, the most common indentation mistakes, and tools to prevent them. ## Why YAML Indentation Matters YAML uses indentation (spaces, never tabs) to define structure: - **2 spaces** is the Ansible convention (though any consistent number works) - **Tabs are not allowed** — YAML parsers reject them - **Indentation defines hierarchy** — child elements must be indented more than parents - **Siblings must align** — items at the same level must have identical indentation ## Common Error Messages ### "could not find expected ':'" [code example] This means a value is at the wrong indentation level. ### "We were unable to read either as JSON nor YAML" [code example] Usually caused by tabs mixed with spaces or inconsistent indentation. ## The 5 Most Common Indentation Mistakes ### 1. Task Not Indented Under tasks: **Wrong:** [code example] **Correct:** [code example] The task (`- name: Install nginx`) must be indented under `tasks:`. ### 2. Module Parameters Not Indented Under Module **Wrong:** [code example] **Correct:** [code example] Module parameters (`name`, `state`) must be indented further than the module name. ### 3. Mixing Tabs and Spaces **Wrong** (invisible but broken): [code example] **Fix:** Configure your editor to u... --- ## Ansible yarn Module — Manage Node.js Packages with Yarn URL: https://www.ansiblebyexample.com/articles/ansible-yarn-module-manage-node-js-packages-with-yarn Description: Install and manage JavaScript packages using Yarn package manager. Tested on real machines with clear, copy-paste examples. # Ansible yarn Module — Manage Node.js Packages with Yarn ## Introduction The `community.general.yarn` module install and manage JavaScript packages using Yarn package manager. This guide covers installation, parameters, practical examples, and troubleshooting for production use. ## Quick Reference [code example] ## Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `state` | No | present | Desired state (present/absent) | | `name` | Yes | — | Target resource name | ## Installation [code example] ## Basic Example [code example] ## Advanced Examples ### Idempotent Configuration [code example] ### Conditional Execution [code example] ### Loop Over Multiple Items [code example] ## Error Handling [code example] ## Troubleshooting | Error | Cause | Fix | |-------|-------|-----| | Module not found | Collection not installed | `ansible-galaxy collection install community.general` | | Permission denied | Insufficient privileges | Add `become: true` | | Timeout | Network/resource unavailable | Increase timeout, check connectivity | | Idempotency issue | Module reports changed every run | Check parameter values match desired state | ## Best Practices 1. **Use FQCN** — always use `community.general.yarn` instead of short name 2. **Register results** — capture output for conditional logic 3. **Handle errors** — use `block/rescue` for graceful failure handling 4. **Test in check mode** — run with `--check` ... --- ## Ansible yum and dnf — RHEL Packages URL: https://www.ansiblebyexample.com/articles/install-a-package-in-redhat-like-systems-ansible-module-yum Description: Install, update, and remove packages on Red Hat family systems with Ansible's yum and dnf modules. Complete parameter reference, version pinning, group. ## Introduction The `ansible.builtin.yum` and `ansible.builtin.dnf` modules manage packages on Red Hat family systems — RHEL, CentOS, CentOS Stream, Fedora, Oracle Linux, Rocky Linux, and AlmaLinux. They handle installation, updates, removal, group installs, and repository management in idempotent tasks. ## yum vs dnf — Which Module to Use? | OS | Native Package Manager | Recommended Module | |----|----------------------|-------------------| | RHEL/CentOS 7 | yum | `ansible.builtin.yum` | | RHEL 8/9 | dnf | `ansible.builtin.dnf` | | CentOS Stream 8/9 | dnf | `ansible.builtin.dnf` | | Fedora | dnf | `ansible.builtin.dnf` | | Rocky/Alma Linux | dnf | `ansible.builtin.dnf` | **Cross-platform:** `ansible.builtin.package` auto-detects the right module. ## Module Parameters | Parameter | Type | Description | |-----------|------|-------------| | `name` | list/string | Package name(s) to manage | | `state` | string | `present`, `latest`, `absent`, `installed`, `removed` | | `update_cache` | bool | Refresh repo metadata before install | | `enablerepo` | string | Enable specific repo for this transaction | | `disablerepo` | string | Disable specific repo for this transaction | | `exclude` | string | Packages to exclude | | `skip_broken` | bool | Skip packages with dependency issues | | `allow_downgrade` | bool | Allow installing older version | | `security` | bool | Only install security updates | | `bugfix` | bool | Only install bugfix updates | | `lock_timeout` | int | Seconds ... --- ## Ansible yum Module — Manage Packages on RHEL and CentOS URL: https://www.ansiblebyexample.com/articles/ansible-yum-module-manage-packages-rhel-centos Description: Use the Ansible yum module to install, update, and remove packages on RHEL, CentOS, and Fedora. Manage repositories, package groups, and version pinning. ## Introduction `ansible.builtin.yum` manages packages on Red Hat-based systems — RHEL, CentOS, Rocky Linux, AlmaLinux, and Fedora. Install, update, remove packages, and manage repositories. For RHEL 9+ and Fedora, `ansible.builtin.dnf` is the native package manager, but `yum` still works as a wrapper. ## Basic Usage [code example] ## Remove Packages [code example] ## Update All Packages [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Package name(s), URL, or local RPM path | | `state` | `present` | `present`, `installed`, `latest`, `absent`, `removed` | | `enablerepo` | — | Enable specific repo for this transaction | | `disablerepo` | — | Disable specific repo | | `disable_gpg_check` | `false` | Skip GPG signature check | | `security` | `false` | Only security-related updates | | `update_cache` | `false` | Force yum cache update | | `autoremove` | `false` | Remove unneeded dependencies | | `lock_timeout` | 30 | Seconds to wait for yum lock | | `exclude` | — | Packages to exclude | | `validate_certs` | `true` | Validate SSL for repo URLs | ## Install from URL or Local RPM [code example] ## Manage Repositories [code example] ## Package Groups [code example] ## yum vs dnf [code example] Use `ansible.builtin.package` for playbooks that target both Debian and RHEL families. ## Practical Patterns ### Web Server Setup [code example] ### Cross-Platform Package Install [code exampl... --- ## Ansible Zabbix — Deploy and Configure Monitoring URL: https://www.ansiblebyexample.com/articles/ansible-zabbix-deploy-and-configure-monitoring Description: Automate Zabbix server, agent, and proxy deployment with Ansible. Configure hosts, templates, triggers, and dashboards using community.zabbix collection. # Ansible Zabbix — Deploy and Configure Monitoring ## Introduction Zabbix is an enterprise-class monitoring solution for networks, servers, and applications. With the `community.zabbix` Ansible collection, you can automate the entire monitoring stack — deploy Zabbix server, install agents on all hosts, configure monitoring templates, and manage alerts through code. ## Prerequisites [code example] ## Deploy Zabbix Server [code example] ## Deploy Zabbix Agent on All Hosts [code example] [code example] ## Register Hosts via API [code example] ## Custom Monitoring Items [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Agent not connecting | Check firewall port 10050/10051 | | No data in Zabbix | Verify `Server=` matches Zabbix server IP | | API authentication failed | Check admin credentials, URL must include `/api_jsonrpc.php` path | | Template import failed | Ensure template XML version matches Zabbix version | | High CPU on server | Increase `CacheSize`, tune `StartPollers` | ## Best Practices 1. **Use Zabbix Agent 2** (Go-based) — better performance than legacy agent 2. **Active checks** (`ServerActive`) — agent pushes data, works behind NAT 3. **Template everything** — link templates to hosts, don't configure items per host 4. **Autoregister agents** — configure auto-registration rules for dynamic environments 5. **Encrypt agent communication** — use PSK or TLS certificates 6. **Monitor the monitor** — set up external checks for ... --- ## Ansible Zero Downtime Deployment — Blue-Green and Canary URL: https://www.ansiblebyexample.com/articles/ansible-zero-downtime-deployment-blue-green-and-canary Description: Ansible Zero Downtime Deployment guide with practical Ansible examples, parameters, and troubleshooting tips. Tested, copy-paste examples included. # Ansible Zero Downtime Deployment — Blue-Green and Canary ## Introduction Blue-Green and Canary. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Ansible Zero Downtime Deployment requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ... --- ## Ansible zypper — SUSE Packages URL: https://www.ansiblebyexample.com/articles/install-a-package-in-suse-like-systems-ansible-module-zypper Description: Install, update, and remove packages on SUSE and openSUSE with the Ansible zypper module. Repository management, patterns, and playbook examples. ## Introduction The `community.general.zypper` module manages packages on SUSE Linux Enterprise Server (SLES) and openSUSE using the zypper package manager. It's the SUSE equivalent of `ansible.builtin.apt` (Debian/Ubuntu) or `ansible.builtin.yum` (RHEL/CentOS). This article covers installation, removal, updates, repository management, and production patterns. ## Module Overview | Property | Value | |---|---| | FQCN | `community.general.zypper` | | Collection | `community.general` | | OS Support | SLES, openSUSE Leap, openSUSE Tumbleweed | | Become | Required (`become: true`) | ## Key Parameters | Parameter | Type | Default | Description | |---|---|---|---| | `name` | string/list | — | Package name(s) or pattern | | `state` | string | `present` | `present`, `absent`, `latest`, `dist-upgrade` | | `type` | string | `package` | `package`, `patch`, `pattern`, `product`, `srcpackage` | | `update_cache` | bool | `false` | Refresh repo metadata before operation | | `disable_recommends` | bool | `true` | Don't install recommended packages | | `force` | bool | `false` | Force package installation | | `oldpackage` | bool | `false` | Allow downgrade | | `extra_args` | string | — | Additional zypper CLI arguments | ## Basic Operations ### Install a Package [code example] ### Install Multiple Packages [code example] ### Install with Cache Refresh [code example] Equivalent to running `zypper refresh && zypper install dos2unix`. ### Install a Specific Version [code example] ... --- ## ansible_hostname vs inventory_hostname URL: https://www.ansiblebyexample.com/articles/ansible-terminology-ansible-hostname-vs-inventory-hostname-vs-ansible-fqdn Description: Understand the difference between ansible_hostname, inventory_hostname, and ansible_fqdn. When to use each variable with practical playbook examples. ## What is the difference between ansible_hostname vs inventory_hostname? These two ansible internal variables sometimes confuse one for another but they're fundamentally different. ### ansible_hostname and ansible_fqdn Read from the target machine hostname from the facts: - `ansible_hostname` read the hostname from the facts collected during the `gather_facts` - Same as the `uname -n` or `hostname` command-line - Need `gather_facts` enabled, otherwise the `ansible_facts` variable would be unavailable to use in your playbook - Same as hostname of the target host - As this is based on the `gather_facts` step. ansible_hostname not available in ad-hoc command ### inventory_hostname Read from Ansible inventory or hosts files: - `inventory_hostname` read the hostname from the inventory configuration or the hosts file. Could be different from the hostname configuration of the remote system. It could be only a name on the controller machine - `inventory_hostname` is always available to use in your playbook. - Could be different from the hostname of the target host - Available for both playbook and ad-hoc command ## Playbook Let me show you the difference between `ansible_hostname` vs `inventory_hostname` vs `ansible_fqdn` internal variables in a simple Ansible Playbook. ### code - hostnames.yml [code example] - inventory [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ## Conclusion Now you know more abo... --- ## ansible_password vs ansible_ssh_pass: SSH Authentication in Ansible URL: https://www.ansiblebyexample.com/articles/ansible-password-vs-ansible-ssh-pass-ssh-authentication-in-ansible Description: Learn the difference between ansible_password and ansible_ssh_pass in Ansible. Configure password-based SSH authentication with practical examples,. ## ansible_password vs ansible_ssh_pass In Ansible, both `ansible_password` and `ansible_ssh_pass` configure the SSH password for connecting to remote hosts. Here's what you need to know: | Variable | Status | Purpose | |----------|--------|---------| | `ansible_password` | **Current (recommended)** | SSH password for the connection plugin | | `ansible_ssh_pass` | **Legacy alias** | Old name, still works but deprecated | Since Ansible 2.0, `ansible_password` is the preferred variable name. The old `ansible_ssh_pass` still works as a backward-compatible alias. ## Setting the SSH Password in Inventory ### INI Format [code example] ### YAML Format [code example] ## Security Best Practice: Use Ansible Vault **Never store passwords in plain text.** Use Ansible Vault to encrypt sensitive variables: [code example] Inside the vault file: [code example] Reference it in your inventory or playbook: [code example] Run the playbook with vault: [code example] ## Related Connection Variables | Variable | Purpose | |----------|---------| | `ansible_password` | SSH password | | `ansible_user` | SSH username | | `ansible_become_pass` | Sudo/privilege escalation password | | `ansible_ssh_private_key_file` | Path to SSH private key | | `ansible_connection` | Connection type (ssh, local, winrm) | | `ansible_port` | SSH port (default: 22) | ## Prerequisite: sshpass For password-based SSH connections, you need `sshpass` installed on the Ansible control node: [code example] ##... --- ## Ansible-core 2.19 — Changes and Upgrade Guide URL: https://www.ansiblebyexample.com/articles/ansible-core-2-19 Description: A comprehensive field guide to Ansible-core 2.19: root causes behind breaking changes, current open issues, concrete refactors for Jinja/JMESPath,. # Ansible-core 2.19 > A practical, field-tested guide to what changed, what’s still broken, and how to upgrade safely (Oct 26, 2025) Ansible-core 2.19 is the biggest plumbing change since collections. It delivered the **Data Tagging** overhaul and a stricter templating engine, which in turn surfaced long-hidden assumptions in playbooks, roles, and collections—especially in networking. This guide explains the *why*, catalogs today’s *known issues*, and gives you copy-pasteable *mitigations* and an *upgrade plan* that won’t melt your pipelines. --- ## TL;DR (for busy humans) * 2.19 tightened **templating & typing** (“tagged” values) and changed parts of **module argument loading**. That exposed brittle Jinja/JMESPath patterns and broke some “direct execution” flows used by network content. ([Ansible Documentation][1]) * **ansible.netcommon** initially didn’t mesh with 2.19’s new behavior; vendor collections relying on it (Arista, Cisco, Juniper, etc.) were impacted until follow-up fixes landed. **Do not upgrade core alone**—move **core + netcommon + vendor collections** together after testing. ([Ansible][2]) * If you need a stable baseline today: [code example] Then ready your codebase for 2.19 using the steps below. (Some vendor ecosystems—e.g., **arista.avd 5.x**—explicitly support up to 2.18.x.) ([avd.arista.com][3]) --- ## What actually changed (and why it matters) ### 1) Data Tagging & stricter templating Values flowing through Jinja are now **explicitly typ... --- ## Ansible-core 2.21.3 Released - What's New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-core-2-21-3-released-what-s-new-and-how-to-test Description: Ansible-core 2.21.3 is out with bugfixes for the 2.21 branch. Learn what changed, where to find the changelog, and how to install, verify, and upgrade it. # Ansible-core 2.21.3 Released - What's New and How to Test ## Introduction Ansible-core 2.21.3 has been published on PyPI and tagged on GitHub. This is a maintenance release in the 2.21.x branch, meaning it ships bugfixes and small corrections rather than new features. This article walks through what is included, where to find the full changelog, and how to install or upgrade to this version in a controlled way. ## What's New Ansible-core 2.21.3 is a patch release. As with every point release in the ansible-core 2.21 series, no new modules, plugins, or breaking changes are expected. The purpose of this release is to consolidate fixes accumulated since 2.21.2 (or the prior known tag) into a stable, installable artifact. ### Where to Find the Details The project does not embed the full list of changes in the GitHub release body; instead, it points to the versioned changelog file in the repository: - Full changelog: `changelogs/CHANGELOG-v2.21.rst` on the `v2.21.3` tag - Release tag: `v2.21.3` Anyone tracking specific fixes (module behavior, connection plugin edge cases, inventory parsing, etc.) should consult that RST file directly, since it lists the individual changelog fragments merged for this release. ### Release Artifacts The release provides both a built wheel and a source distribution on PyPI. | Artifact | Type | Size | SHA256 | |---|---|---|---| | ansible_core-2.21.3-py3-none-any.whl | Built Distribution (wheel) | 2,446,988 bytes | 9e7dd367f7dc5d5e9fc5ae1ba... --- ## Ansible-core 2.21.4 Released - Security Hardening for URL Authentication Masking URL: https://www.ansiblebyexample.com/articles/ansible-core-2-21-4-released-security-hardening-for-url-authentication-masking Description: Ansible-core 2.21.4 fixes URL auth masking in apt_key, get_url, rpm_key, uri, url lookup and adds tempfile path traversal protection. # Ansible-core 2.21.4 Released - Security Hardening for URL Authentication Masking ## Introduction Ansible-core 2.21.4 was published on 2026-09-08, following 2.21.3. This is a bugfix release focused almost entirely on hardening how sensitive authentication data embedded in URLs is masked in module output, logs, and error messages. It also includes a small hardening fix for the `tempfile` module utility. No new features are introduced beyond a supporting minor change to `mask_url`. ## Whats New ### Minor Changes - `mask_url` function in `module_utils` has been extended to allow masking of authentication data embedded in URLs, providing the foundation used by several of the bugfixes below. ### Bugfixes The bulk of this release addresses a class of issues where authentication credentials embedded in URLs (e.g. `user:password@host` or `:password@host`) could leak into module output, return values, or error messages instead of being masked: - `apt_key` module now masks authentication information in all displays and returns of URI information. - `get_url` module now masks authentication information in all displays and returns of URI information. - `module_utils` - `mask_url` now correctly masks the password in URLs that contain a password but no username, such as `redis://:password@host`, instead of returning them unmasked. - `module_utils.urls` now masks in-line URL authentication information across all error messages. - `rpm_key` module now masks authentication informatio... --- ## Ansible-core 2.21.5 Released - Bugfixes for ansible-connection Permissions, ansible-test Sanity, and dnf5 URL: https://www.ansiblebyexample.com/articles/ansible-core-2-21-5-released-bugfixes-for-ansible-connection-permissions-ansible-test-sanity-and-dnf5 Description: Ansible-core 2.21.5 is out: fixes connection dir permissions, validate-modules sanity for secret key, and dnf5 destdir handling. # Ansible-core 2.21.5 Released - Bugfixes for ansible-connection Permissions, ansible-test Sanity, and dnf5 ## Introduction Ansible-core 2.21.5 was released on October 5, 2026, as a maintenance release following 2.21.4. This version does not introduce new features; it is a bugfix-only release that ships three targeted fixes affecting `ansible-connection`, the `ansible-test` sanity suite, and the `dnf5` module. The full changelog is available in the CHANGELOG-v2.21.rst file, and the release itself is tagged at v2.21.5. ## Whats New ### Bugfixes - **ansible-connection**: ensures that the connection persistent directory has private permissions. This covers the corner case in which the preceding directories do not exist or do not have sufficiently private permissions, which could otherwise leave the persistent connection socket directory exposed. - **ansible-test**: the `validate-modules` sanity test no longer fails when a plugin documents an option with the `secret` key. That key is only honored starting with ansible-core 2.22, where it masks the option value in output; earlier versions ignore it but now accept it in the sanity test, so collection authors can document `secret` options while still testing against 2.21 and earlier. - **dnf5 module**: the module now sets the dnf `destdir` configuration option from `download_dir` when `download_only` is `true`, matching what the documentation already states. Previously, packages downloaded with `download_only: true` could end u... --- ## Ansible-Core vs Ansible — Differences URL: https://www.ansiblebyexample.com/articles/ansible-terminology-ansible-vs-ansible-core-packages Description: Learn the differences between ansible-core and ansible community package — versioning, collections, installation, and which one to choose. ## Introduction Since Ansible 2.10, the project split into two distinct packages: **ansible-core** (the engine) and **ansible** (the community package with batteries included). This change confused many users, especially when pip installing one vs the other produced very different results. This article explains what each package contains, how versioning works, which one to install for your use case, and how the two packages relate to each other. ## The Split: What Happened After Ansible 2.9 Before Ansible 2.10, there was a single `ansible` package that contained everything — the runtime, all modules, and all plugins. With thousands of modules growing faster than core could release, the project restructured: [code example] ## ansible-core ### What Is ansible-core? `ansible-core` is the minimal Ansible engine. It contains: - **CLI tools**: `ansible`, `ansible-playbook`, `ansible-galaxy`, `ansible-vault`, `ansible-doc`, `ansible-pull`, `ansible-config`, `ansible-inventory`, `ansible-console` - **The Ansible language**: YAML playbook parsing, Jinja2 templating, variable precedence, conditionals, loops, blocks, handlers - **Builtin plugins**: A small set of essential modules and plugins in `ansible.builtin` — including `debug`, `copy`, `file`, `template`, `command`, `shell`, `setup`, `apt`, `yum`, `service`, `user`, `group`, `lineinfile`, `uri`, and others - **The plugin architecture**: Framework for loading collections, modules, callback plugins, connection plugins, etc.... --- ## Ansible-Core: The Foundation of Modern IT Automation URL: https://www.ansiblebyexample.com/articles/ansible-core Description: Complete guide to ansible-core — the minimal Ansible runtime. Learn installation, version management, included modules, collections, and how it differs. ## Introduction `ansible-core` is the minimal, essential runtime that powers Ansible. It includes the command-line tools (`ansible-playbook`, `ansible-galaxy`, `ansible-doc`), the execution engine, and a curated set of built-in modules — everything you need to run playbooks without the 85+ community collections bundled in the full `ansible` package. Understanding the difference between `ansible-core` and the `ansible` community package is crucial for managing dependencies, planning upgrades, and building lean automation environments. ## ansible-core vs Ansible Community Package | Feature | ansible-core | ansible (community package) | |---------|-------------|---------------------------| | CLI tools | ✅ All included | ✅ All included | | Built-in modules | ~70 modules | ~70 modules | | Community collections | ❌ Install separately | ✅ 85+ pre-installed | | Package size | ~15 MB | ~200+ MB | | Release cycle | Every ~4 months | Follows ansible-core | | Best for | Production, CI/CD, containers | Quick start, learning | ### What's Included in ansible-core [code example] ### Built-in Modules (ansible.builtin) ansible-core ships with essential modules: - **Files:** `copy`, `file`, `template`, `lineinfile`, `blockinfile`, `fetch`, `stat`, `find` - **System:** `service`, `systemd`, `user`, `group`, `cron`, `hostname`, `sysctl` - **Commands:** `command`, `shell`, `raw`, `script`, `expect` - **Packages:** `apt`, `yum`, `dnf`, `pip`, `package` - **Net:** `uri`, `get_url` - **Logic... --- ## ansible-inventory-grapher — Visualize Ansible Inventory Structure URL: https://www.ansiblebyexample.com/articles/visualizing-ansible-architectures-with-ansible-inventory-grapher Description: How to use ansible-inventory-grapher to visualize Ansible inventory structure. Install, generate DOT graphs, and render with Graphviz. Step-by-step. ## What is ansible-inventory-grapher? `ansible-inventory-grapher` is a command-line tool that generates visual graphs of your Ansible inventory — showing groups, hosts, and their relationships. It outputs DOT format that you render with Graphviz into PNG, SVG, or PDF diagrams. ## Installation [code example] ## Basic Usage [code example] This reads your inventory, generates a DOT graph, and pipes it to Graphviz to create a PNG image. ## Example Inventory [code example] ## Generate the Graph [code example] ## Graph a Specific Group [code example] ## Show Variables on the Graph [code example] ## Customize Graph Appearance Pass Graphviz attributes to change the layout: [code example] ## Use with Dynamic Inventory [code example] ## Automate Diagram Generation Add to your CI/CD or Makefile: [code example] ## Use Cases - **Documentation** — Auto-generate infrastructure diagrams for wikis and runbooks - **Debugging** — Spot misplaced hosts, wrong group membership, or inheritance issues - **Onboarding** — Help new team members understand inventory structure instantly - **Auditing** — Verify group hierarchy before running playbooks on production ## Alternative: ansible-inventory --graph Ansible includes a built-in text-based view: [code example] Output: [code example] This is simpler but doesn't produce visual diagrams. ## Related Articles - Ansible Tutorial for Beginners — Getting started - Ansible Best Practices — Directory structure and organization - ... --- ## Ansible-Lint Offline — Air-Gapped URL: https://www.ansiblebyexample.com/articles/ansible-lint-in-air-gapped-environments Description: A guide to running Ansible-Lint in air-gapped environments, covering offline setup, dependency management, and configuration for seamless linting. ## Using Ansible-Lint in Air-Gapped Environments: Best Practices and Troubleshooting When managing infrastructure in air-gapped environments—where systems are isolated from the internet for security purposes—teams often encounter challenges related to software dependencies that require online access. One common tool that may pose issues in such setups is `ansible-lint`, which is used to enforce coding standards for Ansible playbooks. In this article, we’ll explore how `ansible-lint` operates in air-gapped environments, the errors you might encounter, and solutions to help it work smoothly offline. --- ### Understanding Ansible-Lint and Galaxy Dependencies `ansible-lint` is a powerful tool for validating and enforcing standards across Ansible playbooks, roles, and collections. However, `ansible-lint` often requires access to collections or roles hosted on **Ansible Galaxy** (galaxy.ansible.com), the public repository for sharing Ansible content. In an air-gapped environment, calls to Galaxy will fail, resulting in errors and incomplete checks. When trying to use `ansible-lint` in such an environment, you may encounter errors like: [code example] This error indicates that `ansible-lint` is attempting to reach Galaxy to verify or download a collection, which is inaccessible in your air-gapped setup. ### Steps to Use Ansible-Lint Offline To configure `ansible-lint` to work effectively in an air-gapped environment, follow these best practices. --- ### 1. **Use the Off... --- ## Ansible-Lint Profiles — Choose the Right Lint Level URL: https://www.ansiblebyexample.com/articles/exploring-ansible-lint-profiles Description: Configure ansible-lint profiles from min to production. Understand rule severity, skip rules, custom profiles, and CI/CD integration. ## Introduction Ansible is a powerful automation tool that simplifies configuration management, application deployment, and task automation. Ensuring the quality and consistency of Ansible content is crucial for effective automation. Ansible-lint is a popular linting tool that helps identify issues and enforce best practices in Ansible playbooks, roles, and collections. Ansible-lint introduces the concept of profiles to gradually increase rule strictness throughout the content lifecycle. ## Understanding Ansible-Lint Profiles Ansible-lint profiles provide a structured way to manage linting rules based on the desired level of strictness. As your Ansible content evolves, you can apply different profiles to catch potential issues early in development and ensure compliance with best practices. Let's explore the available profiles and their purposes: ### 1. Min Profile The `min` profile serves as the foundation, ensuring Ansible can load content without fatal errors. Rules in this profile are mandatory and include: - `internal-error`: Prevent internal errors. - `load-failure`: Ensure content can be loaded. - `parser-error`: Identify parsing errors. - `syntax-check`: Verify syntax correctness. Developers can customize the profile by excluding specific files or providing dependencies to load the correct files. ### 2. Basic Profile Building upon the `min` profile, the `basic` profile addresses common coding issues and enforces standard styles and formatting. Key rules in thi... --- ## Ansible-Lint Rule Analysis and Best Practices URL: https://www.ansiblebyexample.com/articles/ansible-lint-rule-analysis-and-best-practices Description: Complete guide to ansible-lint — install, configure, understand rule categories, use autofix, integrate into CI/CD pipelines, write custom rules, and fix. ## Introduction ansible-lint is the standard static analysis tool for Ansible playbooks, roles, and collections. It catches bugs, enforces best practices, flags deprecated syntax, and can automatically fix many issues. Used locally during development and in CI/CD pipelines, ansible-lint ensures consistent, high-quality automation code across your team. This guide covers installation, configuration, every rule category, autofix, custom rules, and CI/CD integration. ## Install [code example] ## Quick Start [code example] ## Configuration ### .ansible-lint [code example] ### Profiles | Profile | Rules | Use Case | |---|---|---| | `null` | No rules | Disable linting | | `min` | Syntax only | Minimal checking | | `basic` | Common issues | Starting point | | `moderate` | + Best practices | Team projects | | `safety` | + Security | Production code | | `shared` | + Consistency | Shared roles/collections | | `production` | All rules | Production automation | ## Rule Categories ### args — Module Argument Validation Validates that module arguments are correct and match expected types. [code example] ### command-shell — Command Module Best Practices [code example] ### deprecated — Deprecated Syntax and Modules [code example] ### formatting — YAML Style [code example] ### idempotency — Ensure Repeatable Runs [code example] ### naming — Consistent Naming [code example] ### security — Sensitive Data [code example] ### unpredictability — Avoid Surprises [code exam... --- ## Ansible-Lint: Complete Guide to Linting Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/ansible-lint Description: Complete guide to ansible-lint — install, configure, run, and integrate into CI/CD. Covers rules, profiles, autofix, custom rules, and .ansible-lint. ## Introduction `ansible-lint` is the standard tool for checking Ansible playbooks, roles, and collections against best practices. It catches syntax errors, deprecated features, security issues, and style violations before they reach production. This guide covers installation, configuration, CI/CD integration, and every essential feature. ## Installation [code example] ### System Packages [code example] ## Basic Usage ### Lint a Single Playbook [code example] ### Lint Entire Project [code example] ### List All Available Rules [code example] ### Show Rule Details [code example] ## Configuration File Create `.ansible-lint` in your project root: [code example] ### Profiles Profiles bundle rules by strictness level: | Profile | Description | Use Case | |---------|-------------|----------| | `min` | Bare minimum rules | Legacy projects | | `basic` | Core syntax and logic | Getting started | | `moderate` | + Style and naming | Active development | | `safety` | + Security rules | Security-conscious teams | | `shared` | + Collaboration rules | Shared codebases | | `production` | All rules | Production automation | [code example] ## Key Rules ### Syntax and Logic | Rule | Description | |------|-------------| | `syntax-check` | Playbook fails `ansible-playbook --syntax-check` | | `parser-error` | YAML parsing failures | | `no-changed-when` | Commands/shell without `changed_when` | | `no-handler` | Tasks that should use handlers | | `no-jinja-when` | Jinja2 used ... --- ## ansible-navigator — TUI for Developing and Running Ansible Content URL: https://www.ansiblebyexample.com/articles/ansible-navigator-tui-run-playbooks-ee Description: Complete guide to ansible-navigator — the TUI for running Ansible playbooks in Execution Environments, exploring collections, browsing docs, and replaying. ## Introduction `ansible-navigator` is a text-based user interface (TUI) for running and developing Ansible content. It replaces `ansible-playbook`, `ansible-doc`, `ansible-inventory`, and `ansible-config` with a single tool that runs playbooks inside Execution Environments (container images) — the same way Automation Controller runs them. This means what works in your terminal works identically in production. ## Install [code example] ### Requirements - Python 3.10+ - Container runtime: `podman` (preferred) or `docker` - An Execution Environment image (or uses `ansible-navigator` default EE) ## Quick Start [code example] ## ansible-navigator vs ansible-playbook | Feature | `ansible-playbook` | `ansible-navigator` | |---|---|---| | **Output** | Streaming text | Interactive TUI or stdout | | **Execution** | Local Python env | Inside Execution Environment | | **Replay** | No | Yes — artifact JSON | | **Collection docs** | Separate `ansible-doc` | Built-in `:doc` | | **Inventory explorer** | Separate `ansible-inventory` | Built-in `:inventory` | | **Config viewer** | Separate `ansible-config` | Built-in `:config` | | **EE support** | No (manual) | Native | | **Image explorer** | No | Built-in `:images` | ## Modes ### Interactive Mode (Default) [code example] Launches a TUI with navigable output: - Use **number keys** to drill into plays, tasks, hosts - Press **`:back`** or **Esc** to go up - Press **`:quit`** or **q** to exit - Type **`:help`** for all commands ###... --- ## Ansible: Disable and Lock a Linux User Account URL: https://www.ansiblebyexample.com/articles/disable-user-account-ansible-module-user Description: Disable a Linux user account with Ansible: set password_lock: true and the nologin shell to block all logins — with copy-paste playbook examples. ## How to disable a user account with Ansible? ## Ansible disable user account Today we're talking about the Ansible module `user`. The full name is `ansible.builtin.user`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts. It supports a huge variety of Linux distributions, SunOS and macOS, and FreeBSD. For Windows, use the `ansible.windows.win_user` module instead. ## Parameters - name string - username - state string - present/absent - password_lock boolean - no/yes - shell string - "/sbin/nologin" This module has many parameters to perform any task. The only required is "name", which is the username. The parameter "state" allows us to create or delete a user. The "password_lock" parameter specifies to lock the user password. This parameter uses the `passwd` tool on Linux systems to disables a password by changing it to a value that matches no possible encrypted value (it adds a ´!´ at the beginning of the password). This parameter does not disable the user, only locks the password. This parameter does not always mean the user cannot log in using other methods. The "shell" parameter specifies the user shell. A very special is the `nologin`. When a user with that shell logs in, they'll get a polite message saying 'This account is currently not available.' This message can be customized with the file /etc/nologin.txt. ## Playbook Let's jump into a rea... --- ## Ansible: Fix 'Failed to Import botocore or boto3' for AWS URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-aws-failed-to-import-the-required-python-library-botocore-or-boto3 Description: Learn how to troubleshoot and fix the "Failed to import the required Python library (botocore or boto3)" error in Ansible for AWS with a live Playbook. ## Introduction Today we’re going to talk about Ansible troubleshooting, specifically about the “`Failed to import the required Python library (botocore or boto3)`” message and enable Ansible For AWS. This fatal error message happens when we are trying to execute some code against your AWS EC2 Infrastructure without the necessary Python libraries for the AWS. These circumstances are usually related to the configuration of your Ansible Controller node and usually are not related to Ansible Playbook. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the “Failed to import the required Python library (botocore or boto3)” and how to solve it! In this Playbook, I’m going to reproduce the error and fix using the PIP, the Python Package Manager on a demo machine. ### error execution [code example] ### fix code - python version The first step is to determine your Python version (3.8 in this example): [code example] - before Let’s use the `pip3.8` command because we are running python 3.8. In other Linux distributions, you might need to specify different Python versions. For example Python 3.9 using `pip3.9`, `pip3` or just `pip`. [code example] - fixed with PIP [code example] - after [code example] ### fix execution [code example] ## Conclusion Now you know better how to troubleshoot the Ansible “Failed to import the required Python library (botocore or boto3)” message and move forward with yo... --- ## ansible.builtin.apt — Install Packages on Debian/Ubuntu URL: https://www.ansiblebyexample.com/articles/install-a-package-in-debian-like-systems-ansible-module-apt Description: Install and manage packages with ansible.builtin.apt on Debian/Ubuntu. Full examples for install, upgrade, remove, cache updates, and .deb files. The `ansible.builtin.apt` module manages packages on Debian-based systems — Debian, Ubuntu, Linux Mint, Kali Linux, and other APT-based distributions. It handles installation, removal, upgrades, cache updates, and `.deb` file installation. ## Module Overview - **Full name:** `ansible.builtin.apt` - **Collection:** Built-in (shipped with Ansible) - **Platforms:** Debian, Ubuntu, Linux Mint, Kali Linux, Pop!_OS, and other APT-based systems - **Equivalent for RHEL:** `ansible.builtin.yum` / `ansible.builtin.dnf` ## Key Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `name` | string/list | — | Package name(s) to manage | | `state` | string | `present` | `present`, `absent`, `latest`, `fixed`, `build-dep` | | `update_cache` | bool | `false` | Run `apt-get update` before install | | `cache_valid_time` | int | `0` | Seconds to consider cache valid (skip update if recent) | | `upgrade` | string | `no` | `yes`, `safe`, `full`, `dist` | | `deb` | string | — | Path or URL to a `.deb` file | | `autoremove` | bool | `false` | Remove unused dependencies | | `purge` | bool | `false` | Remove package and config files | | `force_apt_get` | bool | `false` | Force use of `apt-get` instead of `aptitude` | | `install_recommends` | bool | `true` | Install recommended packages | | `default_release` | string | — | Target release (e.g., `bullseye-backports`) | | `dpkg_options` | string | `force-confdef,force-confold` | Options passed to dpkg ... --- ## ansible.builtin.copy: Copy Files to Remote Hosts URL: https://www.ansiblebyexample.com/articles/copy-files-to-remote-hosts-ansible-module-copy Description: Master ansible.builtin.copy to transfer files, set permissions, create backups, validate configs, and copy directories on remote hosts. ## Introduction The `ansible.builtin.copy` module — commonly called the **ansible copy** module — transfers files from the Ansible controller to remote hosts. It handles permissions, ownership, SELinux context, backup, and validation in a single task — making it the standard way to deploy configuration files, scripts, and static content. For the reverse (remote → local), use the fetch module. For Windows targets, use win_copy. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `dest` | path | Yes | Remote absolute path | | `src` | path | No* | Local file or directory path | | `content` | string | No* | Inline content to write (instead of src) | | `mode` | string | No | File permissions (e.g., `'0644'`) | | `owner` | string | No | File owner | | `group` | string | No | File group | | `backup` | bool | No | Create backup before overwriting | | `validate` | string | No | Validation command (`%s` = temp file) | | `remote_src` | bool | No | Copy from remote to remote (not local) | | `force` | bool | No | Replace even if file exists (default: yes) | | `directory_mode` | string | No | Permissions for created directories | | `follow` | bool | No | Follow symlinks on remote | | `checksum` | string | No | Expected SHA1 checksum | *Either `src` or `content` is required when `state: present`. ## Basic Examples ### Copy a File [code example] ### Copy with Inline Content [code example] ### Copy a Directory [code ex... --- ## ansible.builtin.debug — Print Variables and Messages URL: https://www.ansiblebyexample.com/articles/print-text-or-variable-during-execution-ansible-module-debug Description: Print variables, messages, and debug info with ansible.builtin.debug. Use msg, var, and verbosity parameters. Debug registered results and facts. ## What is the Ansible debug Module? The `ansible.builtin.debug` module prints messages, variables, and facts during playbook execution. It's the primary tool for troubleshooting and understanding what your playbook is doing. ## Print a Simple Message [code example] Output: [code example] If you omit `msg`, it defaults to "Hello world!". ## Print a Variable Use `var` to display a variable's full value: [code example] Use `msg` to combine text and variables: [code example] ## Print Registered Output [code example] ## Print Complex Data Structures [code example] ## Print Dictionary Keys and Values [code example] ## Verbosity Levels Control when debug output appears using `verbosity`: [code example] Run with verbosity: [code example] ## Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `msg` | string | "Hello world!" | Message to print (supports Jinja2) | | `var` | string | — | Variable name to display (no `{{ }}` needed) | | `verbosity` | integer | 0 | Minimum verbosity level to show output | **Important:** Don't use `msg` and `var` together — they're mutually exclusive. Use `msg` when you want to format output; use `var` for raw variable inspection. ## Loop with debug [code example] ## Conditional Debug [code example] ## Full Troubleshooting Playbook [code example] ## Common Mistakes [code example] ## Related Articles - Ansible Facts — System information to debug - Ansible set_fact ... --- ## ansible.builtin.file: Create and Manage Files URL: https://www.ansiblebyexample.com/articles/create-an-empty-file-ansible-module-file Description: Learn ansible.builtin.file module: Create empty files with touch, directories, symlinks, and manage permissions and ownership in Ansible playbooks. ## Introduction **ansible.builtin.file** is Ansible's core module for file and directory management. It creates empty files, directories, and symlinks while managing permissions, ownership, and attributes on remote hosts — all with full idempotency. The module combines the functionality of Linux utilities like `touch`, `mkdir`, `chmod`, and `ln` into a single Ansible resource. This guide covers all the ways to use `ansible.builtin.file` for file creation and management. ## Module Reference **Full name:** `ansible.builtin.file` **Collection:** `ansible.builtin` (included with Ansible) ### Key Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | File or directory path (aliases: `dest`, `name`) | | `state` | string | No | `file`, `directory`, `touch`, `link`, `hard`, `absent` | | `mode` | string | No | File permissions (e.g., `'0644'`, `'u+rw,g-wx'`) | | `owner` | string | No | File owner | | `group` | string | No | File group | | `recurse` | bool | No | Recursively set attributes (directories only) | | `modification_time` | string | No | Set modification time (`preserve` or timestamp) | | `access_time` | string | No | Set access time (`preserve` or timestamp) | ### State Values | State | Behavior | |-------|----------| | `touch` | Create file if missing; update timestamps if exists | | `file` | Verify file exists and set attributes (fail if missing) | | `directory` | Create directory (and parent... --- ## ansible.builtin.git Module — Clone via SSH URL: https://www.ansiblebyexample.com/articles/checkout-git-repository-ssh-ansible-module-git Description: Clone Git repositories with Ansible's ansible.builtin.git module over SSH. Configure SSH keys, deploy branches/tags, and handle submodules. ## Introduction The `ansible.builtin.git` module clones and updates Git repositories on remote hosts. Combined with SSH key authentication, it's the standard way to deploy application code, configuration repos, and infrastructure-as-code across server fleets. For HTTPS checkout, see Checkout git repository via HTTPS. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `repo` | string | Yes | Repository URL (SSH or HTTPS) | | `dest` | path | Yes | Destination directory on remote | | `version` | string | No | Branch, tag, or commit SHA (default: `HEAD`) | | `key_file` | path | No | Path to SSH private key on remote host | | `accept_hostkey` | bool | No | Auto-accept unknown SSH host keys | | `update` | bool | No | Pull new revisions if repo exists (default: `true`) | | `force` | bool | No | Discard local changes before updating | | `depth` | int | No | Shallow clone depth (saves bandwidth) | | `recursive` | bool | No | Initialize submodules (default: `true`) | | `single_branch` | bool | No | Clone only the specified branch | | `clone` | bool | No | If `false`, only update existing repo | | `bare` | bool | No | Create a bare repository | ## Basic Clone via SSH [code example] ## SSH Key Setup ### Prerequisites The SSH private key must exist on the **remote host** (not the controller). The corresponding public key must be added to your Git server. ### Deploy SSH Key with Ansible [code example] ### Use Agent... --- ## ansible.builtin.service: Start, Stop, Restart Services URL: https://www.ansiblebyexample.com/articles/ansible-service-module-manage-system-services Description: ansible.builtin.service manages system services: start, stop, restart, reload, and enable at boot. Examples, parameters, troubleshooting tips. ## What Is the ansible service Module? The **ansible service module** (`ansible.builtin.service`) manages system services — start, stop, restart, reload, and enable services for boot. It works across init systems (systemd, SysV, Upstart). For systemd-specific features, use `ansible.builtin.systemd`. Use this module when you want a portable service task that works across Linux init systems; switch to `ansible.builtin.systemd` only when you need systemd-only options such as `daemon_reload`, `masked`, or `scope`. ## Basic Usage [code example] ## Start and Enable at Boot [code example] ## Parameters | Parameter | Description | |-----------|-------------| | `name` | Service name (required) | | `state` | `started`, `stopped`, `restarted`, `reloaded` | | `enabled` | Start at boot: `true`/`false` | | `pattern` | Process name pattern (for SysV init detection) | | `sleep` | Seconds to sleep between stop and start (for restarted) | ## service vs systemd [code example] Use `service` for portability. Use `systemd` when you need `daemon_reload`, `masked`, or `scope`. ## Common Patterns ### Deploy Config and Restart [code example] ### Manage Multiple Services [code example] ### Check Service Status Before Acting [code example] ### Deploy Custom systemd Service [code example] `templates/myapp.service.j2`: [code example] ### Rolling Restart [code example] ### Mask/Unmask Services (systemd) [code example] ## state Behavior | State | Action | |-------|--------| | `sta... --- ## ansible.builtin.stat — Check If File or Directory Exists URL: https://www.ansiblebyexample.com/articles/ansible-check-if-file-directory-exists-stat Description: The ansible.builtin.stat module checks if files, directories, or symlinks exist. Examples: conditional tasks, file properties, size checks, and checksums. ## Introduction Ansible's `stat` module checks whether a file, directory, or symlink exists on remote hosts and returns detailed information about it. Use it to conditionally run tasks based on file existence — install only if a binary is missing, skip config if already deployed, or fail early if a required file isn't found. ## Basic Check: Does a File Exist? [code example] ## Check If Directory Exists [code example] ## Check File Type [code example] ## Common Patterns ### Install Only If Binary Missing [code example] ### Skip If Already Configured [code example] ### Fail If Required File Missing [code example] ### Backup Before Overwriting [code example] ### Check Multiple Files [code example] ## File Properties from stat The `stat` module returns much more than just existence: [code example] ### Check File Size [code example] ### Check File Permissions [code example] ### Compare Checksums [code example] ## stat vs Other Approaches [code example] Use `stat` when you need to **branch logic** based on existence. Use `creates`/`removes` for simple command guards. Use `file`/`copy`/`template` directly when the module is already idempotent. ## Troubleshooting ### "stat.exists is undefined" The `stat` call itself failed (permissions, path syntax error). Check: [code example] ## Related Articles - Ansible file Module — Create Files & Directories - Ansible assert Module - Ansible Create Directory Guide - Ansible when Conditional - Ansible copy Mod... --- ## ansible.builtin.template — Loops and Config File Templates URL: https://www.ansiblebyexample.com/articles/loop-in-file-template-ansible-module-template Description: The ansible.builtin.template module renders Jinja2 templates to remote hosts. Generate config files and /etc/hosts with loops and dynamic variables. ## How to use a loop in a file template to the target host with Ansible? This is extremely useful for service configuration files, placeholder web pages, reports, and so much more use cases. ## Ansible loop in file template - ansible.builtin.template - Template a file out to a target host - ansible_managed, template_host, template_uid, template_path, template_fullpath, template_destpath, and template_run_date Today we're talking about the Ansible module template. The full name is ansible.builtin.template, it's part of `ansible-core` and is included in all Ansible installations. It templates a file out to a target host. Templates are processed by the Jinja2 templating language. Also you could use also some special variables in your templates: `ansible_managed`, `template_host`, `template_uid`, `template_path`, `template_fullpath`, `template_destpath`, and `template_run_date`. It supports a large variety of Operating Systems. For basic text formatting, use the Ansible `ansible.builtin.copy` module or for empty file Ansible `ansible.builtin.file` module. For Windows, use the `ansible.windows.win_template` module instead. ## Parameters - src path - template ("templates/" dir) - dest path - target location - validate string - validation command before ("%s") - backup boolean - no/yes - mode/owner/group - permission - setype/seuser/selevel - SELinux Let me highlight the most useful parameters for the template module. The only required parameters are "src" and "dest". The "src... --- ## ansible.builtin.uri Module - HTTP API Requests URL: https://www.ansiblebyexample.com/articles/ansible-uri-module-http-api-requests Description: The ansible.builtin.uri module lets you make HTTP requests in playbooks: GET, POST, PUT, DELETE, authentication, health checks, and file downloads. ## Introduction `ansible.builtin.uri` makes HTTP requests from your playbooks — call REST APIs, check health endpoints, download files, submit forms, and authenticate with tokens. It's Ansible's equivalent of `curl`. ## Basic Requests [code example] ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `url` | (required) | Request URL | | `method` | `GET` | HTTP method | | `body` | — | Request body | | `body_format` | `raw` | `json`, `form-urlencoded`, `form-multipart`, `raw` | | `headers` | — | Request headers dict | | `status_code` | `200` | Expected status code(s) | | `return_content` | `false` | Include body in response | | `timeout` | `30` | Request timeout (seconds) | | `validate_certs` | `true` | Verify SSL certificates | | `url_username` | — | Basic auth username | | `url_password` | — | Basic auth password | | `force_basic_auth` | `false` | Send auth header preemptively | | `dest` | — | Download to file path | | `creates` | — | Skip if file exists | | `follow_redirects` | `safe` | `all`, `safe`, `none` | ## POST Request (JSON) [code example] ## PUT Request [code example] ## DELETE Request [code example] ## Authentication [code example] ## Download Files [code example] ## Practical Patterns ### Health Check with Retries [code example] ### API Pagination [code example] ### Webhook Notification [code example] ### Deploy with API Calls [code example] ### CRUD Operations [code example] ## Troubleshooting ##... --- ## ansible.builtin.user Module: Manage Linux Accounts URL: https://www.ansiblebyexample.com/articles/ansible-user-module-create-manage-linux-accounts Description: Manage Linux accounts with ansible.builtin.user: create, modify, and delete users; set passwords, groups, SSH keys, home directories, and shells. ## Introduction The `ansible.builtin.user` module manages user accounts on Linux — create users, set passwords, configure groups, manage SSH keys, set shells, and remove accounts. It wraps `useradd`, `usermod`, and `userdel` with idempotent, cross-platform behavior. ## Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `name` | (required) | Username | | `state` | `present` | `present` to create/modify, `absent` to remove | | `uid` | — | User ID number | | `group` | — | Primary group | | `groups` | — | Secondary groups (comma-separated or list) | | `append` | `false` | **Append** to groups (vs replace) | | `shell` | `/bin/bash` | Login shell | | `home` | `/home/` | Home directory path | | `create_home` | `true` | Create home directory | | `password` | — | Hashed password (NOT plaintext!) | | `comment` | — | GECOS field (full name/description) | | `system` | `false` | Create system user (UID < 1000) | | `expires` | — | Account expiry (epoch timestamp) | | `generate_ssh_key` | `false` | Generate SSH keypair | | `ssh_key_bits` | 4096 | SSH key size | | `ssh_key_type` | `rsa` | Key type (rsa, ed25519, ecdsa) | | `remove` | `false` | Remove home dir when `state: absent` | | `force` | `false` | Force removal even if logged in | ## Create a User [code example] ## Set Password ⚠️ Passwords must be **hashed**, not plaintext: [code example] ### update_password Options | Value | Behavior | |-------|----------| | `always` (default) | Set pas... --- ## Ansible.cfg & OpenSSH SCP Deprecation URL: https://www.ansiblebyexample.com/articles/ansible-configuration-file-ansible-cfg-for-openssh-scp-option Description: Learn how to configure ansible.cfg SSH settings for OpenSSH 9.0+ where SCP is deprecated. Complete guide to ssh_connection options, SFTP migration. ## Introduction The `ansible.cfg` file is Ansible's primary configuration file, controlling everything from SSH connection behavior to module paths and output formatting. One of the most impactful recent changes affecting Ansible users is the deprecation of the SCP protocol in OpenSSH 9.0 (shipped with RHEL 9, Ubuntu 22.04+, and Fedora 36+). If your playbooks suddenly fail with file transfer errors after an OS upgrade, this is likely the cause. This guide covers the `ansible.cfg` SSH settings you need to understand, how to handle the SCP deprecation, and best practices for optimal SSH performance. ## ansible.cfg File Locations Ansible searches for configuration in this order (first found wins): 1. `ANSIBLE_CONFIG` environment variable 2. `./ansible.cfg` (current directory) 3. `~/.ansible.cfg` (home directory) 4. `/etc/ansible/ansible.cfg` (global) **Best practice:** Keep `ansible.cfg` in your project directory alongside your playbooks and commit it to version control. [code example] ## The SCP Deprecation in OpenSSH 9.0 ### What Changed Starting with OpenSSH 9.0 (RHEL 9, Ubuntu 22.04+): - The `scp` command now uses **SFTP protocol** internally by default - The legacy SCP protocol can be restored with the `-O` flag - Future OpenSSH releases will remove SCP protocol support entirely ### Impact on Ansible Ansible uses file transfer for modules, facts, and the `copy`/`fetch`/`template` modules. If your `ansible.cfg` explicitly set `transfer_method = scp`, file transf... --- ## Ansible.cfg Configuration — Guide URL: https://www.ansiblebyexample.com/articles/ansible-cfg Description: Configure ansible.cfg for your environment. Settings for SSH, inventory, roles_path, callback plugins, and performance tuning with examples. The `ansible.cfg` file is a crucial component in the Ansible ecosystem, providing a centralized configuration point to customize the behavior of Ansible. This article explores the structure, key sections, and settings of the `ansible.cfg` file, and provides best practices for its usage. ## What is ansible.cfg? The `ansible.cfg` file is an INI-like configuration file used to define various settings and parameters that influence how Ansible operates. This file can be placed in different locations, with Ansible searching for it in the following order of precedence: 1. ANSIBLE_CONFIG environment variable (if set) 2. `ansible.cfg` file in the current working directory 3. `.ansible.cfg` file in the user’s home directory 4. `/etc/ansible/ansible.cfg` file (global configuration) Each of these configuration files can override the settings specified in the others, with the highest precedence being given to the environment variable. ## Structure of ansible.cfg The `ansible.cfg` file is divided into sections, each containing various parameters that can be customized. Here are some of the key sections and their important settings: 1. **[defaults]** This section contains the default settings for Ansible, including the inventory file location, remote user, and module path. [code example] 2. **[privilege_escalation]** This section manages settings for privilege escalation, such as `sudo`. [code example] 3. **[ssh_connection]** This section contains settings related to... --- ## ansible.mysql Collection 5.0 — MySQL Automation Guide URL: https://www.ansiblebyexample.com/articles/ansible-mysql-collection-5-0-mysql-automation-guide Description: Use the ansible.mysql collection 5.0 to manage MySQL databases, users, replication, and queries. Covers migration from community.mysql and new features. # ansible.mysql Collection 5.0 — MySQL Automation Guide ## Introduction The `ansible.mysql` collection version 5.0.0 is the official successor to `community.mysql`, which has been sunset. All MySQL automation in Ansible now uses `ansible.mysql`. This guide covers installation, migration from `community.mysql`, and practical examples for every key module. ## Installation [code example] ## Migration from community.mysql The `community.mysql` collection 4.2.1 is the **last release**. All future development happens in `ansible.mysql`. [code example] ### Bulk Migration [code example] ## Managing Databases [code example] ## Managing Users and Privileges [code example] ## Running Queries [code example] ## Replication Setup [code example] ## MySQL Variables [code example] ## Module Reference | Module | Purpose | |--------|---------| | `ansible.mysql.mysql_db` | Create, drop, import, dump databases | | `ansible.mysql.mysql_user` | Manage users and privileges | | `ansible.mysql.mysql_query` | Execute SQL queries | | `ansible.mysql.mysql_replication` | Configure replication | | `ansible.mysql.mysql_variables` | Get/set server variables | | `ansible.mysql.mysql_info` | Gather server information | | `ansible.mysql.mysql_role` | Manage MySQL roles (8.0+) | ## Troubleshooting | Issue | Solution | |-------|----------| | `No module named pymysql` | Install: `pip install PyMySQL` | | Access denied | Check `login_user`, `login_password`, and `host` | | `community.mysql` n... --- ## ansible.posix 2.2.2 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-posix-2-2-2-released-whats-new-and-how-to-test Description: ansible.posix 2.2.2 is out, a minor release fixing the README contact information for Red Hat Automation Hub subscribers. # ansible.posix 2.2.2 Released - Whats New and How to Test ## Introduction `ansible.posix` is the collection that bundles POSIX-specific modules and plugins for Ansible, covering things like `mount`, `firewalld`, `selinux`, `sysctl`, `synchronize`, `at`, `authorized_key`, and the `profile_tasks`/`profile_roles` callback plugins commonly used to profile playbook execution. It is one of the collections shipped by default with the `ansible` community package, and version 2.2.2 has just been published to Ansible Galaxy. ## Whats New Version 2.2.2 is a minor release. Compared to 2.2.1, there are no functional changes to any module or plugin code in this release: no new modules, no new parameters, no behavioral bugfixes to `mount`, `firewalld`, `selinux`, `sysctl`, `synchronize`, or any of the other modules in the collection. The only change in the changelog is a documentation fix in the `README`. ### Bugfixes - README - Added `Red Hat Automation Hub` as the correct contact information for Red Hat Ansible Automation Platform (AAP) subscribers. In practice, this means the `README.md` shipped with the collection now points AAP customers to Automation Hub as the correct support/contact channel, instead of whatever reference was there before. If a user is not consuming this collection through Red Hat Automation Hub, this release has no practical impact and can be treated as a no-op update. ## How to Test Since this release only touches documentation, testing is limited to con... --- ## Ansible.Windows 3.8.0 - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/ansible-windows-3-8-0-whats-new-and-how-to-test Description: ansible.windows 3.8.0 adds win_reboot_info module, diff support in win_copy, retry logic in win_updates, and fixes a win_copy destination bug. # Ansible.Windows 3.8.0 - Whats New and How to Test ## Introduction `ansible.windows` is the Ansible Content Collection that ships the core modules and plugins used to manage Windows hosts over WinRM (and PSRP), including file operations, service management, updates, and the `win_*` family of modules that most Windows-focused playbooks depend on. Version 3.8.0 has just been published to Ansible Galaxy and introduces a new module, two minor feature additions, and one bugfix. This is the first tracked release for this collection on ansiblebyexample.com, so there is no direct comparison against a previous known version, but the changelog for this exact release is detailed below. ## Whats New ### New Modules - `win_reboot_info` - a new module that retrieves reboot status information for a Windows host. This is useful for checking pending reboot state (e.g. after patching or feature installation) without having to shell out to registry checks manually. ### Minor Changes - `win_copy` - diff support has been added when copying single files. Running with `--diff` will now show the actual file differences for single-file copy operations performed by `win_copy` and `win_template`. Copying multiple files at once still does not produce diff output. See issue #16. - `win_updates` - a new `maximum_retries_on_failed_updates` option has been added to control how many attempts the module makes at installing an update that has been rolled back. This addresses issue #762, where a single ... --- ## API Validation with Postman URL: https://www.ansiblebyexample.com/articles/api-validation-with-postman Description: Learn efficient API validation, error handling, and performance optimization with the hands-on Coursera course 'API Validation with Postman' by Luca. ## Introduction In the digital age, reliable APIs are the backbone of seamless user experiences. Ensuring their performance, security, and reliability is crucial. **"API Validation with Postman"**, a Coursera course taught by **Luca Berton**, equips you with the tools and techniques needed to validate, test, and optimize APIs effectively. From schema validation to error handling and performance optimization, this course provides a hands-on approach to mastering API testing using Postman. {{}} ## Why Learn API Validation? API validation goes beyond just ensuring correct responses; it ensures: - **Reliability**: Robust APIs that perform well under various conditions. - **Data Integrity**: Secure and accurate data exchanges between systems. - **Error Management**: Quick identification and resolution of issues to minimize downtime. Whether you're a developer, QA engineer, or IT professional, mastering API validation enhances your ability to deliver high-performing, reliable, and secure applications. ## Course Overview This intermediate-level course is designed for learners with basic knowledge of HTTP usage, authentication, and API concepts. Familiarity with API methods like GET, POST, PUT, and DELETE will help you maximize your learning experience. Over two flexible hours, you'll gain practical insights into optimizing API performance and ensuring their reliability using Postman. ## Learning Objectives Participants in this course will: - **Apply efficient API validation... --- ## ARA Records Ansible — Reporting URL: https://www.ansiblebyexample.com/articles/ara-records-ansible-for-ansible-reporting Description: Install and configure ARA Records Ansible to track playbook runs, audit changes, and troubleshoot failures via a web dashboard. Setup guide with examples. *Original post: https://blog.while-true-do.io/spotlight-ara-records-ansible/* ## Introduction Are you an avid Ansible user? Do you find yourself utilizing Ansible in pipelines or collaborating across teams? If so, tracking changes and keeping tabs on your last runs might be a priority. Enter ARA, a powerful tool that records Ansible activities and provides a comprehensive overview. In this article, we’ll delve into ARA, exploring how this tool can elevate your Ansible experience. ### Ansible Overview Ansible stands as an open-source automation software designed for tasks ranging from small-scale use cases to managing entire cloud ecosystems. Using minimal YAML configurations, you can automate processes such as package installations, network configurations, or even Kubernetes deployments on platforms like AWS. ### ARA — ARA Records Ansible ARA steps in as an Ansible reporting solution, capturing ansible and ansible-playbook commands regardless of their execution location or method. Achieving this functionality involves integrating a simple callback plugin into your existing content. ### Reasons to Use ARA Let’s take a closer look at ARA and understand its potential benefits. The first question that may arise is, “Why should I use ARA?” While ARA isn’t mandatory for running Ansible or enhancing playbook performance, it provides transparency into the execution process. ARA proves invaluable for: - Compliance Audits - Change Management - CI/CD Tracking (e.g., GitOps) - Self-... --- ## Assign Memory to Kubernetes Pods with Ansible URL: https://www.ansiblebyexample.com/articles/assign-memory-resources-to-kubernetes-k8s-or-openshift-ocp-containers-and-pods-ansible-module-k8s Description: Learn how to assign memory resources to Kubernetes or OpenShift containers and pods using Ansible. Follow our live Playbook and simple code examples. ## How to Assign Memory Resources to Kubernetes K8s or OpenShift OCP Containers and Pods with Ansible? I’m going to show you a live Playbook and some simple Ansible code. Containers cannot use more Memory than the configured limit. Provided the system has Memory time free, a container is guaranteed to be allocated as much Memory as it requests. To specify a Memory request for a container, include the `resources:requests` field in the Container resource manifest. To specify a Memory limit, include `resources:limits`. ## Ansible creates Kubernetes or OpenShift service - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - `name` _string_ /namespace _string_ - object name / namespace - `api_version` _string_ - "v1" - `kind` _string_ - object model - `state` _string_ - present/absent/patched - `definition` _string_ - YAML definition - `src` _path_ - path for YAML definition - `template` _raw_ - YAML template definition - `validate` _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object ... --- ## Automate Ansible Collection Testing with GitHub Actions URL: https://www.ansiblebyexample.com/articles/automating-collection-testing-in-github Description: Set up GitHub Actions CI/CD for Ansible collections — automated lint, sanity, unit, and integration tests on every PR. Complete workflow configuration. ## Introduction Automated testing is essential for maintaining quality in Ansible collections. GitHub Actions provides native CI/CD that runs lint checks, sanity tests, unit tests, and integration tests on every pull request — catching issues before they reach `main`. This article covers the complete workflow setup using the `ansible-network/github_actions` reusable workflows, custom test configurations, and best practices for collection CI/CD. ## Quick Start: Minimal Workflow Create `.github/workflows/test.yml` in your collection repository: [code example] ## Understanding Each Job ### ansible-lint Runs `ansible-lint` against the collection to catch: - YAML syntax issues - Deprecated module usage - Missing FQCN (Fully Qualified Collection Names) - Task naming violations - Jinja2 best practices ### changelog Validates changelog fragments exist for PRs. Ansible collections use `changelogs/fragments/` with YAML files: [code example] ### sanity Runs `ansible-test sanity` which checks: - Python import validation - Documentation formatting - GPL license headers - PEP 8 compliance - YAML syntax - Proper module documentation - Return value documentation ### unit-galaxy Runs unit tests from `tests/unit/` using `ansible-test units`: [code example] ### integration Runs integration tests from `tests/integration/targets/`: [code example] [code example] ### all_green A gate job that ensures all other jobs passed before the PR can be merged. Uses Python assertion to ... --- ## Automate CLI Interactions in Ansible with the expect Module URL: https://www.ansiblebyexample.com/articles/automating-command-line-interfaces-with-ansible-expect-module Description: Use the Ansible expect module to automate interactive CLI prompts. Complete guide with pexpect setup, password prompts, multiple responses, timeout. ## Introduction Some commands require interactive user input — password prompts, confirmation dialogs, setup wizards. Ansible's `expect` module automates these interactions by sending predefined responses to expected prompts, eliminating the need for manual intervention during playbook execution. This guide covers everything from basic setup to advanced patterns including multiple prompts, timeout handling, and security considerations. ## Prerequisites The `expect` module requires the `pexpect` Python library (version 3.3+) on the **control node**: [code example] Or install it as part of your playbook: [code example] Verify the installation: [code example] ## Basic Usage The `expect` module takes a `command` to run and a dictionary of `responses` mapping expected prompts (as regex patterns) to the text to send: [code example] ### Module Parameters | Parameter | Required | Default | Description | |-----------|----------|---------|-------------| | `command` | Yes | — | The command to execute | | `responses` | Yes | — | Dict of prompt regex → response mappings | | `timeout` | No | 30 | Seconds to wait for each prompt | | `echo` | No | false | Whether to echo the command output | | `chdir` | No | — | Directory to run the command in | | `creates` | No | — | Skip if this file exists | | `removes` | No | — | Skip unless this file exists | ## Practical Examples ### Automating SSH Key Generation [code example] ### Database Setup Wizard [code example] ### Interactiv... --- ## Automate Dell EMC DNOS 10 Backups with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/backup-config-on-dell-emc-networking-operating-system-dnos-10-ansible-network-dellemc-os10 Description: Learn to automate the backup of Dell EMC DNOS 10 configurations with Ansible. This guide includes a practical Playbook example and setup instructions for. ## How to Backup Config on Dell EMC Networking Operating System DNOS 10 with Ansible? Maintaining a backup copy of your network appliance configuration is a good practice for all IT professionals. You could automate this process for Dell EMC network appliances using Ansible. ## Ansible Backup Config on DNOS 10 > `dellemc.os10.os10_config`: Manage Dell EMC OS10 configuration sections Let's talk about the Ansible module `os10_config`. The full name is `dellemc.os10.os10_config`, which means that is part of the collection `dellemc.os10` specialized in the module to interact with Ansible Network Collection for Dell EMC OS10. This collection requires ansible-core version 2.10+. It manages Dell EMC OS10 configuration sections. ## Parameters - backup boolean - no/yes - backup_options dictionary - configurable options related to a backup file path - dir_path path - If the directory does not exist it will be first created - filename string - `\\_config.\@\` Let me summarize the parameter of `os10_config` module for the backup use-case. The `backup` boolean enables the backup mode of the configuration. Once enabled you could specify some `backup_options`. I suggest you specify the `dir_path`, the directory where to save backups, and the `filename` if you have a specific one. Otherwise, Ansible is going to create a file with the current timestamp. ## Links - Dell OS10 Platform Options - dellemc.os10.os10_config - os10_config backup option not working #113 ## Demo How to Backup ... --- ## Automate EC2 Creation with Ansible: YAML Playbook Demo URL: https://www.ansiblebyexample.com/articles/ansible-playbook-for-automating-ec2-ubuntu-instance-creation-and-host-data-collection-on-aws Description: Explore an Ansible playbook for creating EC2 instances on AWS. Learn to use ec2_ami_info, ec2_instance, set_fact, and shell modules in a live Playbook. ## Introduction This is an Ansible playbook written in YAML format that automates the creation of Amazon Elastic Compute Cloud (EC2) instances and collects the host data. The playbook has three tasks: 1. The first task, named “find ami,” uses the `amazon.aws.ec2_ami_info` module to find an Amazon Machine Image (AMI) based on the specified filters and store the result in the `ec2_ami_facts_result` variable. 2. The second task, named “instances,” uses the `amazon.aws.ec2_instance` module to create EC2 instances based on the specified parameters, including the AMI ID obtained from the previous task. It loops through a list of instances defined in the `aws_instances` variable, and stores the output in the `aws_ec2_instance_output` variable. 3. The third task, named “collect host data”, uses the `ansible.builtin.set_fact` module to extract the relevant data from the `aws_ec2_instance_output` variable and stores it in the `aws_ec2_instance_data` variable. 4. The fourth task, named “fetch host keys”, uses the `ansible.builtin.shell` module to run a command that retrieves the host keys from the instances. It loops through the instances in the `aws_ec2_instance_data` variable and stores the output in the `aws_ec2_host_keys` variable. It will keep retrying the command until it gets non-empty output or exceeds the maximum number of retries specified. The output will be discarded as it's not registered in a variable. ## Links - `amazon.aws.ec2_ami_info` - amazon.aws.ec2_instance ##... --- ## Automate Oracle Cloud Infrastructure with Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/automate-oracle-cloud-infrastructure-with-ansible-playbooks Description: Learn how to automate Oracle Cloud Infrastructure with Ansible, from setup to creating and managing compute instance pools. ## Introduction In today's IT landscape, the automation of cloud infrastructure has become a pivotal aspect of managing scalable, reliable, and efficient systems. Oracle Cloud Infrastructure (OCI) is one such platform that benefits greatly from automation. This article will guide you through creating a compute instance pool and launching instances in OCI using Ansible, providing a detailed example and best practices. ## Understanding Ansible Ansible is an open-source automation tool that simplifies the management of complex IT environments. It uses a human-readable language, YAML, to describe automation jobs, known as playbooks. Ansible is agentless, using SSH or WinRM for communication, making it a secure and efficient choice for IT automation. ### Key Features of Ansible 1. **Human-Readable Automation**: Uses YAML for playbooks, making it easy to read and write. 2. **Agentless Architecture**: Requires no agents on the managed nodes, reducing overhead and security risks. 3. **Cross-Platform Support**: Works with Linux, Windows, UNIX, and network devices. 4. **Extensible**: Can be extended with modules and plugins written in any language. ## Setting Up the Environment Before diving into the playbook, ensure you have the following prerequisites: 1. **Ansible Installed**: Ensure Ansible is installed on your control node. You can install it using pip: [code example] 2. **OCI CLI Configured**: Configure the OCI CLI on your control node. Follow the OCI CLI installation ... --- ## Automate PostgreSQL Backups with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/backup-a-postgresql-database-ansible-module-postgresql-db Description: Discover how to automate PostgreSQL database backups with Ansible. This guide includes a live Playbook example and detailed execution steps for. ## How to Backup a PostgreSQL Database with Ansible? I’m going to show you a live Playbook with some simple Ansible code. ## Ansible Backup a PostgreSQL Database > `community.postgresql.postgresql_db`: Add or remove PostgreSQL databases from a remote host Let’s talk about the Ansible module postgresql_db. The full name is `community.postgresql.postgresql_db`, which means that is part of the collection of modules “`community.postgresql`” maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to add or remove PostgreSQL databases from a remote host. ## Parameters - `name` _string_ — name of database - `state` _string_ — `present`/`absent`/`dump`/`restore`/`rename` — the operation - `target` - file name Let me summarize the main parameters of the module postgresql_db. Ansible supposes that PostgreSQL is in the target node. The only required parameter is `name`, the name of the database to interact with. The parameter “`state`” specifies the desired state or the operation for the selected database. The option “present” means that the database should be created and the option `absent` means that the database should be deleted. Other useful operations are `dump` and `restore` which use `pg_dump`, the embedded PostgreSQL utility to backup and restore to the target file. Another useful operation is `rename`, from name to target... --- ## Automate Redmine Installation on Ubuntu LTS 22.04 with Ansible URL: https://www.ansiblebyexample.com/articles/automate-redmine-installation-on-ubuntu-lts-22-04-with-ansible Description: Learn how to automate the installation of Redmine on Ubuntu 22.04 LTS using Ansible, ensuring a consistent and efficient deployment process for your. ## Introduction Welcome to a comprehensive guide on automating the installation of Redmine on Ubuntu LTS 22.04 using Ansible. In today’s rapidly evolving technological landscape, streamlining the deployment process of essential software like Redmine has become a priority for efficient project management and collaboration. Redmine, a versatile and widely-used project management tool, facilitates tasks ranging from issue tracking to time tracking, all within a unified platform. This guide delves into the integration of Ansible, a powerful automation tool, to orchestrate the installation of Redmine on Ubuntu LTS 22.04. Ansible eliminates the manual complexities of software deployment by providing a clear, repeatable, and automated solution. By following this tutorial, you’ll harness the capabilities of Ansible to expedite the installation process, ensuring consistency and accuracy across multiple instances. Whether you’re a seasoned DevOps professional seeking to optimize deployment workflows or an IT enthusiast eager to explore the realms of automation, this guide will equip you with the knowledge and steps needed to effortlessly set up Redmine on the latest Ubuntu LTS release. Let’s embark on this journey to enhance your project management efficiency through seamless and automated deployment. ## Links - https://www.redmineup.com/pages/help/installation/installing-redmine-on-ubuntu-20-04 ## Step by Step The following Ansible playbook for Redmine installation on Ubuntu 22.0... --- ## Automate Tasks with Ansible: Execute Actions at 10:55 URL: https://www.ansiblebyexample.com/articles/automating-tasks-with-ansible-scheduled-execution-at-specific-time Description: Learn how to automate scheduled tasks in Ansible. This guide demonstrates executing a playbook at 10:55, including time calculations and waiting. ## Introduction In IT infrastructure management, automation is a key component that empowers administrators to streamline repetitive tasks and ensure consistent operations. Ansible, a popular open-source automation tool, offers extensive capabilities for orchestrating tasks across a wide range of systems. One intriguing aspect of Ansible is its ability to execute tasks at specific times, enabling administrators to schedule actions with precision. This article will explore a practical example of how Ansible can execute tasks at a predetermined time, specifically at 10:55. ### The Power of Scheduled Execution Imagine a scenario where a system administrator needs to perform a task on a fleet of servers every day at exactly 10:55. This task might involve updating configurations, performing backups, or any other action necessary to maintain system health and security. Manually executing such tasks can be time-consuming, error-prone, and disruptive, especially in a large-scale environment. Ansible addresses this challenge by allowing administrators to define and schedule tasks for execution at specific times. This reduces the required manual effort and ensures consistency and accuracy in task execution. ## Links - https://docs.ansible.com/ansible/latest/collections/ansible/builtin/wait_for_module.html - https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html ## Understanding the Playbook To Playbooknstrate scheduled execution with Ansible, we will walk ... --- ## Automating Butt Plugin Configuration and Management with Ansible URL: https://www.ansiblebyexample.com/articles/automating-butt-plugin-configuration-and-management-with-ansible Description: Discover how to set up and manage the Butt plugin for seamless audio streaming. Automate configurations and updates with Ansible for efficiency. The **Butt plugin** (Broadcast Using This Tool) is a versatile and widely-used plugin for audio streaming and recording. Whether you're setting up a live broadcast or managing multiple recording systems, automating the configuration of the Butt plugin with **Ansible** can save time and ensure consistency across systems. --- ## What is the Butt Plugin? The **Butt plugin** is an open-source tool designed for streaming audio to online servers and recording locally. It is commonly used for: - **Live Broadcasting**: Stream audio to platforms like Icecast or Shoutcast. - **Audio Recording**: Save high-quality audio files locally for future use. - **Cross-Platform Compatibility**: Available on Windows, macOS, and Linux. When paired with **Ansible**, the Butt plugin setup and management process becomes streamlined, ensuring a consistent configuration across multiple systems. --- ## Why Use Ansible for Butt Plugin Management? - **Automation**: Automate repetitive setup tasks, including installation and configuration. - **Scalability**: Deploy the Butt plugin across multiple devices efficiently. - **Consistency**: Apply uniform settings, such as server configurations and recording options. - **Error Reduction**: Eliminate manual mistakes during setup and updates. --- ## Setting Up the Butt Plugin ### Manual Steps 1. **Download the Plugin**: - Visit the official website and download the plugin for your operating system. 2. **Install Dependencies**: - Ensure required lib... --- ## Automating Data Transformation with Ansible: Converting Dictionaries to Lists URL: https://www.ansiblebyexample.com/articles/data-transformation-with-ansible-converting-dictionaries-to-lists Description: Explore how to automate data transformations in Ansible by converting dictionary-based structures into lists using Jinja2 filters. Simplify data handling. ## Introduction When working with Ansible, automating data manipulation is crucial for dynamic and scalable playbooks. A common scenario involves converting a list of dictionaries into a simple list for further processing. In this guide, we’ll explore how to achieve this transformation effectively using Jinja2 filters in Ansible. ## Problem Statement You may encounter a data structure like this: [code example] Your goal is to extract the values of the `name` key into a simple list: [code example] Let’s explore the solution step by step. ## Ansible Solution with Jinja2 Filters Ansible’s Jinja2 templating engine provides powerful filters like `map` and `list` to simplify this task. ### Example Playbook Here’s a playbook to convert the given data structure into a list: [code example] ### Explanation of Filters 1. **`map(attribute='name')`**: Extracts the value of the `name` key from each dictionary in the list. 2. **`| list`**: Converts the resulting generator into a proper list. ### Debugging Output The debug task will display the extracted list: [code example] ## Handling Common Errors ### Error: "Invalid data passed to loop" If Ansible complains about invalid data, the issue may lie in how the data is interpreted. Use these additional filters to ensure the data is processed correctly: [code example] This serialization-deserialization process guarantees the data is treated as a list. ## Conclusion Transforming data structures in Ansible is straightforward with... --- ## Automating depmod with Ansible URL: https://www.ansiblebyexample.com/articles/automating-depmod-with-ansible Description: Learn how to automate the depmod command using Ansible for streamlined kernel module management. Tested on real machines with clear, copy-paste examples. ## Automating `depmod` Command with Ansible The `depmod` command in Linux is critical for generating module dependency information, stored in `/lib/modules//modules.dep`. This command is particularly useful when managing custom kernel modules or after installing new modules. Automating `depmod` with Ansible ensures consistency, reduces human error, and improves overall efficiency. --- ### Why Automate `depmod` with Ansible? 1. **Consistency**: Guarantees all systems have updated module dependencies. 2. **Speed**: Saves time by automating repetitive tasks during updates or module installations. 3. **Error Reduction**: Eliminates manual mistakes, such as forgetting to run `depmod` after kernel updates. 4. **Scalability**: Manages multiple systems simultaneously using a single playbook. --- ## What is `depmod`? The `depmod` command analyzes kernel modules and generates dependency files used by `modprobe` and the kernel to automatically load required modules. Common use cases include: - Installing a new kernel. - Adding or removing kernel modules. - Customizing module configurations. --- ## Ansible Playbook for Automating `depmod` Here’s how to automate `depmod` using Ansible: [code example] ### Explanation: - **`hosts: all`**: Specifies that the playbook applies to all hosts in the inventory. - **`become: true`**: Ensures the `depmod` command runs with elevated privileges. - **`ansible.builtin.shell`**: Executes the `depmod` command. - **`register`**: Captures the o... --- ## Automating Distributed File System Replication (DFSR) with Ansible URL: https://www.ansiblebyexample.com/articles/automating-distributed-file-system-replication-dfsr Description: Discover how to set up and automate Distributed File System Replication (DFSR) with Ansible. Ensure reliable, scalable file synchronization. **Distributed File System Replication (DFSR)** is a powerful feature that ensures files are synchronized across multiple servers in a network. Paired with **Ansible automation**, DFSR becomes even more effective, enabling IT administrators to efficiently manage and deploy replication configurations across systems. --- ## What is Distributed File System Replication (DFSR)? **DFSR** is a feature in Microsoft Windows Server that replicates files between servers in a Distributed File System (DFS). It ensures: - **Data Consistency**: Synchronizes files across multiple locations. - **High Availability**: Provides redundant copies of data to ensure access in case of server failure. - **Efficient Bandwidth Use**: Uses Remote Differential Compression (RDC) to replicate only changed portions of a file. When combined with Ansible, DFSR setup and management can be automated, reducing manual effort and ensuring consistent configurations. --- ## Why Use Ansible for DFSR Automation? - **Time Savings**: Automate repetitive tasks such as adding replication members or monitoring synchronization status. - **Scalability**: Configure DFSR on multiple servers simultaneously. - **Consistency**: Ensure replication settings are uniform across your environment. - **Error Reduction**: Minimize configuration mistakes with reliable playbooks. --- ## Setting Up Distributed File System Replication (DFSR) ### Manual Steps 1. **Install DFS Management Tools**: - On Windows Server, use Server Mana... --- ## Automating Dynamic Time Date Facts with Ansible URL: https://www.ansiblebyexample.com/articles/automating-dynamic-time-date-facts-with-ansible Description: Learn how to work with dates, timestamps, and time formatting in Ansible playbooks using set_fact, now(), ansible_date_time, and strftime filters with. ## Introduction Working with dates and timestamps is essential in Ansible automation. Whether you're creating timestamped backup directories, naming log files, setting file expiration dates, or adding deployment timestamps, Ansible provides several methods to capture and format dates dynamically during playbook execution. This guide covers all the ways to work with dates and times in Ansible — from the built-in `ansible_date_time` facts to the `now()` function, `strftime` filter, and `pipe` lookup. ## Method 1: ansible_date_time Facts The simplest way to access the current date and time is through Ansible's gathered facts. When `gather_facts: true` (the default), Ansible automatically collects date/time information: [code example] This provides a dictionary with these fields: | Field | Example | Description | |-------|---------|-------------| | `date` | `2024-02-26` | Current date (YYYY-MM-DD) | | `time` | `14:30:45` | Current time (HH:MM:SS) | | `epoch` | `1708958445` | Unix timestamp | | `iso8601` | `2024-02-26T14:30:45Z` | ISO 8601 format | | `iso8601_basic` | `20240226T143045` | Compact ISO format | | `year` | `2024` | Four-digit year | | `month` | `02` | Two-digit month | | `day` | `26` | Two-digit day | | `hour` | `14` | Two-digit hour (24h) | | `minute` | `30` | Two-digit minute | | `second` | `45` | Two-digit second | | `weekday` | `Monday` | Day of the week | | `tz` | `UTC` | Timezone abbreviation | **Important:** `ansible_date_time` is captured once at the s... --- ## Automating File Extension Validation with Ansible URL: https://www.ansiblebyexample.com/articles/automating-file-extension-validation-with-ansible Description: Learn how to structure an Ansible playbook to validate file extensions, ensuring files end with specified formats like .csv or .txt through practical. ## Introduction In the age of automation, managing file integrity across diverse environments is crucial for ensuring data consistency and security. Ansible, a powerful IT automation tool, offers an efficient way to automate tasks and ensure that files meet specified criteria, such as having correct file extensions. This article presents a detailed guide on using Ansible to validate file extensions within a system. ### Understanding the Playbook Structure The given Ansible playbook is designed to validate file extensions to ensure that each file ends with specified formats (e.g., `.csv` or `.txt`). Here’s a breakdown of the playbook's components: [code example] ### Key Components Explained 1. **Hosts**: The playbook targets `localhost`, meaning it runs on the local machine. This setup is ideal for scripts that manage local files or perform tests without affecting remote systems. 2. **Variables**: The `my_dicts` variable is a list of dictionaries, each representing a file with a `file_name` key. This structure is flexible and can be expanded to include more files or metadata as needed. 3. **Tasks**: - **Check file extensions**: This task utilizes the `assert` module, which checks conditions and fails if the conditions are not met. The condition here ensures each file name matches the regex pattern `'.*\.(csv|txt)$'`, confirming it ends with `.csv` or `.txt`. - **Loop**: The playbook iterates over each filename extracted from `my_dicts`, applying the validatio... --- ## Automating File Reading with Ansible URL: https://www.ansiblebyexample.com/articles/automating-file-reading-with-ansible Description: Automate reading and displaying text files in a directory with Ansible using find, slurp, and debug modules to manage file content effortlessly. ## Introduction Automation is key in modern IT infrastructure management. Ansible, a powerful automation tool, makes it easy to manage complex environments. One of the many tasks you can automate with Ansible is reading content from multiple files. This article will guide you through a simple playbook that reads content from text files within a specified directory and displays the content. ## Understanding the Playbook The provided playbook is designed to run on the local host and performs the following tasks: 1. **List all text files in the specified directory and its subdirectories**. 2. **Read the content from each text file**. 3. **Display the content of the files**. Let's break down each section of the playbook to understand how it works. ### Listing Files in a Directory First, we use the `ansible.builtin.find` module to list all text files in the specified directory (`/path/to/your/directory`). The `recurse: yes` option ensures that the search includes subdirectories. [code example] The results are stored in a variable called `files_list`. ### Reading Content from Each File Next, we initialize an empty list to store the file contents using `ansible.builtin.set_fact`. [code example] We then use a loop to iterate over each file in `files_list.files`. The `ansible.builtin.slurp` module reads the content of each file and stores it in the `slurped_files` variable. The `loop_control` ensures we use a custom loop variable `item_info`. [code example] ### Displayin... --- ## Automating Jenkins Installation with Ansible URL: https://www.ansiblebyexample.com/articles/automating-jenkins-installation-with-ansible Description: Automate Jenkins installation effortlessly with Ansible. This playbook guides through installing Java, adding Jenkins repository, and configuring. ## Introduction In the rapidly evolving world of software development, Continuous Integration/Continuous Deployment (CI/CD) has become a cornerstone of modern DevOps practices. Jenkins, one of the most popular open-source automation servers, facilitates CI/CD by automating the build, test, and deployment phases of the software development process. However, setting up Jenkins can be a repetitive and time-consuming task, which is where Ansible, an automation tool for configuration management, comes into play. This article provides a step-by-step guide on how to automate the installation and initial setup of Jenkins on a server using Ansible, making it a reproducible and error-free process. ### Prerequisites Before we dive into the Ansible playbook, ensure you have the following prerequisites met: - An Ansible control node configured to manage your servers. - A target server, which we refer to as `jenkins_server` in our inventory. - The target server must be running a Debian-based operating system since the playbook uses `apt` for package management. ## The Ansible Playbook for Jenkins Installation An Ansible playbook is a blueprint of automation tasks, which are executed in the order they are defined. The playbook we are discussing is composed of a series of tasks to install Java, add the Jenkins repository, install Jenkins, and ensure the service is running. ### Step 1: Installing Java Jenkins is a Java-based application, so the first task in our playbook installs Java... --- ## Automating Key Management with Ansible Using ansible.utils.remove_keys URL: https://www.ansiblebyexample.com/articles/key-management-with-ansible-using-remove-keys-utility Description: Master Ansible's remove_keys utility to remove keys dynamically using regex patterns in playbooks for efficient data management and automation. ## Introduction In automation workflows, efficient data manipulation plays a crucial role, especially when managing sensitive data or cleaning structured inputs. Ansible, known for its simplicity and flexibility, offers utilities to handle such scenarios. One such utility is `ansible.utils.remove_keys`, a Python method used to remove keys from a dictionary based on specified criteria, such as matching patterns. This article dives into the utility's usage, focusing on the `target` and `matching_parameter` arguments, and demonstrates its practical application with an Ansible playbook. ## Understanding `ansible.utils.remove_keys` The `ansible.utils.remove_keys` method provides a systematic way to delete dictionary keys. Key arguments include: - **`target`**: A regular expression (regex) pattern defining which keys to target for removal. - **`matching_parameter`**: Defines how the matching is determined. For regex-based matching, this value is `"regex"`. For example: [code example] This removes keys named `"note"` from the given dictionary. ## Why Use `ansible.utils.remove_keys`? - **Data Cleaning**: Useful when cleaning unwanted metadata or temporary data. - **Enhanced Security**: Prevents accidental propagation of sensitive information. - **Flexibility**: Allows dynamic targeting of keys using regex patterns. --- ## Playbook Demonstration Below is a simple playbook leveraging the `ansible.utils.remove_keys` utility: [code example] ### Explanation of the Playbook 1. **... --- ## Automating PostgreSQL Configuration with Ansible Setting Maximum Connections URL: https://www.ansiblebyexample.com/articles/automating-postgresql-configuration-with-ansible-setting-maximum-connections Description: Learn how to use Ansible lineinfile module to configure PostgreSQL max_connections and other settings. Complete guide with playbooks for tuning. ## Introduction PostgreSQL is one of the most popular open-source relational databases, powering applications from small startups to enterprise platforms. As your application scales, tuning PostgreSQL configuration becomes critical for performance. The `max_connections` setting is one of the first parameters administrators need to adjust — and automating this with Ansible ensures consistency across your entire database fleet. This guide shows how to automate PostgreSQL configuration changes using Ansible's `lineinfile` module, covering `max_connections` and other essential tuning parameters. ## Why Automate PostgreSQL Configuration? Manually editing `postgresql.conf` across multiple servers is: - **Error-prone** — typos can crash PostgreSQL - **Inconsistent** — settings drift between servers over time - **Slow** — editing files on 10+ servers takes significant time - **Unauditable** — no record of who changed what and when Ansible solves all of these problems by defining configuration as code. ## Basic Playbook: Setting max_connections The simplest playbook to set `max_connections`: [code example] Key points: - The `regexp` matches both commented (`#max_connections`) and uncommented lines - The handler restarts PostgreSQL only when the configuration actually changes - Using a variable for the config path supports different PostgreSQL versions ## Understanding max_connections The `max_connections` parameter controls how many simultaneous client connections PostgreS... --- ## Automating SSL/TLS Certificate Rotation in AKS URL: https://www.ansiblebyexample.com/articles/automating-ssl-tls-certificate-rotation-in-aks Description: Learn how to automate SSL/TLS certificate rotation in Azure Kubernetes Service (AKS) using Cert-Manager and custom scripts for seamless security. ## Introduction A **Custom Resource Definition (CRD)** in Kubernetes allows you to extend the Kubernetes API by defining your own custom resources. These custom resources can represent any kind of domain-specific entity, and you can manage them using standard Kubernetes tools like `kubectl`. ### Overview of Custom Resource Definitions (CRDs) - **Custom Resources:** These are extensions of the Kubernetes API. They allow you to create your own custom resource types that can be managed like built-in resources (e.g., Pods, Services). - **Custom Resource Definitions (CRDs):** These are used to define the schema and behavior of custom resources. Once a CRD is created, you can create instances of the custom resource it defines. ### Steps to Create and Use a Custom Resource Definition #### Step 1: Define the Custom Resource Definition (CRD) The CRD defines the structure and behavior of your custom resource. Here is an example of a simple CRD for a custom resource called `MyApp`. [code example] ### Explanation: - **`apiVersion`**: The API version for CRDs is `apiextensions.k8s.io/v1`. - **`kind`**: This is `CustomResourceDefinition` since you are defining a new custom resource. - **`metadata.name`**: The name of the CRD should be in the form of `plural.group`. In this case, it's `myapps.example.com`. - **`spec.group`**: The API group your custom resource belongs to. In this case, it's `example.com`. - **`spec.versions`**: The different versions of your custom resource. Each ve... --- ## Automating VMware Tag Verification with Ansible URL: https://www.ansiblebyexample.com/articles/vmware-tag-verification-with-ansible Description: Leverage Ansible to efficiently manage and verify VMware cluster tags, identifying critical metadata for streamlined resource management. ## Introduction Efficient resource management in VMware environments requires robust tools and streamlined practices. Tags are essential metadata that help categorize and organize resources like clusters, enabling administrators to maintain control over complex infrastructures. Ansible, a powerful automation tool, simplifies the process of retrieving and verifying VMware cluster tags. This article demonstrates how to automate tag verification using Ansible, with a focus on identifying and displaying the `category_name` and `name` attributes of cluster tags. --- ## 1. Why Automate VMware Tag Management? Tags in VMware are indispensable for managing large-scale environments, providing metadata that defines a resource's purpose, ownership, or environment (e.g., production or staging). Automating tag verification ensures: - **Consistency**: Every resource adheres to predefined tagging policies. - **Scalability**: Easily manage tags across numerous clusters. - **Efficiency**: Save time and minimize human error in tag inspections. --- ## 2. Ansible: The Key to VMware Automation Ansible provides an agentless and straightforward approach to managing VMware environments. With the `community.vmware` collection, administrators can seamlessly interact with VMware vCenter and automate tag-related tasks. ### Installing the `community.vmware` Collection Before running the playbook, install the required collection: [code example] --- ## 3. The Playbook: Verifying `category_name` in... --- ## Automating Windows Installations with Ansible for IT Efficiency URL: https://www.ansiblebyexample.com/articles/automating-windows-installations-with-ansible-for-it-efficiency Description: Simplify Windows installations with Ansible. Automate deployments, configurations, and updates to save time and reduce manual errors in IT environments. Installing **Windows operating systems** across multiple devices is a time-consuming task that can be streamlined significantly with **Ansible automation**. By automating Windows installations, IT teams can save time, reduce manual errors, and ensure consistent configurations across their infrastructure. --- ## Why Automate Windows Installations? - **Time Efficiency**: Automate repetitive tasks, such as partitioning disks and configuring settings. - **Consistency**: Ensure uniform configurations across all deployed systems. - **Scalability**: Deploy Windows to multiple devices simultaneously. - **Error Reduction**: Eliminate manual errors by using pre-defined playbooks. --- ## How to Automate Windows Installations with Ansible ### Manual Steps for Windows Installation 1. **Prepare Installation Media**: - Use the Media Creation Tool to create a bootable USB drive or ISO file. 2. **Partition Disk**: - Configure disk partitions using the Windows setup wizard. 3. **Install Windows**: - Follow the installation prompts to complete the process. 4. **Configure System**: - Set up user accounts, network settings, and system updates manually. --- ### Automating with Ansible #### Example Playbook for Preparing Windows Installation This playbook downloads the Windows ISO file and creates bootable installation media. [code example] --- #### Example Playbook for Installing Windows Using a Pre-Configured Answer File Use an answer file to automate Windows setup. [c... --- ## AWX vs Ansible Tower vs AAP — Detailed Comparison URL: https://www.ansiblebyexample.com/articles/awx-vs-ansible-tower-vs-aap-detailed-comparison Description: Compare AWX, Ansible Tower, and Automation Platform: features, licensing, and migration paths. Tested, copy-paste examples included. # AWX vs Ansible Tower vs AAP — Detailed Comparison ## Introduction Compare AWX, Ansible Tower, and Automation Platform: features, licensing, and migration paths. This comprehensive guide helps you make informed decisions and implement effectively. ## Overview [code example] ## Key Concepts ### When to Choose This Approach | Factor | Consideration | |--------|--------------| | Team size | Small teams benefit from simplicity | | Existing tools | Integrate with current stack | | Scale | Consider automation volume | | Compliance | Regulatory requirements | | Budget | Open source vs commercial | ## Practical Implementation [code example] ## Best Practices 1. **Start simple** — add complexity only when needed 2. **Automate incrementally** — don't try to automate everything at once 3. **Test thoroughly** — use Molecule and check mode 4. **Document decisions** — future team members will thank you 5. **Version control** — commit everything to git 6. **Security first** — use Vault, limit access, audit actions ## Common Mistakes | Mistake | Impact | Fix | |---------|--------|-----| | Over-engineering | Complexity, maintenance burden | KISS principle | | No testing | Broken deployments | Molecule + CI/CD | | Hardcoded values | Environment lock-in | Variables + Vault | | No documentation | Knowledge silos | README + comments | ## Conclusion Compare AWX, Ansible Tower, and Automation Platform: features, licensing, and migration paths. Start with the fundamentals, implement ... --- ## Backup Ansible Automation Platform — Complete Guide URL: https://www.ansiblebyexample.com/articles/backup-ansible-automation-platform Description: Complete guide to backing up and restoring Ansible Automation Platform. Use setup.sh for full platform backups including Controller, Hub, EDA. ## Introduction The Ansible Automation Platform installer includes built-in backup and restore capabilities. A single `setup.sh -b` command creates a complete backup of the Automation Controller, Private Automation Hub, Event-Driven Ansible Controller, and the PostgreSQL database — everything you need to recover from failures or migrate to new infrastructure. ## Prerequisites - Root access on the AAP installer host - The original `setup.sh` installer and `inventory` file - Sufficient disk space for the backup tarball - Same AAP version for backup and restore (version must match) ## Backup Commands ### Full Platform Backup [code example] This creates a tarball in the current directory: [code example] A symlink `automation-platform-backup-latest` always points to the most recent backup. ### Backup to Custom Location [code example] ### What's Included in the Backup | Component | Data Backed Up | |-----------|---------------| | **Automation Controller** | Jobs, inventories, credentials, projects, schedules, RBAC | | **Automation Hub** | Collections, namespaces, container images, signing keys | | **EDA Controller** | Rulebooks, activations, event sources | | **PostgreSQL** | Full database dump | | **SECRET_KEY** | Encryption key for credentials | | **Custom configs** | Manual projects, custom settings files | ## Restore Commands ### Restore from Default Location [code example] This restores from the `automation-platform-backup-latest` symlink. ### Restore from Sp... --- ## Backup Dell EMC DNOS 6 Configs with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/backup-config-on-dell-emc-networking-operating-system-dnos-6-ansible-network-dellemc-os6 Description: Discover how to automate Dell EMC DNOS 6 configuration backups with Ansible. This guide includes a Playbook example and setup instructions for efficient. ## How to Backup Config on Dell EMC Networking Operating System DNOS 6 with Ansible? Maintaining a backup copy of your network appliance configuration is a good practice for all IT professionals. You could automate this process for Dell EMC network appliances using Ansible. ## Ansible Backup Config on DNOS 6 - dellemc.os6.os6_config - Manage Dell EMC OS6 configuration sections Let's talk about the Ansible module `os6_config`. The full name is `dellemc.os6.os6_config`, which means that is part of the collection `dellemc.os6` specialized in the module to interact with Ansible Network Collection for Dell EMC OS6. This collection requires ansible-core version 2.10+. It manages Dell EMC OS6 configuration sections. ## Parameters - backup boolean - no/yes - backup_options dictionary - configurable options related to a backup file path - dir_path path - If the directory does not exist it will be first created - filename string - \\_config.\@\ Let me summarize the parameter of `os6_config` module for the backup use-case. The `backup` boolean enables the backup mode of the configuration. Once enabled you could specify some `backup_options`. I suggest you specify the `dir_path`, the directory where to save backups, and the `filename` if you have a specific one. Otherwise, Ansible is going to create a file with the current timestamp. ## Links - Dell OS6 Platform Options - dellemc.os6.os6_config module ## Demo How to Backup Config on Dell Networking Operating System 6 with Ansib... --- ## Bard-ing with Ansible: Streamlining Testing for Google's AI Writing Tool URL: https://www.ansiblebyexample.com/articles/google-bard-and-ansible Description: Effortlessly Enhancing Productivity and Accuracy with Ansible for Bard, Google's Cutting-edge Writing AI. With tested, real-world examples. ## Google Bard Google Bard is the newest Chat-style Artificial Intelligence created by Google based on the Google Language Model for Dialogue Applications (or LaMDA for short). It's the closest competitor ofOpenAI ChatGPT. ## Links - An important next step on our AI journey https://blog.google/technology/ai/bard-google-ai-search-updates/ ## Four Challenges I decided to judge the quality of the AI using the following four challenges: 1. How to Pass Variables to Ansible Playbook in the command line? - Ansible extra variables 2. Configure a Windows Host for Ansible - Ansible winrm 3. Using Date, Time, and Timestamp in Ansible Playbook - Ansible Tip and Tricks 4. Change user password - Ansible module user ## Challenge 1 - How to Pass Variables to Ansible Playbook in the command line? - Ansible extra variables Score: Good ## Challenge 2 - Configure a Windows Host for Ansible - Ansible winrm Score: Bad ## Challenge 3 - Using Date, Time, and Timestamp in Ansible Playbook - Ansible Tip and Tricks Score: Good ## Challenge 4 - Change user password - Ansible module user Score: Good ## Conclusion Google Bard is a great companion that speeds up prototyping and boosts out productivity. I'm impressed by the quality of the result. They appear good-looking and well-organized. However, at the moment, the outcome is still in the early stage and requires some manual rework before being able to actually use in our laboratory. The challenges saw that it is excellent for minor p... --- ## Book Presentation: Red Hat Ansible Automation Platform by Luca Berton URL: https://www.ansiblebyexample.com/articles/presentation-of-the-book-red-hat-ansible-automation-platform-by-luca-berton Description: Modernize your organization with automation and Infrastructure as Code in Luca Berton book, "Red Hat Ansible Automation Platform." # Book Presentation: Red Hat Ansible Automation Platform by Luca Berton ## Introduction Book Presentation: Red Hat Ansible Automation Platform by Luca Berton. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Book Presentation: Red Hat Ansible Automation Platform by Luca Berton requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbook... --- ## Break Strings Across Lines in YAML and Ansible URL: https://www.ansiblebyexample.com/articles/break-a-string-over-multiple-lines-ansible-literal-and-folded-block-scalar-operators Description: Learn to use YAML "|" and ">" operators for breaking strings into multiple lines in Ansible. Explore practical examples and playbook implementations. ## How to Break a string over multiple lines with Ansible? And in general with YAML language. ## Ansible Break a string over multiple lines Today we're talking about Ansible Break a string over multiple lines: Basically, there are two different operators: - the "|" - Literal Block Scalar" - the ">" Folded Block Scalar" It's easy for me to show you the behavior by example. To break a string over multiple lines in Ansible, you can use the following operators: - Literal Block Scalar (|): This operator tells Ansible to treat the string as a literal block scalar. This means that Ansible will preserve the newlines in the string. For example, the following code will create a variable called `my_variable` that contains the following string: [code example] - Folded Block Scalar (>): This operator tells Ansible to treat the string as a folded block scalar. This means that Ansible will collapse all of the newlines in the string into a single space. For example, the following code will create a variable called `my_variable` that contains the following string: [code example] The main difference between the Literal Block Scalar and the Folded Block Scalar operators is that the Literal Block Scalar operator will preserve the newlines in the string, while the Folded Block Scalar operator will collapse all of the newlines in the string into a single space. ## Examples #### variable1 code [code example] #### variable1 output [code example] #### variable2 code [code example] ####... --- ## Browser in a Browser Proxy with Ansible Automation URL: https://www.ansiblebyexample.com/articles/browser-in-a-browser-proxy-with-ansible-automation Description: Discover how to use browser-in-a-browser proxies for secure browsing and automate their configuration and management with Ansible. A **browser in a browser proxy** offers an innovative way to secure online browsing by encapsulating a browser session within another, effectively isolating sensitive activities. When paired with **Ansible automation**, managing and configuring these proxies becomes seamless and efficient, ensuring secure and consistent performance. --- ## What is a Browser in a Browser Proxy? A **browser in a browser proxy** is a configuration that runs a browser session within another browser or isolated environment. This setup provides: - **Enhanced Security**: Isolates browsing sessions to prevent malicious exploits. - **Proxy Integration**: Ensures privacy by routing traffic through a proxy server. - **Controlled Access**: Limits external interaction with sensitive environments. With **Ansible**, you can automate the setup and configuration of these proxies, reducing manual effort and ensuring secure, consistent deployments. --- ## Why Use Ansible with Browser in a Browser Proxies? - **Automation**: Simplify repetitive tasks like proxy configuration or environment setup. - **Consistency**: Ensure identical settings across multiple systems or browsers. - **Scalability**: Deploy configurations to large numbers of devices with minimal effort. - **Security**: Automate security protocols and ensure compliance. --- ## How to Set Up a Browser in a Browser Proxy ### Manual Steps 1. **Install a Browser with Proxy Support**: - Download a browser that supports advanced proxy settings, ... --- ## Build Ansible AWX in Docker — Development Setup Guide URL: https://www.ansiblebyexample.com/articles/build-ansible-awx-in-docker-containers-ansible-awx Description: Build and run Ansible AWX from source in Docker containers. Development environment setup with make, docker-compose, and UI customization. ## How to build Ansible AWX in Docker containers? AWX is the Open Source upstream project of the Ansible Automation Controller, included in the Ansible Automation Platform (formerly Ansible Tower). Running in Docker containers to use the modern web-UI and API interface. Running in Docker containers is recommended only for experienced users and developers. ## Ansible AWX Ansible AWX supports only the x86_64 operating system: - Fedora (maintained versions) - Ubuntu LTS (20.04 or 22.04) - Red Hat Enterprise Linux 8+, CentOS Stream 8+ - macOS 11 Ansible AWX is the upstream project of Ansible Automation Controller (formerly Ansible Tower), providing a modern web-UI and API interface to manage Ansible Playbooks, inventories, Credentials, and Vaults between your team in your organization. Running AWX in local Docker containers allows you to test the AWX web-UI and API to manage Ansible Playbook execution easily. AWX run on Docker is considered for Testing or Development only; the preferred way is via the AWX Operator since version 18.0. This initial configuration sometimes is a roadblock for some Ansible AWX users. ## Links - Installing AWX ## Playbook How to Build Ansible AWX in Docker containers. I’m going to show you how to build the latest Ansible AWX in the latest Fedora using Docker containers and the latest receptor image. The additional software must be installed: - OpenSSL library - Ansible - Docker Please note that the latest Docker technology should be inst... --- ## Build Ansible Execution Environment URL: https://www.ansiblebyexample.com/articles/build-an-ansible-execution-environment-ansible-builder-command-line-tool Description: Learn how to build a custom Ansible Execution Environment using the ansible-builder tool. Manage system, Python, and collection dependencies effectively. ## How to build a custom Ansible Execution Environment? Using an Ansible Execution Environment is the latest technology to maintain up-to-date Python dependency of the Ansible collections without interfering with your Linux system. It's the evolution of Python Virtual Environment. This initial configuration sometimes is a roadblock for some Ansible users. ## Ansible Execution Environment - Ansible Execution Environment - `ansible-builder` command-line tool - `ansible-runner` command-line tool Let's talk about the Ansible Execution Environment. The Ansible Execution Environment is container images that can be utilized as Ansible control nodes. It's the latest technology developed by Red Hat to simplify the automation process. The main advantage is a standard environment for Development and Production images using container technology creating portable automation runtimes. This technology superseded manual Python Virtual Environments, Ansible module dependencies, and bubblewrap. Experienced users are probably familiar with a lot of challenges managing custom Python Virtual Environments and Ansible module dependencies. Enterprise users of Ansible Automation Platform were familiar with limiting execution jobs under bubblewrap in order to isolate processes The creation is performed by the Ansible Builder tool. Ansible Builder produces a directory that acts as the build context for the container image build, containing the `Containerfile`, along with any other files that need to... --- ## Build Ansible Pilot Community: Ansible Anwendertreffen 2022 URL: https://www.ansiblebyexample.com/articles/15-02-2022-from-zero-to-hero-how-to-build-the-ansible-pilot-community-ansible-anwendertreffe Description: Save the date! Join Luca Berton on February 15, 2022, at Ansible Anwendertreffen for insights on building the Ansible Pilot Community. Register for the. ## TL;DR: From Zero to Hero: How to build the Ansible Pilot Community - Ansible Anwendertreffen 15 February 2022 conference {{}} Save the date! On **15th February 2022** I'll be the speaker on the 3rd edition of Ansible Anwendertreffen (virtual) conference. - 15:15 - 16:00 CET timezone - From Zero to Hero: How to build the Ansible Pilot Community - by Luca Berton (Red Hat CZ) - The full program of the conference and register. Save the date! On 15th February 2022! I’ll be the speaker at the 3rd edition of the Ansible Anwendertreffen (virtual) conference. The presentation title is “From Zero to Hero: How to build the Ansible Pilot Community” — by Luca Berton. ## Save the date: 15 Feb 2022 Ansible Anwendertreffen🇩🇪 - Ansible Anwendertreffen — 3rd edition — 15 Feb 2022 - **15:15 – 16:00** CET timezone From Zero to Hero: How to build the Ansible Pilot Community by Luca Berton - Focus on Ansible Users - Ansible Anwendertreffen🇩🇪 What is Ansible Anwendertreffen? It’s a very nice meeting place, especially for the German speakers' Ansible users! Danke schön 🇩🇪 Wir sehen uns dort. Prost! My German is bad, apologies. The conference started three years ago by two fellow Red Hat Solution Architects aim to support the day-to-day Ansible Users, real use case, not a marketing event! The event is public, free, and probably interesting for many Developers, System Administrator, DevOps, Cloud Engineers. Hurry up and register on the Ansible Anwendertreffen🇩🇪 website. I’ll be one ... --- ## Can Ansible Automate Windows? URL: https://www.ansiblebyexample.com/articles/can-ansible-automate-windows Description: Learn how Ansible can automate Windows systems, its requirements, supported modules, and use cases for streamlining Windows administration tasks. Ansible is well-known for its ability to automate Linux systems, but it is equally capable of managing and automating **Windows systems**. Its agentless architecture and extensive module library make Ansible a powerful tool for streamlining Windows administration tasks. This article explores how Ansible can automate Windows systems, its requirements, and use cases. ## Can Ansible Automate Windows? Yes, Ansible can automate Windows systems by leveraging **Windows Remote Management (WinRM)** or **SSH**. With support for Windows-specific modules, Ansible can perform tasks such as software deployment, configuration management, and service orchestration on Windows environments. ### Key Features: - **Agentless Architecture**: No need for additional agents; uses WinRM or SSH. - **Windows Modules**: A rich library of modules tailored for Windows automation. - **Cross-Platform Management**: Manage Windows alongside Linux and other platforms. ## Prerequisites for Automating Windows with Ansible ### 1. Enable WinRM WinRM is the default communication protocol for Ansible to interact with Windows systems. To enable WinRM: 1. Open PowerShell as Administrator. 2. Run the following commands: [code example] ### 2. Install pywinrm The **pywinrm** Python library is required for Ansible to communicate with Windows systems over WinRM: [code example] ### 3. Configure the Inventory File Add your Windows systems to the inventory file with appropriate credentials: [code example] ## Common ... --- ## Can Ansible Be Used for Deployment? URL: https://www.ansiblebyexample.com/articles/can-ansible-be-used-for-deployment Description: Learn how Ansible can be used for application deployment, its capabilities, and best practices for automating deployment workflows. Ansible is a powerful tool that can be used for application deployment, making it a valuable asset in DevOps workflows. Its ability to automate repetitive tasks and ensure consistency across environments simplifies the deployment process. This article explores how Ansible can be used for deployments, its capabilities, and best practices for managing deployment workflows. ## Can Ansible Be Used for Deployment? Yes, Ansible can be used for application deployment. Its agentless architecture and modular design allow you to automate the entire deployment pipeline, from provisioning infrastructure to configuring and deploying applications. ### Key Features: - **Idempotency**: Ensures deployments are repeatable and consistent. - **Cross-Platform Support**: Manage deployments across Linux, Windows, and cloud environments. - **Integration**: Works seamlessly with CI/CD pipelines and external tools. ## Use Cases for Deployment with Ansible 1. **Web Application Deployment**: Deploy web applications, configure servers, and manage dependencies. 2. **Container Deployment**: Manage Docker containers and Kubernetes clusters. 3. **Database Deployment**: Automate database schema updates and migrations. 4. **Multi-Tier Applications**: Deploy multi-tier architectures with load balancers, web servers, and databases. 5. **Cloud-Native Applications**: Automate deployments to AWS, Azure, Google Cloud, or other cloud providers. ## Example Ansible Playbooks for Deployment ###... --- ## Can Ansible Be Used for Monitoring? URL: https://www.ansiblebyexample.com/articles/can-ansible-be-used-for-monitoring Description: Explore how Ansible can be used to automate monitoring setups, deploy monitoring tools, and collect system metrics for infrastructure management. Ansible is widely recognized for its configuration management and automation capabilities, but can it be used for monitoring? While Ansible is not a dedicated monitoring tool, it excels at **automating the deployment and configuration of monitoring systems** and collecting system metrics. This article explores how Ansible can be used for monitoring setups, its capabilities, and use cases. ## Can Ansible Be Used for Monitoring? Yes, Ansible can automate monitoring tasks such as deploying monitoring tools, configuring agents, and collecting metrics. However, it does not provide real-time monitoring or alerting capabilities like dedicated tools (e.g., Nagios, Zabbix, or Prometheus). Instead, Ansible complements monitoring workflows by automating the setup and management of monitoring infrastructure. ### Key Capabilities: - **Automated Deployment**: Deploy monitoring agents and servers. - **Configuration Management**: Standardize monitoring configurations across systems. - **Data Collection**: Use Ansible to gather system metrics periodically. ## Use Cases for Ansible in Monitoring ### 1. Deploying Monitoring Tools Ansible can deploy and configure popular monitoring tools like Prometheus, Grafana, Zabbix, or Nagios. #### Example: Deploying Prometheus [code example] ### 2. Installing Monitoring Agents Deploy and configure monitoring agents like Telegraf, Node Exporter, or Datadog on target hosts. #### Example: Installing Node Exporter [code example] ### 3. Configuring Mon... --- ## Can Ansible Create VMs? URL: https://www.ansiblebyexample.com/articles/can-ansible-create-vms Description: Learn how Ansible can create virtual machines in cloud and on-premises environments, including examples and best practices. Ansible is a powerful tool for automating IT operations, including the creation of virtual machines (VMs) in cloud and on-premises environments. This article explores how Ansible can create VMs, its integration with virtualization platforms, and examples of playbooks for automating VM provisioning. ## Can Ansible Create VMs? Yes, Ansible can create virtual machines by interacting with virtualization platforms and cloud providers. Using platform-specific modules and collections, Ansible automates the provisioning of VMs, from defining configurations to deploying operating systems and managing resources. ## Supported Platforms for VM Creation Ansible integrates with a variety of platforms to create VMs: 1. **Cloud Providers**: - **AWS**: Use the `amazon.aws.ec2_instance` module. - **Azure**: Use the `azure.azcollection.azure_rm_virtualmachine` module. - **Google Cloud**: Use the `google.cloud.gcp_compute_instance` module. 2. **On-Premises Virtualization**: - **VMware**: Use the `vmware.vmware_guest` module. - **KVM/Libvirt**: Use the `community.libvirt.virt` module. - **Hyper-V**: Use the `ansible.windows.win_hyperv_vm` module. 3. **Containerized Environments**: - Automate virtualized containers with tools like Kubernetes and Docker. ## Examples of Creating VMs with Ansible ### 1. Creating an EC2 Instance on AWS [code example] ### 2. Creating a Virtual Machine on VMware [code example] ### 3. Creating a VM on KVM/Libvirt [code example] ### 4. Cre... --- ## Can Ansible Install an OS? URL: https://www.ansiblebyexample.com/articles/can-ansible-install-an-os Description: Use Ansible to automate OS installation with PXE boot, Kickstart, Preseed, and cloud-init. Bare-metal provisioning and VM deployment patterns. Ansible is widely used for configuration management and application deployment, but can it install an operating system? The answer is **partially**. While Ansible itself cannot directly perform OS installation on bare-metal systems, it can assist with **automated OS deployments** in certain scenarios, particularly in virtualized or cloud environments. This article explores how Ansible fits into the OS installation process. ## Can Ansible Install an OS? Ansible cannot directly install an operating system on bare-metal systems, as OS installation typically requires bootstrapping from ISO images or PXE boot. However, Ansible can: 1. **Automate OS Provisioning** in virtualized or cloud environments. 2. **Configure Systems Post-Installation** using playbooks. 3. **Integrate with Tools** like PXE boot, Kickstart, and cloud-init for streamlined deployment. ## Scenarios Where Ansible Can Help ### 1. Automating OS Deployment in Virtual Environments Ansible can provision virtual machines or cloud instances with a pre-installed operating system using modules for cloud providers and hypervisors: - **Cloud Examples**: - AWS: Use the `amazon.aws.ec2_instance` module to launch instances with a specified OS image. - Azure: Use the `azure.azcollection.azure_rm_virtualmachine` module. - **VMware Examples**: - Use the `vmware.vmware_guest` module to create VMs with predefined OS templates. Example Playbook for AWS EC2: [code example] ### 2. Configuring Systems Post-Installation Ans... --- ## Can Ansible Manage Windows Hosts? URL: https://www.ansiblebyexample.com/articles/can-ansible-manage-windows-hosts Description: Learn how Ansible manages Windows hosts, its requirements, and use cases for automating tasks on Windows systems. With tested, real-world examples. Ansible is known for its versatility in managing Linux systems, but can it manage Windows hosts? The answer is **yes**. Ansible provides robust support for automating Windows systems using **Windows Remote Management (WinRM)** or SSH. This article explains how to manage Windows hosts with Ansible, its prerequisites, and common use cases. ## Can Ansible Manage Windows Hosts? Yes, Ansible can effectively manage Windows hosts. By leveraging WinRM, Ansible communicates with Windows systems to perform configuration management, software deployment, and other administrative tasks. ### Key Features: - **Agentless Architecture**: Ansible uses WinRM or SSH to manage Windows systems without requiring additional software. - **Rich Module Support**: Ansible provides Windows-specific modules for tasks like service management, file operations, and user management. - **Seamless Integration**: Manage both Linux and Windows hosts from a single control node. ## Prerequisites for Managing Windows Hosts with Ansible ### 1. Enable WinRM on Windows Hosts WinRM is the primary communication protocol for managing Windows hosts with Ansible. To enable it: 1. Open PowerShell as Administrator. 2. Run the following commands: [code example] ### 2. Install pywinrm on the Control Node The **pywinrm** Python library is required for Ansible to communicate with Windows hosts: [code example] ### 3. Configure the Inventory File Add the Windows host to your inventory file: [code example] ## Common Ansi... --- ## Can Ansible Manage Windows? URL: https://www.ansiblebyexample.com/articles/can-ansible-manage-windows Description: Discover how Ansible manages Windows systems, its requirements, and the modules available for automation tasks. With clear, copy-paste, step-by-step examples. Ansible is a powerful tool for automating tasks across various platforms, including **Windows systems**. While it’s widely known for managing Linux, Ansible’s support for Windows enables seamless cross-platform automation. This article explains how Ansible can manage Windows, the prerequisites, and use cases. ## Can Ansible Manage Windows? Yes, Ansible can manage Windows systems using **WinRM (Windows Remote Management)** or **SSH**. With its agentless architecture, Ansible performs tasks like software deployment, configuration management, and system updates on Windows nodes. ## Prerequisites for Managing Windows with Ansible ### 1. Enable WinRM on Windows Hosts WinRM allows Ansible to communicate with Windows machines remotely. #### Steps to Enable WinRM: 1. Open PowerShell as Administrator. 2. Run the following commands: [code example] ### 2. Install pywinrm on the Ansible Control Node Install the **pywinrm** library to enable WinRM communication: [code example] ### 3. Configure Inventory for Windows Define the Windows hosts in your inventory file: [code example] ## Ansible Modules for Windows Automation Ansible provides several modules specifically for managing Windows systems. Here are some commonly used ones: ### 1. **win_service**: Manage Windows services. [code example] ### 2. **win_package**: Install or uninstall software. [code example] ### 3. **win_user**: Manage user accounts. [code example] ### 4. **win_file**: Manage files and... --- ## Can Ansible Replace Terraform? URL: https://www.ansiblebyexample.com/articles/can-ansible-replace-terraform Description: Understand the differences between Ansible and Terraform, and whether Ansible can fully replace Terraform in managing infrastructure. Ansible and Terraform are two of the most popular tools in the DevOps ecosystem. While they share similarities as Infrastructure as Code (IaC) tools, they serve different purposes. This article explores whether **Ansible** can fully replace **Terraform** and the scenarios in which they complement each other. ## Can Ansible Replace Terraform? The short answer is: **No, Ansible cannot completely replace Terraform**, because their core objectives and strengths differ. However, the decision to use one or both tools depends on your specific automation needs. ### Core Differences Between Ansible and Terraform | Feature | Ansible | Terraform | |------------------------|----------------------------------------|----------------------------------------| | **Primary Purpose** | Configuration management and orchestration | Infrastructure provisioning | | **Language** | YAML | HCL (HashiCorp Configuration Language) | | **Execution** | Push-based | Declarative, state-driven | | **State Management** | Stateless | Maintains infrastructure state | | **Target Systems** | Applications, servers, and networks | Cloud infrastructure and resources | ## What Terraform Excels At 1. **Infrastructure Provisioning**: Terraform is purpose-built for creating, modifyin... --- ## Can Ansible Run on Ubuntu? URL: https://www.ansiblebyexample.com/articles/can-ansible-run-on-ubuntu Description: Discover how to install and use Ansible on Ubuntu for automating infrastructure and application tasks with ease. With clear, copy-paste, step-by-step examples. Ansible is a widely used automation tool that runs seamlessly on Ubuntu, making it an excellent choice for managing infrastructure and applications. This article explores how to install and use Ansible on Ubuntu to simplify automation workflows. ## Can Ansible Run on Ubuntu? Yes, Ansible runs perfectly on Ubuntu, both as a **control node** (where Ansible is installed and executed) and as a **managed node** (where Ansible performs tasks). Its compatibility with Ubuntu's package management system and extensive module library ensures efficient automation on Ubuntu systems. ### Key Features: - **Native Support**: Available in Ubuntu’s default repositories. - **Cross-Platform Management**: Manage Ubuntu alongside other operating systems. - **Rich Module Library**: Includes modules tailored for Ubuntu-based tasks. ## Installing Ansible on Ubuntu ### Step 1: Update the System Ensure your Ubuntu system is up-to-date: [code example] ### Step 2: Add the Ansible PPA (Optional) To get the latest Ansible version, add the official Ansible PPA: [code example] ### Step 3: Install Ansible Install Ansible using the `apt` package manager: [code example] ### Step 4: Verify the Installation Check the installed Ansible version: [code example] ### Step 5: Configure the Inventory File The default inventory file is located at `/etc/ansible/hosts`. Add your managed nodes: [code example] ## Running Ansible Playbooks on Ubuntu ### Example: Updating Packages Create a playbook to update all pac... --- ## Can Ansible Run on Windows? URL: https://www.ansiblebyexample.com/articles/can-ansible-run-on-windows Description: Explore whether Ansible can run on Windows, its requirements, and how to configure Ansible on a Windows machine for automation workflows. Ansible is widely recognized for its ability to manage Linux systems, but can it run on Windows? The short answer is **yes, with certain configurations**. This article explores how Ansible works on Windows, its requirements, and how to set it up for automation workflows. ## Can Ansible Run on Windows? Ansible is primarily designed to run on Linux-based control nodes. However, with tools like the **Windows Subsystem for Linux (WSL)** or a virtual machine, it can run effectively on a Windows system. Ansible can also manage Windows target nodes directly using protocols like WinRM. ### Key Points: - Ansible **cannot run natively** on Windows as a control node. - Use **WSL** or a virtual machine for running Ansible on Windows systems. - Ansible can manage Windows systems as target nodes. ## Setting Up Ansible on Windows Using WSL Windows Subsystem for Linux (WSL) enables you to run a Linux environment directly on a Windows machine. Follow these steps to set up Ansible on Windows using WSL: ### 1. Install WSL 1. Open PowerShell as Administrator. 2. Run the following command to install WSL: [code example] 3. Restart your system if prompted. ### 2. Install a Linux Distribution After installing WSL, choose a Linux distribution (e.g., Ubuntu) from the Microsoft Store. ### 3. Update and Install Ansible 1. Open the installed Linux distribution. 2. Update the package manager: [code example] 3. Install Ansible: [code example] ### 4. Verify Ansible Installation Run the fo... --- ## Can Ansible Run PowerShell Scripts? URL: https://www.ansiblebyexample.com/articles/can-ansible-run-powershell-scripts Description: Learn how Ansible can run PowerShell scripts on Windows systems, including setup requirements, examples, and best practices. Ansible is a versatile automation tool capable of managing Windows systems, including the execution of **PowerShell scripts**. This article explains how Ansible can run PowerShell scripts, its requirements, and best practices for integrating PowerShell into your automation workflows. ## Can Ansible Run PowerShell Scripts? Yes, Ansible can run PowerShell scripts on Windows systems. Using the **`win_shell`** and **`win_command`** modules, you can execute inline PowerShell commands or external PowerShell script files on target Windows hosts. ## Prerequisites for Running PowerShell Scripts with Ansible ### 1. Enable Windows Remote Management (WinRM) WinRM allows Ansible to communicate with Windows hosts. To enable it: 1. Open PowerShell as Administrator. 2. Run the following commands: [code example] ### 2. Install pywinrm Install the **pywinrm** Python library on the Ansible control node: [code example] ### 3. Configure Ansible Inventory Define your Windows hosts in the inventory file: [code example] ## Using Ansible to Run PowerShell Scripts ### 1. Run Inline PowerShell Commands Use the **`win_shell`** module to execute PowerShell commands directly: [code example] ### 2. Execute PowerShell Scripts from a File To run an external PowerShell script, use the **`win_shell`** module: [code example] ### 3. Transfer and Execute PowerShell Scripts If the script is not present on the Windows host, use the **`copy`** module to transfer it first: [code example] ### 4. Capture ... --- ## Can Ansible Run Python Scripts? URL: https://www.ansiblebyexample.com/articles/can-ansible-run-python-scripts Description: Learn how Ansible can execute Python scripts on target systems, its requirements, and examples for automating Python-based workflows. Ansible is a versatile automation tool that can run **Python scripts** on target systems, making it a valuable resource for managing Python-based workflows and tasks. This article explores how Ansible can execute Python scripts, its requirements, and best practices for integrating Python into your automation pipelines. ## Can Ansible Run Python Scripts? Yes, Ansible can execute Python scripts on target systems using modules like **`script`**, **`command`**, or **`shell`**. By leveraging these modules, you can deploy, execute, and manage Python scripts efficiently. ### Key Features: - **Cross-Platform Compatibility**: Run Python scripts on Linux, Windows, and other platforms. - **Integration with Workflows**: Combine Python scripts with Ansible tasks for end-to-end automation. - **Dynamic Execution**: Pass arguments or environment variables to scripts during execution. ## How to Run Python Scripts with Ansible ### 1. Using the `script` Module The `script` module is designed to transfer and execute scripts on remote hosts. #### Example: [code example] In this example: - The Python script is transferred to the target system and executed. - The output of the script is captured for debugging or further use. ### 2. Using the `command` Module The `command` module executes commands directly on the target system. #### Example: [code example] ### 3. Using the `shell` Module The `shell` module provides more flexibility by allowing environment variables or shell-specific featur... --- ## Can Ansible Work on Windows? URL: https://www.ansiblebyexample.com/articles/can-ansible-work-on-windows Description: Learn how Ansible can manage and automate Windows systems, including setup, modules, and best practices. With tested, real-world examples. Ansible is a versatile automation tool that works seamlessly across Linux, macOS, and **Windows** systems. This article explores how Ansible can automate tasks on Windows, its requirements, and common use cases. ## Can Ansible Work on Windows? Yes, Ansible can manage and automate Windows systems. While Ansible traditionally targets Linux systems, its support for Windows has grown significantly. Using **WinRM** (Windows Remote Management) or SSH, Ansible communicates with Windows machines to perform various administrative tasks. ## Setting Up Ansible for Windows To manage Windows with Ansible, follow these steps: ### 1. Configure the Windows Host Enable WinRM on the Windows machine. This allows Ansible to communicate with the system. #### Steps to Enable WinRM: - Open PowerShell as Administrator. - Run the following command to enable basic authentication: [code example] - Add the Ansible control node's IP to the trusted hosts: [code example] ### 2. Install Required Modules Ensure the **pywinrm** Python library is installed on the Ansible control node: [code example] ### 3. Update the Inventory Define the Windows host in the Ansible inventory file: [code example] ## Ansible Modules for Windows Ansible provides a rich set of modules specifically for Windows automation: ### Common Windows Modules 1. **win_service**: Manage Windows services. [code example] 2. **win_package**: Install or uninstall Windows packages. [code example] 3. **win_user**: Manage Wind... --- ## Can You Use Ansible's assert Module in Jinja Templates? URL: https://www.ansiblebyexample.com/articles/can-you-use-ansible-assert-module-in-jinja-templates Description: Learn why Ansible's assert module can't run inside Jinja2 templates and discover the correct alternatives — from Jinja2 raise(), to assert tasks with. ## Introduction Ansible's `assert` module validates conditions during playbook execution — but it **cannot** run inside Jinja2 templates. Templates render text; modules execute tasks. Understanding this boundary helps you choose the right validation approach for each situation. ## Why assert Can't Run in Templates Jinja2 templates are a **rendering engine** — they produce text output. Ansible modules are **task executors** — they perform actions on hosts. These are fundamentally different: | Context | Purpose | Can Run Modules? | |---------|---------|-----------------| | Jinja2 template (`.j2` file) | Generate text output | No | | Ansible task (playbook) | Execute actions | Yes | | Jinja2 expression in task | Evaluate to a value | No | [code example] ## The assert Module — Correct Usage ### Basic Assertion [code example] ### Multiple Conditions [code example] ### Assert with Loop [code example] ### Assert in Handlers [code example] ## Validation Inside Jinja2 Templates When you need validation logic *within* a template file, use these Jinja2-native approaches: ### Method 1: Raise an Error [code example] The `mandatory` filter raises an `AnsibleUndefinedVariable` error with your message. ### Method 2: Conditional Content with Warnings [code example] ### Method 3: Default Values [code example] ### Method 4: Division by Zero Trick (Last Resort) [code example] This works but produces an ugly error. Prefer `mandatory` filter instead. ## Combining assert ... --- ## Change the User Primary Group on Linux with Ansible URL: https://www.ansiblebyexample.com/articles/change-the-user-primary-group-on-linux-ansible-module-user Description: Learn how to use Ansible to change a user's primary group on Linux systems with the user module. Streamline user management and ensure consistent group. ## How to Change the User Primary Group on Linux with Ansible? ## Ansible changes the User Primary Group on Linux > `ansible.builtin.user` Manage user accounts Today we're talking about Ansible module `user`. The full name is ansible.builtin.user, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts. It supports a huge variety of Linux distributions, SunOS and macOS, and FreeBSD. For Windows, use the `ansible.windows.win_user` module instead. ## Parameters - name _string_ - username - group _string_ - user's primary group (only one) - groups _list / elements=string_ - list of groups the user will be added to - append _boolean_ - no/yes - If yes, add the user to the groups specified in groups. If no, replace. This module has many parameters, let me highlight the useful for our use case. The only required is "name", which is the username. The primary group is specified in the "group" parameter, every user need to be part of only one group. The "groups" parameter specifies the list of additional groups that the user will be added to. This type of group sometimes is called also "secondary", "additional" or "supplementary". The parameter "append" is very important. With the "yes" option, the user is going to be added to the specified groups. With the "no" option, all group members are going to be overwritten with the specified groups. So to Conclusion is you s... --- ## ChatGPT for DevOps: Boost Productivity with AI-Generated Code URL: https://www.ansiblebyexample.com/articles/ansible-chatgpt-and-project-wisdom Description: Discover the benefits and limitations of using ChatGPT for DevOps tasks. Learn how AI-generated code can speed up workflows but requires careful. ChatGPT, produced by OpenAI, is an excellent tool for artificial intelligence with a Chat-like interface. We can ask ChatGPT any questions. What is unexpected is that the results are quite brilliant when we ask how to write code, too. Since the OpenAI ChatGPT release announcement on 30th November 2022, the ChatGPT tool has been a great hype on the internet. People around the globe tested in the most variant situations. It's impressive the application of the GPT (Generative Pre-trained Transformer) 3.5 large language model with a massive amount of data. It's a great tool to speed up the DevOps and SysOps workflow. Long story short: it creates a skeleton that we can use as a base for laboratory tests, but nothing is ready for production. It's impressive because it could be improved and probably we could obtain a great result in a few years. After a few tries, I agree with the opinions of Craig Brandt in the "Ansible and ChatGPT: Putting it to the test" article on the Ansible blog. ## The good ChatGPT can understand our request and process it in a way to generate some code. The output code respects the Ansible syntax. It gives us an idea of how automation could be executed in real life. {{}} ## The bad The produced code it's far from production ready. Some outputs are definitely better quality than others; it depends on the use case. We can use the Ansible-Lint tool to analyze for syntax checks and test when the Ansible best practices are fulfilled. ## Project Wisdom Pr... --- ## Checkout Git Repository via HTTPS — Ansible git Module Guide URL: https://www.ansiblebyexample.com/articles/checkout-git-repository-https-ansible-module-git Description: Automate Git repository cloning and updates with Ansible git module. Complete guide covering HTTPS checkout, version pinning, sparse checkout, deploy. ## Introduction Deploying code from Git repositories is a fundamental automation task. The `ansible.builtin.git` module handles cloning, updating, and managing Git checkouts on remote hosts — supporting HTTPS, SSH, version pinning, and advanced features like sparse checkout and submodules. For SSH-based checkout, see: Checkout Git Repository via SSH ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `repo` | string | Yes | Repository URL (HTTPS or SSH) | | `dest` | string | Yes | Destination path on the remote host | | `version` | string | No | Branch, tag, or commit SHA (default: `HEAD`) | | `update` | bool | No | Pull new revisions if repo exists (default: `true`) | | `clone` | bool | No | Clone the repo if it doesn't exist (default: `true`) | | `depth` | int | No | Shallow clone depth (saves bandwidth) | | `force` | bool | No | Discard local changes before updating | | `single_branch` | bool | No | Clone only the specified branch | | `recursive` | bool | No | Initialize submodules (default: `true`) | | `accept_hostkey` | bool | No | Accept SSH host keys automatically | | `key_file` | string | No | Path to SSH private key | ### Return Values | Return | Type | Description | |--------|------|-------------| | `after` | string | Commit SHA after checkout | | `before` | string | Previous commit SHA (if updated) | | `remote_url_changed` | bool | Whether the remote URL was modified | ## Basic Checkout [code ex... --- ## cisco.ios 11.5.1 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/cisco-ios-11-5-1-released-whats-new-and-how-to-test Description: cisco.ios 11.5.1 ships ACL port-mapping fixes, BGP l2vpn vpls safi support, and ios_user hashed_password idempotency fixes. # cisco.ios 11.5.1 Released - Whats New and How to Test ## Introduction `cisco.ios` is the Ansible collection that provides modules, plugins, and connection/cliconf logic for automating Cisco IOS and IOS-XE network devices - things like `ios_acls`, `ios_bgp_address_family`, `ios_user`, `ios_facts`, and the `ios` connection/terminal plugins used to manage config state, VLANs, interfaces, routing, and users over CLI (network_cli). Version **11.5.1** has just been published on Ansible Galaxy. Since this is the first version tracked for this collection on the blog, there is no prior baseline to diff against - the notes below come straight from the collection's own changelog for this release. ## Whats New This is a bugfix and documentation release. No new modules or feature additions are included; the changes focus on ACL protocol mapping, BGP address-family SAFI choices, terminal error detection, and a set of idempotency fixes in `ios_user` around hashed passwords. ### Bugfixes - **ios_acls** - Corrected port-to-protocol mapping for ports 5001 and 5002. - **ios_bgp_address_family** - Added `vpls` as a valid `safi` choice for the `l2vpn` address family configuration. - **ios_user** - Fixed `hashed_password` idempotency so that re-applying the same type/value pair against an already-configured user produces no commands, preventing unnecessary password updates on repeat runs. - **ios_user** - The `parse_hashed_password` helper now extracts the stored hash type and hash value ... --- ## cisco.ios 11.6.0 - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/cisco-ios-11-6-0-whats-new-and-how-to-test Description: cisco.ios 11.6.0 adds the traps.vrrpv3 option to ios_snmp_server and fixes idempotency and crash bugs in the BGP, HSRP, route-maps and SNMP modules. # cisco.ios 11.6.0 - Whats New and How to Test ## Introduction cisco.ios is the Ansible collection that provides modules and plugins for automating Cisco IOS and IOS-XE network devices, covering configuration of BGP, SNMP, HSRP, route-maps, interfaces, and more via resource modules. This article covers the changes shipped in cisco.ios 11.6.0, released as the successor to 11.5.1. This release adds one new parameter to `ios_snmp_server` and fixes a set of idempotency and crash bugs in `ios_bgp_address_family`, `ios_bgp_global`, `ios_hsrp_interfaces`, `ios_route_maps`, and `ios_snmp_server`. Anyone managing BGP neighbors with `remote_as`, HSRP `use_bia`, catch-all route-map entries, or SNMP VRRP traps should review the bugfix list below before upgrading, since several of these fixes change generated command output on `replaced`/`merged` runs. ## Whats New ### Minor Changes - `ios_snmp_server` - adds the `traps.vrrpv3` boolean parameter to configure `snmp-server enable traps vrrpv3`. ### Bugfixes - `ios_bgp_address_family` - fixed an idempotency issue where specifying `remote_as` for a neighbor caused the module to emit `neighbor X remote-as Y` on every run. `remote_as` can be specified at address-family or global level, but it always resides at the global level in IOS. The config class now correctly associates global-level attributes with the matching address-family during have-facts comparison. - `ios_bgp_address_family` - fixed `replaced` state not generating `no neigh... --- ## Civo Navigate 2024 Berlin: Explore Cloud, AI, and Emerging Tech URL: https://www.ansiblebyexample.com/articles/civo-navigate-europe-2024-save-the-date Description: Discover the latest in cloud, AI, and emerging tech at Civo Navigate 2024 in Berlin. Secure your spot for this transformative event. ## Introduction Berlin is set to become the epicenter of cloud innovation and technological advancement as Civo Navigate 2024 arrives in the vibrant city on September 10-11, 2024. This two-day event promises to bring together thought leaders, industry experts, and tech enthusiasts from around the world to explore the cutting-edge developments in cloud computing, artificial intelligence, machine learning, and emerging technologies. Mark your calendars, because this is an event you won’t want to miss. ## A Deep Dive into Technology's Future Civo Navigate 2024 will be divided into four distinct tracks: Thought Leadership, Cloud Native & Security, AI/ML, and Emerging Technology. Each track is designed to provide attendees with a comprehensive understanding of the latest trends, tools, and strategies shaping the future of technology. - **Thought Leadership:** Expect thought-provoking keynote speeches and panel discussions that delve into the future of AI, the impact of open-source technologies, and the evolution of cloud computing. These sessions will offer a unique perspective on how technology is driving innovation and sustainability in today's fast-paced digital world. - **Cloud Native & Security:** With a focus on practical knowledge, this track will feature workshops and tutorials on the latest cloud native practices, Kubernetes security, and the integration of new technologies into cloud environments. Whether you're a seasoned professional or new to the field, these ses... --- ## Clean Up Flatpak Apps — Reclaim Disk Space on Linux URL: https://www.ansiblebyexample.com/articles/how-to-clean-up-flatpak-apps-and-reclaim-disk-space Description: Remove unused Flatpak apps, runtimes, and cache to reclaim disk space. Uninstall, prune, and automate cleanup on Fedora, Ubuntu, and more. ## Introduction Flatpak, a popular package management system, provides a sandboxed environment for running applications. However, this sandboxed nature can result in the accumulation of significant disk space over time. In this guide, we will walk you through the process of cleaning up Flatpak apps to free up precious disk space on your Linux system. ### Where Flatpak Packages are Installed When you install a Flatpak package, it is stored in two primary locations on your system: 1. System Installation Directory: ``/var/lib/flatpak`` This directory contains all the files, metadata, application files, and runtime files shared among all Flatpak apps. 2\. User Installation Directory: ``~/.local/share/flatpak``\ Flatpak data specific to each user, including installed applications, is stored in this directory. ## How to Find Out the Size of Flatpak Apps Before proceeding with cleanup, it's helpful to identify the disk space occupied by Flatpak apps. Here are some commands you can use: 1. Check the size of `/var/lib/flatpak` [code example] 2\. Use Disk Usage Analyzer\ Alternatively, you can visually inspect the size of Flatpak data by using a disk usage analyzer tool. 3\. List installed Flatpak packages - by name and size [code example] - by app, name and size [code example] Output is like this: [code example] - by name and size per user [code example] ### Commands to Clean Up Flatpak Apps Now, let's proceed with cleaning up Flatpak apps to reclaim disk... --- ## Cloud Native London 2023: Save the Date URL: https://www.ansiblebyexample.com/articles/cloud-native-london-2023-save-the-date Description: Join Luca Berton at Cloud Native London on December 6th, 2023, for insights on cloud-native technologies. Details and registration here! ## Introduction Save the date for 6th December 2023 for Luca Berton's presentation at Cloud native London. The tech world in London gathered in anticipation at the December 2023 edition of Cloud Native London. ## Key Information 🗓 Date: 6th December 2023 📍 Location: 2 Fleet Place, EC4M 7RF, London, UK 🗒️ Registration: https://www.meetup.com/cloud-native-london/events/293022845/ ⏰ Agenda: - 6:00 PM — Enjoy delicious pizza and drinks - 6:30 PM — Welcome - 6:45 PM — Luca Berton - 7:15 PM — Shalabh Srivastava, AWS - 7:45 PM — Short Break - 8:00 PM — Octavian Tuchila, Google - 8:30 PM — Wrapping up the evening ## Cloud Native London Cloud Native London is a strong, open, diverse developer community around the Cloud Native platform and technologies in London. Run by Cheryl since 2017. See past events: https://www.oicheryl.com/archive/meetup Speak or sponsor us: http://cloudnativelon.com/ Join the Slack group: http://oicheryl.com/cnl-slack The Cloud Native London organizes events vibrant and informative meetups monthly with tech leaders and enthusiasts. More details can be found at the website https://www.oicheryl.com/cloudnativelondon for those interested in speaking or sponsoring future events. In a world of ever-evolving technology, events like Cloud Native London provide a vital platform for professionals to come together, learn from experts, and propel the tech industry forward. ## Conclusion In conclusion, save the date for the December 2023 Cloud Native London... --- ## community.crypto 3.4.0 Released - New PKCS#12 Modules and select_crypto_backend Deprecations URL: https://www.ansiblebyexample.com/articles/community-crypto-3-4-0-released-new-pkcs-12-modules-and-select-crypto-backend-deprecations Description: community.crypto 3.4.0 adds openssl_pkcs12_extract and openssl_pkcs12_info modules, deprecates select_crypto_backend across 15 modules ahead of 4.0.0. # community.crypto 3.4.0 Released - New PKCS#12 Modules and select_crypto_backend Deprecations ## Introduction `community.crypto` is the Ansible collection that provides modules and plugins for managing X.509 certificates, private/public keys, certificate signing requests, PKCS#12 archives, and other cryptographic material via OpenSSL, cryptography, or acme backends. Version 3.4.0 has just been published on Ansible Galaxy and is the first version tracked on this blog, so this post covers exactly what changed in this release according to the collection's own changelog. ## Whats New ### Release Summary According to the changelog, 3.4.0 is a feature release whose main additions are two new PKCS#12-related modules, accompanied by a broad deprecation of the `select_crypto_backend` option across most crypto modules in the collection. ### New Modules - `community.crypto.openssl_pkcs12_extract` - extracts certificate and private key from a PKCS#12 archive. - `community.crypto.openssl_pkcs12_info` - returns certificates and, optionally, the private key contained in a PKCS#12 file. These two modules complement the existing `openssl_pkcs12` module, which handles creation of PKCS#12 archives, by giving users a way to inspect and extract data from existing `.p12`/`.pfx` files without shelling out to `openssl` manually. ### Deprecated Features The `select_crypto_backend` option is now deprecated in the following modules and will be removed in community.crypto 4.0.0 (tracked in PR... --- ## Community.Crypto 3.5.0 Released - What's New and How to Test URL: https://www.ansiblebyexample.com/articles/community-crypto-3-5-0-released-what-s-new-and-how-to-test Description: community.crypto 3.5.0 adds mldsa44 SSH key support and marks private key output as sensitive on ansible-core 2.22+. How to test it. # Community.Crypto 3.5.0 Released - What's New and How to Test ## Introduction `community.crypto` is the Ansible collection that provides modules for managing X.509 certificates, OpenSSL keys and certificates, OpenSSH keys, ACME certificate issuance, and related cryptographic material on managed nodes. Version 3.5.0 has just been published on Galaxy, replacing 3.4.0. This is a feature release. It adds support for a new post-quantum SSH key type in `openssh_keypair`, and it changes how several modules mark returned private key material when running on newer versions of `ansible-core`. It also includes one bugfix related to a deprecated function used internally. ## Whats New ### mldsa44 SSH key type support `openssh_keypair` now supports generating `mldsa44` keys via `ssh-keygen`. This key type is only available when `backend=opensshbin`, or when `backend=auto` is used and a compatible `ssh-keygen` binary is installed on the system (PR #1081). ### Private key output marked as sensitive on ansible-core 2.22+ On `ansible-core` 2.22 and later, several modules and the related filter plugin now mark the private key content they return as sensitive, so it is masked in logs and output rather than printed in plain text (PR #1076). This affects: - `openssl_pkcs12_info` — when `return_private_key=true` - `openssl_privatekey` — when `return_content=true` - `openssl_privatekey_info` — when `return_private_key_data=true` - `openssl_privatekey_info` filter plugin — when `return_priv... --- ## community.docker 5.3.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/community-docker-5-3-0-released-whats-new-and-how-to-test Description: community.docker 5.3.0 adds docker_swarm_service command_as_args option for ENTRYPOINT-preserving service creation. Install and test guide. # community.docker 5.3.0 Released - Whats New and How to Test ## Introduction `community.docker` is the Ansible collection that provides modules and plugins for managing Docker containers, images, networks, volumes, and Docker Swarm resources. It is one of the most widely used community collections and is included by default in the `ansible` community package. Version 5.3.0 has just been published on Ansible Galaxy and is available for installation. This is a feature release. The changelog lists a single minor change affecting the `docker_swarm_service` module, described below, together with the practical steps to install and verify the new version. ## Whats New ### docker_swarm_service - new command_as_args option The `docker_swarm_service` module gains a new boolean option, `command_as_args`. When set to `true`, the module concatenates `command` and `args` and maps the result to `ContainerSpec.Args`, mirroring the behavior of `docker service create IMAGE [COMMAND] [ARG...]` and preserving the image's `ENTRYPOINT`. The default value remains `false`, which keeps the historical, and arguably surprising, mapping in place: `command` is mapped to `ContainerSpec.Command` and `args` to `ContainerSpec.Args`. This default is kept for backward compatibility, so existing playbooks are not affected unless the new option is explicitly enabled. This change closes two long-standing issues: - Addresses the mismatch between Ansible's `command`/`args` handling and the native `docker ... --- ## Community.Docker 5.4.0 Released - Whats New and How to Update URL: https://www.ansiblebyexample.com/articles/community-docker-5-4-0-released-whats-new-and-how-to-update Description: Community.docker 5.4.0 is out: docker_swarm marks join tokens as secrets on ansible-core 2.22+, plus a vendored Docker SDK fix. # Community.Docker 5.4.0 Released - Whats New and How to Update ## Introduction `community.docker` is the Ansible collection that provides modules and plugins to manage Docker hosts, containers, images, networks, volumes, Docker Compose stacks, and Docker Swarm clusters. Version 5.4.0 has been published on Ansible Galaxy, replacing the previous 5.3.0 release. This is a bugfix and feature release, with no breaking changes. ## Whats New ### Minor Changes - `docker_swarm` - on ansible-core 2.22+, the `Manager` and `Worker` join tokens and the `UnlockKey` returned by the module are now marked as secrets. This means they will no longer be displayed in clear text in task output or logs when running against a Swarm cluster with a recent enough ansible-core (PR #1312). ### Bugfixes - All modules using the vendored Docker SDK for Python have an updated list of reasons that are recognized as "image not found" errors. Previously, some Docker daemon error messages indicating a missing image were not matched correctly, which could cause modules to fail or behave unexpectedly instead of treating the image as absent (PR #1315). ## Affected Components | Component | Change type | Reference | | --- | --- | --- | | `docker_swarm` module | Minor change - mark join tokens/UnlockKey as secrets on ansible-core 2.22+ | PR #1312 | | Vendored Docker SDK for Python (all dependent modules) | Bugfix - updated "image not found" error detection | PR #1315 | ## How to Install and Verify [code exa... --- ## community.docker.docker_compose_v2 Module — Deploy Apps URL: https://www.ansiblebyexample.com/articles/ansible-docker-compose-deploy-multi-container-apps Description: The community.docker.docker_compose_v2 module deploys and manages Docker Compose stacks with Ansible, including health checks and rolling updates. ## Introduction `community.docker.docker_compose_v2` is the Ansible module for deploying and managing Docker Compose stacks — it wraps the `docker compose` CLI to bring up, update, and remove multi-container applications idempotently. This article covers the complete workflow from basic deployment to production patterns with health checks and rolling updates. ## Prerequisites [code example] ## Basic Stack Deployment [code example] ## Module Reference ### community.docker.docker_compose_v2 | Parameter | Default | Description | |---|---|---| | `project_src` | — | Path to directory containing `docker-compose.yml` | | `project_name` | directory name | Override project name | | `files` | — | List of compose files (override default) | | `state` | `present` | `present`, `absent`, `stopped`, `restarted` | | `pull` | `policy` | `always`, `missing`, `never` | | `build` | `policy` | `always`, `never` | | `remove_orphans` | `false` | Remove containers for undefined services | | `recreate` | `auto` | `always`, `never`, `auto` | | `services` | — | Specific services to manage | | `profiles` | — | Compose profiles to activate | | `env_files` | — | Additional .env files | | `timeout` | — | Shutdown timeout in seconds | ## Common Operations ### Pull and Recreate (Update) [code example] ### Stop Stack [code example] ### Remove Stack [code example] ### Restart Specific Service [code example] ## Template-Based Compose Files [code example] [code example] ## Health Check Verifi... --- ## community.general 13.4.0 Released - What's New and How to Update URL: https://www.ansiblebyexample.com/articles/community-general-13-4-0-released-what-s-new-and-how-to-update Description: community.general 13.4.0 is out: new Consul URL/env var options, github_repo visibility, gitlab_hook branch filter, and more. Full changelog and upgrade steps. # community.general 13.4.0 Released - What's New and How to Update ## Introduction `community.general` is the large catch-all Ansible collection maintained by the Ansible community, bundling hundreds of modules, plugins, and lookups that don't have a dedicated home in a more specific collection (Consul, GitLab, GitHub, InfluxDB, zypper, vmadm, and many more). It is one of the most frequently installed collections alongside `ansible.posix` and ships as part of the `ansible` community package. Version 13.4.0 has just been published on Ansible Galaxy. This article covers the changes shipped in this release and how to install or upgrade to it. ## What's New 13.4.0 is a regular bugfix and feature release. It does not remove or rename any module, but it adds several new options across existing modules and plugins, and it introduces one deprecation. ### Minor Changes - **archive** - now uses context managers when reading tar checksums (PR #12569). - **consul modules** - add a new `url` option that sets the address of the Consul agent as a whole; the existing `host`, `port`, and `scheme` options each override the matching component of it. This does not apply to `community.general.consul` (PR #12216). - **consul modules** - connection options now fall back to the `CONSUL_HTTP_ADDR`, `CONSUL_HTTP_SSL`, `CONSUL_HTTP_SSL_VERIFY`, `CONSUL_HTTP_TOKEN`, and `CONSUL_CACERT` environment variables when not explicitly specified. Again, this excludes `community.general.consul`, which does... --- ## community.general 13.5.0 Released - Whats New and How to Update URL: https://www.ansiblebyexample.com/articles/community-general-13-5-0-released-whats-new-and-how-to-update Description: community.general 13.5.0 adds diff mode, SASL auth, secrets redaction and more. Full changelog and upgrade instructions inside. # community.general 13.5.0 Released - Whats New and How to Update ## Introduction `community.general` is one of the largest collections shipped as part of the Ansible community package. It bundles modules, lookup plugins, callback plugins, and inventory plugins that do not have a dedicated collection of their own, covering areas such as GitLab/GitHub automation, LDAP, Consul, LVM, logrotate, and various callback plugins used for logging and observability. Version 13.5.0 has just been published on Galaxy, updating from 13.4.0. This is a regular bugfix and feature release, not a major version bump, so no breaking changes are expected. The changelog lists a long set of minor changes across lookup plugins, callback plugins, and modules. ## Whats New ### Callback plugins - secrets redaction on ansible-core 2.22+ Several callback plugins have been updated to redact sensitive output when running on ansible-core 2.22 and newer, taking advantage of the new secrets API: - `elastic` callback plugin - redact sensitive output on ansible-core 2.22+ (also received an internal refactor with no visible behavior changes). - `jabber` callback plugin - redact sensitive output on ansible-core 2.22+. - `log_plays` callback plugin - redact sensitive output on ansible-core 2.22+. - `loganalytics` callback plugin - redact sensitive output on ansible-core 2.22+. - `loganalytics_ingestion` callback plugin - refactored to use ansible-core 2.22's new secrets API to properly mark and mask secrets. ... --- ## community.mysql 5.0.2 Released - Deprecation Warnings on Module Redirects URL: https://www.ansiblebyexample.com/articles/community-mysql-5-0-2-released-deprecation-warnings-on-module-redirects Description: community.mysql 5.0.2 is out: a patch release adding deprecation warnings to module redirects. Details, changelog, and install/verify steps. # community.mysql 5.0.2 Released - Deprecation Warnings on Module Redirects ## Introduction `community.mysql` is the Ansible Collection that provides modules and plugins for managing MySQL and MariaDB databases: creating and dropping databases and users, managing grants, replication, configuration variables, and running arbitrary SQL through modules such as `mysql_db`, `mysql_user`, `mysql_query`, `mysql_replication`, and `mysql_variables`. Version 5.0.2 has just been published to Ansible Galaxy. This is the first time this collection is tracked on this blog, so there is no prior known version to diff against here. However, according to the collection's own changelog, 5.0.2 is a small, self-contained patch release. ## Whats New According to the release summary shipped in the changelog, this version is exactly what it says on the tin: > This is a patch release of community.mysql collections which only adds deprecation warnings to module redirects. In practice, `community.mysql` ships a number of modules as redirects to their canonical implementation (for example short names that alias to `community.mysql.mysql_*` modules, or older module names kept around for backward compatibility). This release adds explicit deprecation warnings to those redirected entry points, so playbooks that still reference the old/aliased module names will now surface a warning in the Ansible output pointing users toward the module they should be using instead. No new modules, no new options, a... --- ## community.postgresql 4.2.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/community-postgresql-4-2-0-released-whats-new-and-how-to-test Description: community.postgresql 4.2.0 adds PostgreSQL 17 MAINTAIN privilege support and fixes three postgresql_db bugs. Install and test instructions inside. # community.postgresql 4.2.0 Released - Whats New and How to Test ## Introduction `community.postgresql` is the Ansible Collection that provides modules and plugins to manage PostgreSQL databases, roles, privileges, extensions, and configuration through Ansible playbooks. It is one of the collections bundled in the `ansible` community package and is commonly used to automate PostgreSQL database provisioning and administration. Version 4.2.0 has been published to Ansible Galaxy. This is a minor release that adds one new privilege-related feature for PostgreSQL 17 and fixes three bugs in the `postgresql_db` module. ## Whats New ### Minor Changes - `postgresql_privs` - now supports granting the `MAINTAIN` privilege on tables. This privilege was introduced in PostgreSQL 17 and covers maintenance operations such as `VACUUM`, `ANALYZE`, `REINDEX`, and `CLUSTER` without requiring ownership of the table (https://github.com/ansible-collections/community.postgresql/pull/888). ### Bugfixes - `postgresql_db` - fixed connection limit not being applied when the value is set to `"0"` (https://github.com/ansible-collections/community.postgresql/issues/879). - `postgresql_db` - fixed the `session_role` parameter, which was being silently ignored for raw connections (https://github.com/ansible-collections/community.postgresql/pull/865). - `postgresql_db` - fixed a bug where restoring from `.sql` files caused the file to be executed twice. The module now avoids combining `--file` and st... --- ## community.postgresql 5.0.0 Released - Major Update to postgresql_membership and Removal of Legacy Options URL: https://www.ansiblebyexample.com/articles/community-postgresql-5-0-0-released-major-update-to-postgresql-membership-and-removal-of-legacy-options Description: community.postgresql 5.0.0 is out with a reworked postgresql_membership module, new memberships option, breaking changes, and removed legacy connection options. # community.postgresql 5.0.0 Released - Major Update to postgresql_membership and Removal of Legacy Options ## Introduction `community.postgresql` is the Ansible collection that provides modules and plugins to manage PostgreSQL databases, roles, privileges, and configuration from playbooks. It is one of the collections bundled in the `ansible` community package and is commonly used for automating database provisioning and access control. Version 5.0.0 is a **major release**, jumping from 4.2.0. Unlike a routine patch bump, this release contains breaking changes centered almost entirely on the `postgresql_membership` module, plus the removal of previously deprecated connection options across the collection. Anyone using `postgresql_membership` in production playbooks should read the porting guide below before upgrading. ## Whats New ### Minor Changes - Replaced the deprecated `ansible.module_utils.six` compatibility shims with their Python standard library equivalents. `ansible.module_utils.six` is deprecated in ansible-core 2.21 and scheduled for removal in 2.24. - `postgresql_membership` - added `granted_by_any`, both at the top level and per `memberships` row, to manage every grant of a membership regardless of who made it, matching the behavior of the deprecated `groups` option. `GRANT` then names no granting role, and `state=absent` / `state=exact` revoke every grant of the membership. - `postgresql_membership` - added the `grants` and `effective_options` return val... --- ## community.vmware 6.3.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/community-vmware-6-3-0-released-whats-new-and-how-to-test Description: community.vmware 6.3.0 bumps vmware.vmware to 2.10.0, deprecates several modules ahead of 8.0.0, and fixes a trunked/PVLAN portgroup bug. # community.vmware 6.3.0 Released - Whats New and How to Test ## Introduction `community.vmware` is the Ansible collection that provides modules and plugins for automating VMware vSphere infrastructure, covering vCenter, ESXi hosts, virtual machines, datastores, networking, tags, and more. Version 6.3.0 has been published to Ansible Galaxy. This article covers what changed in this release and how to install and verify it. ## Whats New The headline change in 6.3.0 is a version bump of the required `vmware.vmware` collection dependency to 2.10.0 (PR #2568). Alongside that bump, several modules have been marked as deprecated ahead of removal in `community.vmware` 8.0.0, and one bugfix has landed for network trunking. ### Major Changes - Required `vmware.vmware` collection version bumped to 2.10.0 (#2568). ### Deprecated Features The following modules are deprecated in 6.3.0 and will be removed in `community.vmware` 8.0.0: - `vcenter_standard_key_provider` - `vmware_guest_snapshot_info` - `vmware_host_facts` - `vmware_host_powerstate` - `vmware_host_service_info` - `vmware_host_service_manager` - `vmware_tag` - `vmware_tag_manager` In addition, the default values used by `vmware_vcenter_settings` are deprecated and will be removed where possible in 8.0.0 (issue #2559). All of the above are tracked under PR #2568. Users relying on these modules should start planning migration to their replacements before the 8.0.0 release. ### Bugfixes - `vmware_guest_network` - fixed... --- ## community.vmware 6.4.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/community-vmware-6-4-0-released-whats-new-and-how-to-test Description: community.vmware 6.4.0 is out, deprecating several module_utils functions and methods ahead of removal in 8.0.0 (PR #2599). Install and test guide. # community.vmware 6.4.0 Released - Whats New and How to Test ## Introduction `community.vmware` is the Ansible collection that provides modules and plugins for automating VMware vSphere infrastructure, covering vCenter, ESXi hosts, clusters, datastores, virtual machines, and content libraries. It is one of the most widely used collections for private cloud and virtualization automation with Ansible. Version 6.4.0 has been published on Ansible Galaxy, bumping up from 6.3.0. Unlike a typical patch release, this version does not add new modules or fix bugs directly. Instead, it formally deprecates a large batch of internal `module_utils` functions and methods that are used across many modules in the collection. All of these deprecations are tracked under a single pull request, PR #2599, and are scheduled for removal in `community.vmware` 8.0.0. ## Whats New ### Deprecated module_utils Functions and Methods The following functions and methods in `plugins.module_utils.vmware` and `plugins.module_utils.vmware_rest_client` are now marked as deprecated. They still work in 6.4.0, but playbook authors and, more importantly, module and role developers relying on these internals should plan a migration path before `community.vmware` 8.0.0 ships. | Module | Deprecated symbol | Type | Removal target | |---|---|---|---| | `module_utils.vmware` | `find_host_by_cluster_datacenter` | function | 8.0.0 | | `module_utils.vmware` | `vmware_argument_spec` | function | 8.0.0 | | `module_util... --- ## community.vmware 7.0.0 Released - Breaking Changes and Removed Modules Explained URL: https://www.ansiblebyexample.com/articles/community-vmware-7-0-0-released-breaking-changes-and-removed-modules-explained Description: community.vmware 7.0.0 drops ansible-core < 2.21.0 support and removes deprecated modules. Full breaking changes list and upgrade steps. # community.vmware 7.0.0 Released - Breaking Changes and Removed Modules Explained ## Introduction `community.vmware` is the Ansible collection that provides modules, inventory plugins and module utilities for automating VMware vSphere and vCenter environments (managing VMs, clusters, hosts, datastores, content libraries, and more). Version 7.0.0 is a **major release** that follows 6.4.0 and, unlike a typical minor bump, it removes a large number of previously deprecated modules, methods and options. Anyone upgrading from the 6.x series needs to review the porting guide before running existing playbooks against this version. ## Whats New ### Breaking Changes The headline change in 7.0.0 is a raised minimum requirement: - Support for `ansible-core =7.0.0` in a `requirements.yml` or CI pipeline: - Confirm `ansible-core` is at 2.21.0 or newer. - Grep playbooks/roles for any of the module names in the tables above and swap them for the `vmware.vmware` equivalents. - If custom modules or `module_utils` import the removed methods/functions directly, update those imports. - Re-run the test suite / molecule scenarios against the new version before promoting it in production. ## Installation and Verification [code example] If using a `requirements.yml`: [code example] [code example] --- ## community.windows 3.3.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/community-windows-3-3-0-released-whats-new-and-how-to-test Description: community.windows 3.3.0 adds win_psmodule_info filtering options and fixes win_scheduled_task SYSTEM become_user issue for Windows automation. # community.windows 3.3.0 Released - Whats New and How to Test ## Introduction community.windows is the Ansible collection that provides Windows-specific modules and plugins not included in ansible.windows, covering areas such as scheduled tasks, PowerShell module management, LAPS password retrieval, and psexec-based connections. Version 3.3.0 has been published on Ansible Galaxy and brings performance improvements to `win_psmodule_info`, a fix for `win_psmodule` module status lookups, and a fix for `win_scheduled_task` when running as `SYSTEM`. ## Whats New ### Minor Changes - `win_psmodule_info` - Added the `include_properties` parameter, allowing fine-grained control over which module properties are returned. This improves performance when only specific properties are needed (PR #688). - `win_psmodule_info` - Added the `skip_module_repository_info` parameter to skip querying PowerShellGet for repository-related metadata (PR #688). - `win_psmodule_info` - The module now automatically skips expensive PowerShellGet repository lookups when `include_properties` is specified without repository-related properties (PR #688). ### Bugfixes - `win_psmodule` - Now retrieves the installation status of the requested module only, instead of all modules, which was expensive on hosts with many modules installed (PR #688). - `win_psmodule_info` - Fixed a documentation typo, changing `procoessor_architecture` to `processor_architecture`. - `laps_password` - Migrated away from the depr... --- ## Comparing versions — ansible.builtin.version plugin URL: https://www.ansiblebyexample.com/articles/comparing-versions-ansible-builtin-version-plugin Description: Using Ansible to compare versions and ensure consistency across your infrastructure with the ansible.builtin.version plugin. As your IT infrastructure grows and evolves, it can become increasingly difficult to ensure consistency across all your systems and applications. One way to address this challenge is using configuration management tools like Ansible to automate tasks such as version comparison and updates. This article will explore how to use Ansible to compare versions and ensure consistency across your infrastructure. ## What is Ansible? Ansible is an open-source tool that automates IT tasks such as configuration management, application deployment, and orchestration. It uses a simple language called YAML to describe configuration and automation tasks, making it easy for developers and system administrators to learn and use. ## Comparing Versions with Ansible One common task in IT infrastructure management is ensuring that all systems and applications run the same software version. This can be time-consuming and error-prone, especially as the number of systems and applications in your infrastructure grows. Fortunately, Ansible makes it easy to automate version comparison and ensure consistency across your infrastructure. The code snippet provided above Playbooknstrates how to use Ansible to compare the version of Ansible installed on all hosts with the specified version “2.15”. This code uses the “ansible.builtin.version” filter to compare the installed version with the specified version and then returns a boolean value indicating whether the installed version is greater than or equal to... --- ## Concatenate Multiple Files in Order with Ansible Template URL: https://www.ansiblebyexample.com/articles/concatenate-multiple-files-in-a-specific-order-ansible-module-template-and-yaml Description: Learn how to concatenate multiple files in a specific order with Ansible. This guide demonstrates using the template module and includes practical code. ## How to use Concatenate multiple files in a specific order using Ansible? This is extremely useful for service configuration files, reports, and so much more use cases. I personally use this code for markdown documents for Pandoc. ## Ansible Concatenate multiple files in a specific order - `ansible.builtin.template` - Template a file out to a target host - `ansible_managed`, `template_host`, `template_uid`, `template_path`, `template_fullpath`, `template_destpath`, and `template_run_date` Let's talk about the Ansible module `template`. The full name is `ansible.builtin.template`, it's part of `ansible-core` and is included in all Ansible installations. It templates a file out to a target host. Templates are processed by the Jinja2 templating language. Also you could use also some special variables in your templates: `ansible_managed`, `template_host`, `template_uid`, `template_path`, `template_fullpath`, `template_destpath`, and `template_run_date`. It supports a large variety of Operating Systems. For basic text formatting, use the Ansible `ansible.builtin.copy` module or for empty file Ansible `ansible.builtin.file` module. For Windows, use the `ansible.windows.win_template` module instead. ## Parameters - `src` _path_ - template ("templates/" dir) - `dest` _path_ - target location - `validate` _string_ - validation command before ("%s") - `backup` _boolean_ - no/yes - `mode`/`owner`/`group` - permission - `setype`/`seuser`/`selevel` - SELinux Let me highlight the m... --- ## Configure a Pod to Use a Volume for Storage on Kubernetes or OpenShift with Ansible URL: https://www.ansiblebyexample.com/articles/configure-a-pod-to-use-a-volume-for-storage-ansible-module-k8s Description: Learn how to configure a Kubernetes or OpenShift Pod to use a volume for persistent storage with Ansible. This guide includes a live Playbook example. ## How to Configure a Pod to Use a Volume for Storage on Kubernetes K8s or OpenShift OCP? I’m going to show you a live Playbook and some simple Ansible code. A Container's file system lives only as long as the Container does. So when a Container terminates and restarts, filesystem changes are lost. For more consistent storage that is independent of the Container, you can use a Volume. This is especially important for stateful applications, such as key-value stores (such as Redis) and databases. ## Ansible creates Kubernetes or OpenShift service - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - name _string_ /namespace _string_ - object name / namespace - api_version _string_ - "v1" - kind _string_ - object model - state _string_ - present/absent/patched - definition _string_ - YAML definition - src _path_ - path for YAML definition - template _raw_ - YAML template definition - validate _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object namespace. They are useful to create, ... --- ## Configure a Python Virtual Environment for Ansible AWS — ansible collection amazon.aws URL: https://www.ansiblebyexample.com/articles/configure-a-python-virtual-environment-for-ansible-aws-ansible-collection-amazon-aws Description: Learn to configure a Python Virtual Environment for Ansible AWS amazon.aws collection using the latest Python 3.8 and boto3 library releases. ## How to configure a Python Virtual Environment for Ansible AWS? Using a Python Virtual Environment is a convenient way to maintain up-to-date Python dependency of the Ansible collection amazon.aws without interfering with your Linux system. This initial configuration sometimes is a roadblock for some AWS users to start using Ansible. ## Links - Ansible collection amazon.aws - Python boto3 ## Playbook Configure a Python Virtual Environment for Ansible AWS: - boto3 How to Python Virtual Environment for Ansible AWS. I’m going to show you how to configure a Python Virtual Environment for Ansible AWS to successfully use the Ansible collection `amazon.aws` of modules and plugins to manage various operations related to AWS infrastructure such as EC2, VPC, Security Groups, etc. Ansible AWS modules are written on top of `boto3`. Boto3 is the Python SDK for the AWS that allows users to manage AWS infrastructure: EC2, VPC, Security Groups, etc. ### code [code example] ### execution [code example] - requirements.txt [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Configure a Python Virtual Environment for Ansible AWS. --- ## Configure Ansible Dynamic Inventory for VMware in Simple Steps URL: https://www.ansiblebyexample.com/articles/ansible-dynamic-inventory-for-vmware-ansible-community-vmware-vmware-vm-inventory Description: Discover how to configure Ansible Dynamic Inventory for VMware to automate and manage virtual machines efficiently. Step-by-step guide with Playbook. ## Introduction This guide shows you the best way to list all the virtual machines within your VMware infrastructure using Ansible. I'll provide a live Playbook and some simple Ansible code. —I'm Luca Berton. ## Ansible Dynamic Inventory for VMware - **Functionality**: Dynamically retrieves virtual machines as inventory hosts from the VMware environment. - **Plugin**: `community.vmware.vmware_vm_inventory` - **Dependencies**: Python `pyVmomi`, `requests`, and vSphere Automation SDK The VMware dynamic inventory plugin interacts with VMware APIs to dynamically manage nodes with Ansible. The `community.vmware.vmware_vm_inventory` plugin, part of the community-supported collection, allows you to run Ansible automation across your VMware virtual machines. ## Links - `community.vmware.vmware_vm_inventory` ## Demo Let’s configure Ansible Dynamic Inventory for VMware to list all virtual machines in your VMware infrastructure as an Ansible inventory. ### Configuration Files - **ansible.cfg**: [code example] - **inventory.vmware.yml**: [code example] ### Listing Hosts - **Command**: [code example] - **Output**: [code example] ### Graphing Hosts - **Command**: [code example] - **Output**: [code example] Code with ❤️ on GitHub ## Conclusion Now you know how to configure Ansible Dynamic Inventory for VMware, enabling you to automate and manage your VMware virtual machines efficiently. --- ## Configure PostgreSQL with Ansible: User Access and Service Management URL: https://www.ansiblebyexample.com/articles/allow-md5-connection-for-a-postgresql-user-or-role-ansible-module-postgresql-pg-hba Description: Learn how to automate PostgreSQL configuration with Ansible. This guide shows how to set user access with md5 authentication and manage PostgreSQL. ## How to Allow md5 Connection for a PostgreSQL User / Role with Ansible? ## Ansible Allow md5 Connection for a PostgreSQL User / Role - `community.postgresql.postgresql_pg_hba` - Add, remove or modify a rule in a pg_hba file Let's talk about the Ansible module `postgresql_pg_hba`. The full name is `community.postgresql.postgresql_pg_hba`, which means that is part of the collection of modules "`community.postgresql`" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to Add, remove or modify a rule in a pg_hba file. This module uses `psycopg2`, a Python PostgreSQL User library. You must ensure that `python3-psycopg2` is installed on the host before using this module. ## Links - `community.postgresql.postgresql_pg_hba` ## Playbook Let's jump into a real-life Ansible Playbook to Allow md5 Connection for a PostgreSQL User / Role now called Role. I'm going to show you how to create a pg_hba.conffile to allow the`myuser` user/role to connect to the current PostgreSQL server using md5 authentication. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Allow md5 Connection for a PostgreSQL User / Role with Ansible. --- ## Configure WSL in Domain — Step-by-Step URL: https://www.ansiblebyexample.com/articles/configuration-of-wsl-in-a-domain-environment Description: Discover how to configure WSL in a domain environment. This guide covers joining a domain, installing necessary packages, and setting up Kerberos. ## Introduction Windows Subsystem for Linux (WSL) is a powerful tool that allows Windows users to run a Linux distribution alongside their Windows operating system. It provides a seamless integration of Linux utilities and tools within the Windows environment. While WSL is primarily used for development and testing, it’s not uncommon for organizations to want to configure it in a domain environment to ensure better management, security, and compliance. In this article, we will explore the steps to configure WSL in a domain environment. ### Prerequisites Before you start configuring WSL in a domain environment, make sure you have the following prerequisites in place: 1. Windows 10 or Windows 11: Ensure that you are using a compatible version of Windows with WSL support. WSL 2 is recommended for its improved performance and compatibility. 2. WSL Installed: Install WSL on your Windows machine. You can do this via the Windows Features settings. 3. Linux Distribution: Choose and install a Linux distribution from the Microsoft Store or via a package manager. Popular choices include Ubuntu, Debian, and CentOS. 4. Domain Membership: Ensure that your Windows machine is joined to the domain. You will need administrative privileges to achieve this. 5. Active Directory: Have access to your organization’s Active Directory server and administrative credentials for user and group management. ## Steps to Configure WSL in a Domain Environment Configuring WSL in a Domain Environment involve... --- ## Configure XFS Filesystem with Quotas on Fedora URL: https://www.ansiblebyexample.com/articles/configure-xfs-filesystem-with-quotas-on-fedora Description: Step-by-step guide to mounting XFS filesystems with user and group quotas on Fedora using fstab and systemd mount units. Managing storage is a critical aspect of system administration, and the XFS filesystem is a popular choice due to its performance and scalability. This guide explains how to configure an XFS filesystem with quotas on Fedora, using both `/etc/fstab` and systemd mount units. ## Introduction This article walks you through the steps to: - Configure an XFS filesystem on a secondary disk. - Enable user (`uquota`) and group (`gquota`) quotas. - Manage mounts using `/etc/fstab` or systemd units. Let’s dive into the configuration. ## Prerequisites - A secondary disk (e.g., `/dev/nvme0n2p1`) is attached to your system. - Familiarity with basic Linux commands. ## Configure the XFS Filesystem ### 1. Identify the Disk Use `lsblk` to identify the disk and its partition: [code example] Ensure the disk (e.g., `/dev/nvme0n2p1`) is recognized. ### 2. Format the Partition If the disk is not formatted, initialize it with the XFS filesystem: [code example] ### 3. Create a Mount Point Create a directory where the filesystem will be mounted: [code example] ## Enable Quotas in `/etc/fstab` To enable quotas during boot, edit `/etc/fstab`: [code example] Add an entry for the partition: [code example] Find the partition’s UUID using: [code example] ### Remount and Verify Remount all filesystems: [code example] Verify the mount options: [code example] ## Use Systemd Mount Units for Advanced Configuration ### Create the Systemd Unit Create a custom systemd unit file: [code example] ... --- ## Configuring Ansible for AWS: Setup Guide & Playbook URL: https://www.ansiblebyexample.com/articles/configure-ansible-for-aws-ansible-collection-amazon-aws Description: Set up Ansible for AWS with IAM credentials, boto3, and the amazon.aws collection. Follow our guide to configure and execute your first AWS playbook. ## How to configure Ansible for AWS? Ansible provides various modules to manage AWS infrastructure, which includes EC2, VPC, Security Groups, etc. I'll show you step by step how to prepare your Ansible controller to interact with the AWS infrastructure. This initial configuration sometimes is a roadblock for some AWS users to start using Ansible. ## Configure Ansible for AWS - Amazon Identity and Access Management (IAM) Access Key - Python `boto3` SDK requires 3.6+ - Ansible collection `amazon.aws` The Ansible modules and plugins support the AWS infrastructure interactions. First of all, you need to authenticate using AWS Access Key credentials: Access Key ID and Secret Access Key from Identity and Access Management (IAM) dashboard. Ansible AWS modules are written on top of `boto3`. `boto3` is the Python SDK for the AWS that allows users to interact with AWS infrastructure via API. This library interacts with the AWS API via the Ansible modules and plugins. The `boto3` Python library requires Python 3.6+. The Ansible collection `amazon.aws` of modules and plugins manages various operations related to EC2, VPC, Security Groups, etc. As the name suggests, this resource is provided by the Ansible Engineer Team. ## Links - Ansible collection amazon.aws - Python boto3 ## Playbook Configure Ansible for AWS - Amazon IAM Access Key - Install Python boto3 SDK - Install Ansible amazon.aws collection - Ansible Playbook How to Configure Ansible for AWS. First of all, you ne... --- ## Configuring ansible_python_interpreter in Ansible URL: https://www.ansiblebyexample.com/articles/configuring-ansible-python-interpreter Description: Learn how to use ansible_python_interpreter to configure the Python interpreter in Ansible, ensure compatibility across hosts, and manage multiple versions. ## Introduction **`ansible_python_interpreter` is an Ansible variable that tells Ansible which Python binary to use on a managed node**, overriding Ansible's auto-detection when a host has multiple Python versions installed or a non-standard interpreter path. When working with Ansible, ensuring the correct Python interpreter is used on managed nodes is crucial for executing tasks seamlessly. By default, Ansible detects and uses the system’s Python version, but sometimes, specifying a particular Python interpreter is necessary—especially when dealing with multiple Python versions or specific system requirements. This article explores how to configure the Python interpreter in Ansible using `ansible_python_interpreter` and why it is important for stable automation. ## Understanding `ansible_python_interpreter` The `ansible_python_interpreter` variable allows users to explicitly define the Python interpreter that Ansible should use when executing tasks. This is particularly useful in environments where: - Multiple versions of Python are installed. - The default Python version is incompatible with Ansible modules. - The target system does not have Python 3 installed as the default interpreter. - Virtual environments are used. ### Default Behavior By default, Ansible attempts to locate and use `/usr/bin/python3`. If it’s unavailable, it falls back to `/usr/bin/python`, and in some cases, it might try `/bin/python` or another available Python interpreter. However, in Red Ha... --- ## Configuring Kernel Parameters in RedHat-like Linux Systems with Ansible System Role URL: https://www.ansiblebyexample.com/articles/configure-kernel-parameters-in-redhat-like-linux-systems-ansible-system-role Description: Learn how to configure kernel parameters in RedHat-like Linux systems using the Ansible System Role. Follow our live Playbook example for efficient. How to Configure Kernel Parameters in RedHat-like Linux systems with Ansible using system role? ## Ansible Configure Kernel Parameters in RedHat-like systems - `linux-system-roles` Fedora, Enterprise Linux & CentOS - `rhel-system-roles` package Red Hat Enterprise Linux Today we're talking about `linux-system-role`. This is a swiss army that you need to absolutely add to your IT knowledge. Currently, there are 21 roles to configure a lot of system properties. The roles are developed and tested for RedHat-like systems but the project might expand in the future. It's available as a package named `linux-system-role` for Fedora, Enterprise Linux, and CentOS. In Red Hat Enterprise Linux is named `rhel-system-roles` and is available since RHEL 8. If you would like to know more about the available roles and jump immediately to the Ansible Galaxy page or the official website. ## Links - https://galaxy.ansible.com/linux-system-roles - https://linux-system-roles.github.io/ ## Playbook Configure Kernel Parameters in RedHat-like Linux systems with Ansible System Role ### code [code example] ### execution [code example] ### idempotency [code example] ### Verification [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Configure Kernel Parameters in RedHat-like systems with Ansible System Role. --- ## Containerized Ansible Automation Platform 2024 Update URL: https://www.ansiblebyexample.com/articles/containerized-ansible-automation-platform-update-2024 Description: The containerized Red Hat Ansible Automation Platform preview has excited the tech community with its streamlined installation, enhanced security. ## Introduction The recent Technology Preview of the containerized Red Hat Ansible Automation Platform has sparked considerable excitement within the tech community. This innovative approach offers a streamlined, feature-rich solution for enterprise-ready automation, gathering interest from both current users and prospects. The journey towards the general availability of this platform has been enriched with valuable feedback, leading to significant enhancements, fixes, and improvements. This article dives into these updates, highlighting how they contribute to a more simplified installation process, enhanced security measures, and other notable changes. ## Further Installation Simplification One of the major strides in improving the user experience with the containerized Ansible Automation Platform is the simplification of the installation process. By leveraging core features of the platform, the need for some command-line instructions has been eliminated, making the setup smoother. For instance, the `ansible.cfg` file now automatically sets up the collections path, default inventory file, and logs: [code example] This adjustment means users no longer have to manually specify a collections path or pass in the inventory when sticking to installation defaults, streamlining the initial setup process. ## Enhanced Security Security is paramount, and the latest update defaults to using Transport Layer Security (TLS) across all services, fortifying network security. Users hav... --- ## Copy Multiple Files to Remote Hosts with Ansible Efficiently URL: https://www.ansiblebyexample.com/articles/copy-multiple-files-ansible-lookup-plugin-fileglob Description: Discover how to use Ansible fileglob lookup plugin and copy module to efficiently transfer multiple files to remote hosts. Explore practical examples. ## How to Copy Multiple Files to Remote Hosts with Ansible? ## Ansible Copy Multiple Files - `ansible.builtin.fileglob` - list files matching a pattern Today we're talking about the Ansible lookup plugin fileglob. Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources. The full name is `ansible.builtin.fileglob`, it's part of `ansible-core` and is included in all Ansible installations. The purpose of the lookup plugin is to list files matching a pattern. ## Usage ### Parameters - \_terms string - path(s) of files to read ### Return Values - \_list list - list of files The parameters of the plugin fileglob. The only required parameter is the default "\_terms", with the path(s) of files to read. You could easily use it in any Ansible loop with the Ansible statement: `with_fileglob`. ## Playbook Copy Multiple Files with Ansible Playbook. ### code - copy-multiple.yml [code example] - examples/report.txt [code example] - examples/report2.txt [code example] ## execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Copy Multiple Files to Remote Hosts with Ansible. --- ## Coursera Back-End Infrastructure: Servers, Secure APIs and Data URL: https://www.ansiblebyexample.com/articles/back-end-infrastructure-servers-secure-apis-and-data Description: Learn back-end infrastructure management, secure API design, and data protection strategies. Enroll for free on Coursera. {{}} ## What you'll learn - Evaluate the integral role of data protection in securing back-end infrastructure and APIs. - Elevate your learned skills for effective server configuration to support robust and secure API integrations. - Analyze case studies Playbooknstrating successful data protection and secure API strategy implementations. - Evaluate and implement security measures to enhance the integrity and confidentiality of data. ## Course description This course explores back-end infrastructure management, secure API design, and robust data protection techniques. Participants will gain practical skills in server configuration, API security, and strategies for protecting data, which are crucial for building resilient and scalable systems. The course combines theoretical foundations, hands-on applications, and real-world examples to ensure comprehensive understanding and skill acquisition. This course empowers professionals like Data Protection Officers, Back-End Developers, API Designers, System Administrators, and Information Security Professionals with essential knowledge and skills in data protection and API security. With prerequisites including basic data protection principles, back-end infrastructure familiarity, API design expertise, and information security experience, participants are well-equipped for effective engagement. Throughout the course, participants will accomplish various objectives, including evaluating data protection's role in securing ba... --- ## Coursera Technical Troubleshooting: Diagnostics, Networks, Customers URL: https://www.ansiblebyexample.com/articles/technical-troubleshooting-diagnostics-networks-customers Description: Learn to resolve complex IT issues, manage networks, and communicate technical solutions effectively. Elevate your IT support skills today! {{}} ## What you'll learn - Analyze and resolve complex software issues using systematic approaches. - Evaluate network performance and troubleshoot intricate problems using advanced tools and techniques. - Articulate technical issues and solutions effectively to non-technical stakeholders, ensuring clarity and understanding. - Synthesize technical troubleshooting and communication strategies to proactively improve customer satisfaction and experience. ## Course description In an era of rising technology integration and complexity, the need for proficient technical troubleshooters who can effectively communicate solutions is more critical than ever. This course aims to equip IT professionals with the skills to navigate and resolve complex IT challenges while maintaining strong stakeholder relationships. By engaging with current case studies, learners will find the course's content relevant and directly applicable to modern IT environments. This included effectively diagnosing incidents, managing network equipment, and communicating strategies for every stakeholder. This course is designed for IT professionals, from novices to seasoned experts, aiming to sharpen their troubleshooting skills and communication abilities. Gain practical techniques to tackle complex software and network issues confidently. Elevate your support game and provide top-notch assistance to end-users and clients. No specific prerequisites needed. Basic understanding of computer systems and ... --- ## Crafting and Publishing Your Custom Ansible Collection on Automation Hub URL: https://www.ansiblebyexample.com/articles/crafting-and-publishing-your-custom-ansible-collection-on-automation-hub Description: Learn to create and publish a custom Ansible Collection "test.test" on Automation Hub. Follow steps to initialize, customize, build, and upload your. ## Introduction In the ever-evolving landscape of automation, creating customized solutions becomes paramount. Ansible Automation Hub provides a platform to showcase and share these custom creations with the world. In this guide, we’ll walk you through the process of crafting your custom Ansible Collection, named “test.test,” and publishing it on Ansible Automation Hub. ## Links - Ansible Automation Hub - https://docs.ansible.com/ansible/latest/dev_guide/developing_collections.html ## Step by step ### 1. Create the Custom Collection Begin your journey by creating the “test.test” collection using the ansible-galaxy command-line utility: [code example] You’ll receive a confirmation that the “test.test” collection has been successfully created. [code example] The command generates the following directory tree in the current directory: [code example] ### 2. Customize the Collection Content Navigate into the collection directory and modify the “`runtime.yml`” file located at “`test/test/meta/runtime.yml`”. You can customize by adding additional modules, plugins, roles, etc. Here, set the “`requires_ansible`” parameter to specify the minimum Ansible version required: [code example] ### 3. Build the Ansible Artifact The following command creates the “test-test-1.0.0.tar.gz” archive that we can publish in Automation Hub. Generate the “test-test-1.0.0.tar.gz” archive using the following command: [code example] Upon execution, the generated archive is ready to be publishe... --- ## Create a directory in Linux — Ansible module file URL: https://www.ansiblebyexample.com/articles/create-a-directory-ansible-module-file Description: How to set up the "~/example" directory, set user and group ownership, and apply UNIX mode 0644 in Linux using Ansible with a live Playbook. ## How to create a directory with Ansible? ## Ansible create a directory > `ansible.builtin.file`: Manage files and file properties Today we're talking about the Ansible module file. The full name is ansible.builtin.file, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties. For Windows targets, use the `ansible.windows.win_file` module instead. ## Parameters - `path` string (dest, name) - file path - `state` string - file/absent/directory/hard/link/touch - `mode`/`owner`/`group` - permission - `setype`/`seuser`/`selevel` - SELinux This module has some parameters to perform any tasks. The only required is "`path`", where you specify the filesystem path of the file you're going to edit. The state defines the type of object we are modifying, the default is "`file`" but for our use case, we need the "`directory`" option. ## Demo Let's jump into a real-life playbook on how to create a directory with Ansible. ### code - create_directory.yml [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to create a directory in Linux with Ansible. --- ## Create Ansible AWX Superuser in Docker — Admin Setup Guide URL: https://www.ansiblebyexample.com/articles/create-ansible-awx-superuser-in-docker-containers-ansible-awx Description: Create an AWX superuser in Docker with awx-manage. Complete guide covering user creation, password reset, API authentication, LDAP integration. ## Introduction The AWX superuser has full administrative power — configuring settings, managing users, running any job template, and accessing all API endpoints. This guide covers creating your first superuser, resetting passwords, managing multiple users, and securing access. ## Prerequisites - AWX running in Docker containers (via Docker Compose or AWX Operator) - Access to the Docker host command line ## Create a Superuser ### Using docker exec [code example] Interactive prompts: [code example] ### Non-Interactive (Scripted) For automation and CI/CD: [code example] Or with environment variables: [code example] ### Find Your Container Name If `tools_awx_1` doesn't work: [code example] For Docker Compose v2: [code example] ## Reset Superuser Password Forgot the admin password: [code example] ## Access the AWX Interface ### Web UI Navigate to `https://awx.example.com` (or your AWX host) and log in: After login, you'll see the AWX Dashboard: ### API Authentication #### Browser API Explorer Navigate to `https://awx.example.com/api/v2/` and log in: #### Token-Based Authentication (Recommended) [code example] Response: [code example] Use the token in subsequent requests: [code example] #### Basic Authentication [code example] ## Manage Multiple Users ### Create Regular Users [code example] ### List All Users [code example] ### Promote User to Superuser [code example] ## awx-manage Commands Reference | Command | Description | |---------... --- ## Create Hard Links in Linux with Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/create-a-hard-link-ansible-module-file Description: Learn to create hard links in Linux using Ansible’s file module. Follow our step-by-step guide and live Playbook example for effective management. ## How to create a hard link in Linux with Ansible? ## Ansible creates a hard link > `ansible.builtin.file` Manage files and file properties Today we're talking about the Ansible module `file`. The full name is `ansible.builtin.file`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties. For a symlink (or softlink) use see the following parameters of Ansible file module. For Windows targets, use the `ansible.windows.win_file` module instead. ## Parameters - src string - symlink path - dest string - destination file path - state string - file/absent/directory/link/hard/touch - mode/owner/group - permission - setype/seuser/selevel - SELinux This module has some parameters to perform any tasks. The two required fields are "src" and "dest" which specify the filesystem paths of the har link and the target file. The state defines the type of object we are modifying, the default is "file" but for our use case, we need the "link" option. Let me highlight also the permission and SELinux parameters. ## Playbook Let's jump into a real-life playbook on how to create a symbolic link with Ansible. ### code - create_hardlink.yml [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know... --- ## Create Kubernetes K8s or OpenShift OCP namespace project — Ansible module k8s URL: https://www.ansiblebyexample.com/articles/create-kubernetes-k8s-or-openshift-ocp-namespace-project-ansible-module-k8s Description: How to automate the \"myapp\" namespace project created using the Ansible module k8s for Kubernetes K8s or OpenShift OCP. Tested, copy-paste examples included. ## How to create Kubernetes K8s or OpenShift OCP namespace project with Ansible? ## Ansible creates Kubernetes or OpenShift namespace project - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - name _string_ /namespace _string_ - object name / namespace - api_version _string_ - "v1" - kind _string_ - object model - state _string_ - present/absent/patched - definition _string_ - YAML definition - src _path_ - path for YAML definition - template _raw_ - YAML template definition - validate _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object namespace. They are useful to create, delete, or discover an object without providing a full resource definition. The `api_version` parameter specifies the Kubernetes API version, the default is "v1" for version 1. The `kind` parameter specifies an object model. The `state` like for other modules determines if an object should be created - `present` option, patched - `patched` option, or deleted - `absent` option. The `definition` parameter allo... --- ## Create Kubernetes K8s or OpenShift OCP Pod — nginx — Ansible module k8s URL: https://www.ansiblebyexample.com/articles/create-kubernetes-k8s-or-openshift-ocp-pod-ansible-module-k8s Description: How to automate the creation of "nginx" Pod in namespace "example" of Kubernetes K8s or OpenShift OCP with Ansible module k8s. ## How to create Kubernetes K8s or OpenShift OCP Pod with Ansible? ## Ansible create Kubernetes or OpenShift Pod - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - name _string_ /namespace _string_ - object name / namespace - api_version _string_ - "v1" - kind _string_ - object model - state _string_ - present/absent/patched - definition _string_ - YAML definition - src _path_ - path for YAML definition - template _raw_ - YAML template definition - validate _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object namespace. They are useful to create, delete, or discover an object without providing a full resource definition. The `api_version` parameter specifies the Kubernetes API version, the default is "v1" for version 1. The `kind` parameter specifies an object model. The `state` like for other modules determines if an object should be created - `present` option, patched - `patched` option, or deleted - `absent` option. The `definition` parameter allows you to provide a valid YA... --- ## Create Kubernetes K8s or OpenShift OCP Secret — Ansible module k8s URL: https://www.ansiblebyexample.com/articles/create-kubernetes-k8s-or-openshift-ocp-secret-ansible-module-k8s Description: How to automate the creation of “mysecret” secret in namespace “default” Kubernetes K8s or OpenShift OCP with Ansible module k8s. ## How to create Kubernetes K8s or OpenShift OCP secret with Ansible? ## Ansible create Kubernetes or OpenShift secret - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - name _string_ /namespace _string_ - object name / namespace - api_version _string_ - "v1" - kind _string_ - object model - state _string_ - present/absent/patched - definition _string_ - YAML definition - src _path_ - path for YAML definition - template _raw_ - YAML template definition - validate _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object namespace. They are useful to create, delete, or discover an object without providing a full resource definition. The `api_version` parameter specifies the Kubernetes API version, the default is "v1" for version 1. The `kind` parameter specifies an object model. The `state` like for other modules determines if an object should be created - `present` option, patched - `patched` option, or deleted - `absent` option. The `definition` parameter allows you to provide a va... --- ## Create Kubernetes K8s or OpenShift OCP Service — Ansible module k8s URL: https://www.ansiblebyexample.com/articles/create-kubernetes-k8s-or-openshift-ocp-service-ansible-module-k8s Description: How to automate the creation of "nginx-service" Service and "nginx" Pod in namespace "example" of Kubernetes K8s or OpenShift OCP with Ansible module k8s. ## How to create Kubernetes K8s or OpenShift OCP Service with Ansible? ## Ansible create Kubernetes or OpenShift Service - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects Let's talk about the Ansible module `k8s`. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. ## Parameters - name _string_ /namespace _string_ - object name / namespace - api_version _string_ - "v1" - kind _string_ - object model - state _string_ - present/absent/patched - definition _string_ - YAML definition - src _path_ - path for YAML definition - template _raw_ - YAML template definition - validate _dictionary_ - validate resource definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and/or the object namespace. They are useful to create, delete, or discover an object without providing a full resource definition. The `api_version` parameter specifies the Kubernetes API version, the default is "v1" for version 1. The `kind` parameter specifies an object model. The `state` like for other modules determines if an object should be created - `present` option, patched - `patched` option, or deleted - `absent` option. The `definition` parameter allows you to provide a ... --- ## Create Local Groups on Windows with Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/create-a-local-group-on-windows-like-systems-ansible-module-win-group Description: Learn how to create and manage local groups on Windows systems using Ansible’s win_group module. Follow our detailed Playbook example for automation. ## How to Create a local group on Windows-like systems with Ansible? ## Ansible creates a local group on Windows-like systems - `ansible.windows.win_group` - Add or remove groups Today we're talking about the Ansible module `win_group`. The full name is `ansible.windows.win_group`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It adds and removes local groups. For Linux target use the `group` module instead. ## Parameters - name string - group name - state string - present/absent - description string - description of the group This module has some parameters to perform some tasks. The only required is "name", which is the group name. The "state" parameter allows us to create or delete a group, in our use case the default it's already set to "present" to create a group. The "description" parameter allows you to specify a description of the group, it's not mandatory but sometimes is useful. ## Links - ansible.windows.win_group ## Playbook How to Create a local group on Windows-like systems with Ansible Playbook. I’m going to show you how to automate the creation of the “example” group on my Playbook Windows machine. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to cre... --- ## Create Network Infrastructure on AWS using Ansible Modules URL: https://www.ansiblebyexample.com/articles/create-network-infrastructure-on-aws-using-ansible-modules Description: Learn how to take advantage of Infrastructure as Code to create our own infrastructure on-demand on Amazon Web Services (AWS) using the Ansible amazon.aws. There is a growing need for streamlined network infrastructure management as more companies migrate to the cloud. Amazon Web Services (AWS), which is one of the most widely used cloud platforms, provides organizations with a variety of tools and services that make it easier for them to manage their network infrastructure. Creating a network infrastructure on AWS can be a daunting task as it involves various cloud computing challenges, but with Ansible modules, the process becomes easier and more manageable. Ansible is one of the most popular ways to manage infrastructure on Amazon. It is an open-source automation platform that lets businesses automate their infrastructure management tasks. In this article, we'll cover how to create network infrastructure on Amazon Web Services (AWS) by utilizing Ansible modules. We'll go through several Ansible modules that may assist in the creation of a virtual private cloud (VPC), subnet, internet gateway, route table, security group, instances, and load balancers. ## What are the Ansible Modules? Ansible is a platform for automation in infrastructure management that simplifies operations for businesses. It has a number of modules that can be used to automate different tasks, such as setting up and managing virtual machines, configuring networks, and deploying applications. Ansible modules are pre-written scripts that can be used to carry out particular tasks like configuring settings, installing software, and managing resources. The... --- ## Create PostgreSQL Databases with Ansible: Easy Guide URL: https://www.ansiblebyexample.com/articles/create-a-postgresql-database-ansible-module-postgresql-db Description: Learn to automate PostgreSQL database management with Ansible postgresql_db module. Follow our guide to create, delete, and manage databases effortlessly. ## How to Create a PostgreSQL Database with Ansible? ## Ansible Create a PostgreSQL Database > `community.postgresql.postgresql_db` Add or remove PostgreSQL databases from a remote host Let's talk about the Ansible module `postgresql_db`. The full name is `community.postgresql.postgresql_db`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to add or remove PostgreSQL databases from a remote host. ## Parameters - `name` _string_ - Name of database - `state` _string_ - present/absent/dump/restore/rename - The operation Let me summarize the main parameters of the module `postgresql_db`. Ansible supposes that PostgreSQL is in the target node. The only required parameter is "name", the name of the database to interact with. The parameter "state" specify the desired state or the operation for the selected database. The option "present" means that the database should be created and the option "absent" means that the database should be deleted. Other useful operations are "dump" and "restore" that uses `pg_dump`, the embedded PostgreSQL utility to backup and restore to the `target` file. Another useful operation is `rename`, from `name` to `target`. This module uses `psycopg2`, a Python PostgreSQL database library. You must ensure that `python3-... --- ## Create Text Files with Ansible copy Module (Playbook Examples) URL: https://www.ansiblebyexample.com/articles/create-a-text-file-ansible-module-copy Description: Create and manage text files with Ansible copy module. Complete guide with content parameter, permissions, SELinux, templates, multi-line content. ## Introduction Creating text files on remote servers is one of the most common tasks in infrastructure automation. Whether you need configuration files, scripts, status markers, or simple text content, the Ansible `copy` module provides an elegant solution using the `content` parameter. In this guide, you'll learn how to create text files with Ansible using `ansible.builtin.copy`, including single-line content, multi-line files, dynamic content with variables, proper permissions, and SELinux contexts. ## The ansible.builtin.copy Module The full module name is `ansible.builtin.copy`, part of the built-in collection shipped with Ansible. While its primary purpose is copying files from the controller to remote hosts, the `content` parameter enables direct file creation without a source file. ### When to Use copy vs template | Use Case | Module | |----------|--------| | Static text content | `ansible.builtin.copy` with `content` | | Content with variables/logic | `ansible.builtin.template` | | Copy existing file | `ansible.builtin.copy` with `src` | | Complex Jinja2 formatting | `ansible.builtin.template` | | Simple variable substitution | Either works | **Rule of thumb**: If your content has `{% %}` blocks, loops, or complex conditionals, use `template`. For static or simple variable content, `copy` is simpler and more readable. ## Parameters Reference | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `dest` | path | Yes | Re... --- ## Create VMware vSphere VM with Ansible: Full Playbook Guide URL: https://www.ansiblebyexample.com/articles/create-a-vmware-vsphere-virtual-machine-ansible-module-vmware-guest Description: Master creating VMware vSphere VMs using Ansible. Our guide provides a comprehensive playbook and step-by-step instructions for VM setup and management. ## How to create a VMware vSphere Virtual Machine with Ansible? ## Ansible creates a VMware vSphere Virtual Machine > `community.vmware.vmware_guest` Manages virtual machines in vCenter Today we're talking about the Ansible module `vmware_guest`. The full name is `community.vmware.vmware_guest`, which means that is part of the collection of modules to interact with VMware, community-supported. It's a module pretty stable and out for years. It manages virtual machines in vCenter. ## Parameters The module `vmware_guest` has a very long list of parameters to customize all your needs to create a VMware vSphere Virtual Machine. Please refer to manual for the full list. ## Links - community.vmware.vmware_guest ## Playbook How to create a VMware vSphere Virtual Machine with Ansible. I'm going to show you how to create a Virtual Machine named "myvm" with the following resources: - 1 CPU - 1 GB of RAM - 10 GB of storage, thin-provisioned in the datastore "Datastore-1" network card name "VM Network", type "vmxnet3" ### code - create_vm.yml [code example] - vars.yml [code example] - inventory [code example] ### execution [code example] #### idempotency [code example] ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to create a VMware vSphere Virtual Machine with Ansible. --- ## Create Windows 10 Pro Media with Microsoft's Official Tool and Ansible URL: https://www.ansiblebyexample.com/articles/create-windows-10-pro-media-with-microsoft-official-tool Description: Learn how to use the Windows Media Creation Tool and automate tasks with Ansible to upgrade, install, or create bootable media for Windows 10 Pro. The **Windows Media Creation Tool** is a utility developed by Microsoft to simplify the process of downloading, installing, or upgrading to **Windows 10 Pro**. Combined with **Ansible automation**, it becomes an even more powerful tool for IT professionals, enabling seamless deployment and installation across multiple systems. --- ## Key Features 1. **Upgrade Assistant**: Helps you upgrade your existing Windows version to Windows 10 Pro directly without requiring an intermediate installation file. 2. **Bootable Media Creation**: Facilitates the creation of a bootable USB drive or DVD for fresh installations or repair. 3. **Customizable Installation**: Allows you to select the Windows edition, architecture (32-bit or 64-bit), and language based on your preferences. 4. **ISO File Download**: Provides an option to download an ISO image of Windows 10 Pro for manual installation. 5. **Automation with Ansible**: Automate repetitive tasks such as ISO downloads, media creation, and installation using Ansible playbooks. --- ## Why Use the Windows Media Creation Tool with Ansible? 1. **Reliable Source**: Directly downloads files from Microsoft servers, ensuring security and authenticity. 2. **Automation Capabilities**: Use Ansible to automate downloading, verifying, and deploying media across multiple systems. 3. **Offline Installation**: Supports creating offline installation media for systems without an internet connection. 4. **Batch Operations**: Ansible allows managing and dep... --- ## Creating a Custom Ansible Lookup Plugin in Python for Reading a File URL: https://www.ansiblebyexample.com/articles/creating-a-custom-ansible-lookup-plugin-in-python-for-reading-a-file Description: Create a custom Ansible lookup plugin in Python to extend capabilities for reading file contents on the Ansible controller, enhancing file retrieval. ## Introduction Ansible, a powerful automation tool, offers a wide range of built-in modules and plugins that simplify infrastructure management. However, there are scenarios where you may need to extend Ansible’s capabilities by creating custom plugins tailored to your specific needs. In this article, we will explore creating and using a custom Ansible file lookup plugin, which allows you to retrieve file contents from your Ansible controller’s file system during playbook execution. ## What is a Lookup Plugin? Ansible lookup plugins are used to retrieve data dynamically during playbook execution. They allow you to fetch information from various sources, such as databases, APIs, or external files, and use that data in your Ansible tasks. ## Links - https://docs.ansible.com/ansible/latest/dev_guide/developing_plugins.html#lookup-plugins - https://docs.ansible.com/ansible/latest/plugins/lookup.html#lookup-plugins - https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-lookup-plugin-path ## Unveiling the Custom File Lookup Plugin Before delving into the details of the plugin, let’s take a closer look at the Python script provided at the beginning of this article. This script serves as an example of a custom Ansible file lookup plugin and consists of several essential components: ### 1. Python 3 Headers [code example] These lines specify Python 3 headers required for compatibility when submitting this plugin to Ansible. ### 2. Documentation [code ... --- ## Creating a Custom Ansible Lookup Plugin in Python for retrieving API token URL: https://www.ansiblebyexample.com/articles/creating-a-custom-ansible-lookup-plugin-in-python-for-retrieving-api-token Description: Learn how to create an Ansible lookup plugin to fetch API tokens, with a complete example of the token.py plugin code and step-by-step explanations. ## Introduction Ansible, an open-source automation tool, offers a wide range of built-in modules and plugins to simplify infrastructure management. However, sometimes, you may need to extend its functionality by creating custom plugins tailored to your specific needs. In this article, we’ll explore the creation of a custom Ansible lookup plugin in Python. ## What is a Lookup Plugin? Ansible lookup plugins are used to retrieve data dynamically during playbook execution. They allow you to fetch information from various sources, such as databases, APIs, or external files, and use that data in your Ansible tasks. ## Links - https://docs.ansible.com/ansible/latest/dev_guide/developing_plugins.html#lookup-plugins - https://docs.ansible.com/ansible/latest/plugins/lookup.html#lookup-plugins - https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-lookup-plugin-path ## Step by Step The following steps explain how to create a custom Ansible lookup plugin in Python. It begins by introducing lookup plugins in Ansible, which are used to fetch data dynamically during playbook execution. The provided Python script is an example of a plugin designed to retrieve an API token from a specific URL. The following steps break down the script into its components: Python headers, documentation, imports, initialization, and the custom lookup module with its ‘run’ method. ### Setting the Stage Let’s consider the example of retrieving a token via an API request with a POS... --- ## Creating a New Ansible Collection: A Step-by-Step Guide URL: https://www.ansiblebyexample.com/articles/creating-a-new-ansible-collection Description: Create a new Ansible Collection "test.test" with ansible-galaxy. Follow steps to initialize, build, and verify the collection, resulting in a. ## Introduction Ansible Collections are a powerful way to organize and distribute your Ansible content, including modules, plugins, roles, and more. They allow you to package and share your automation resources in a structured and reusable manner. In this tutorial, we'll walk you through the process of creating a new Ansible Collection using the `ansible-galaxy` command-line tool. ## Links - Creating collections - Developing collections ## Step by step **Step 1: Installation and Prerequisites** Before you start, ensure that you have Ansible and the `ansible-galaxy` command-line tool installed on your system. If not, you can install Ansible by following the official documentation. Once installed, you'll be ready to create your new Ansible Collection. **Step 2: Initialize a New Collection** To create a new collection, open your terminal and run the following command: [code example] This command initializes a new collection named `test.test`. You should see an output confirming that the collection was created successfully. [code example] **Step 3: Explore the Collection Structure** After creating the collection, navigate to the collection's directory. You can use the following command: [code example] Inside this directory, you'll find several subdirectories and files that make up your Ansible Collection's structure: - `docs/`: This directory is where you can add documentation related to your collection. - `galaxy.yml`: This file contains metadata about your collectio... --- ## Creating an Application Load Balancer with Ansible in AWS URL: https://www.ansiblebyexample.com/articles/creating-an-application-load-balancer-with-ansible-in-aws Description: Automating AWS Infrastructure with Ansible - Creating an Application Load Balancer in AWS. Tested on real machines with clear, copy-paste examples. ## Amazon Application Load Balancer (ALB) As applications grow in complexity, they require more sophisticated infrastructure to ensure high availability and scalability. One of the key components of such infrastructure is a load balancer, which distributes traffic across multiple instances, improving application performance and reliability. In Amazon Web Services (AWS), you can create an Application Load Balancer (ALB) to handle traffic distribution for your applications. And if you want to automate the creation of an ALB and its associated resources, you can use Ansible, a popular open-source automation tool. In this article, we will guide you through the process of creating an ALB using Ansible in AWS. ### Prerequisites Before we dive into the Ansible playbook for creating an ALB, we need to set up a few things in AWS. 1. VPC and Subnets The first thing we need to do is to create a Virtual Private Cloud (VPC) and subnets where the ALB will be deployed. If you have not done this before, follow the instructions in the AWS documentation to create a new VPC and two subnets in different Availability Zones. 2. EC2 instances Next, we need to have at least two EC2 instances running in the subnets created above. These instances will serve as targets for the ALB. You can either create new instances or use existing ones. 3. IAM certificate Finally, we need to have an SSL/TLS certificate created in AWS Identity and Access Management (IAM) that we can use for HTTPS communication... --- ## Creating an Azure Virtual Machine Scale Set using Ansible URL: https://www.ansiblebyexample.com/articles/creating-an-azure-virtual-machine-scale-set-using-ansible Description: Effortlessly Deploy and Scale Your Infrastructure with Ansible and Azure Scale Sets. Tested on real machines with clear, copy-paste examples. ## Creating an Azure Virtual Machine Scale Set using Ansible In the world of cloud computing, scalability is a critical requirement for many organizations. When it comes to managing virtual machines, Azure Virtual Machine Scale Sets is a powerful solution that provides automatic scaling of VMs. Ansible, the popular configuration management tool, also provides a module for managing VM Scale Sets in Azure. In this article, we will explore how to create an Azure Virtual Machine Scale Set using Ansible. ## Overview of Azure Virtual Machine Scale Sets Before we dive into the details of creating a VM Scale Set, let's first understand what it is and how it works. A VM Scale Set is a group of identical, load-balanced virtual machines that can automatically scale up or down based on demand or a schedule. This makes it easy to deploy and manage a set of VMs, while also providing high availability and scalability. A VM Scale Set can be created in Azure using either the Azure Portal, Azure CLI, or Azure PowerShell. In this article, we will use Ansible to create the VM Scale Set. ## Creating an Azure VM Scale Set with Ansible The Ansible module for Azure VM Scale Sets is `azure_rm_virtualmachinescaleset`. This module provides a simple way to create, update, and delete VM Scale Sets in Azure. Let's take a look at the playbook in detail. The playbook starts with defining the hosts and variables required for creating the VM Scale Set. The variables include `vmss_vm_size`, `vmss_admin_... --- ## Creating an Azure Virtual Network with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/creating-an-azure-virtual-network-with-ansible-playbook Description: Learn how to use Ansible’s Azure modules to automate the creation of a virtual network with subnets and a public IP address in Microsoft Azure Cloud. ## Creating an Azure Virtual Network with Ansible Playbook As organizations continue to adopt cloud technologies, the need for automated infrastructure provisioning and configuration management becomes more important than ever. Ansible, a popular open-source automation tool, has several modules for working with Microsoft Azure Cloud. In this article, we will explore how to use Ansible’s Azure modules to automate the creation of a virtual network with subnets and a public IP address in Microsoft Azure Cloud. ## Prerequisites To follow along with this tutorial, you will need the following: - An Azure account with the necessary permissions to create virtual networks and subnets. - Ansible is installed on your local machine or server. - Azure modules for Ansible installed. [code example] Creating an Azure Virtual Network with Ansible Let’s start by creating an Ansible playbook to create a virtual network with subnets and a public IP address in Azure. ## Links - azure.azcollection.azure_rm_virtualnetwork - azure.azcollection.azure_rm_subnet - azure.azcollection.azure_rm_publicipaddress ## Code 1. Define Variables First. We need to define the variables that will be used throughout the playbook. Open a new file and add the following code: [code example] In this code, we define the following variables: - resource_group_name: The name of the resource group where the virtual network will be created. - location: The Azure region where the resource group will be created. - tag... --- ## Creating Ansible Collection Using ansible-creator and VS Code Ansible Extension URL: https://www.ansiblebyexample.com/articles/creating-ansible-collection-using-ansible-creator-and-vs-code-ansible-extension Description: Create and scaffold Ansible Collections using ansible-creator and the VS Code Ansible Extension. Complete guide with CLI commands, directory structure. ## Introduction Ansible Collections are the standard way to package and distribute Ansible content — modules, roles, plugins, and playbooks — as reusable units. The `ansible-creator` tool (part of the Ansible Development Tools) scaffolds a complete collection structure with all the required files, saving you from creating the directory tree manually. This guide covers both the CLI and VS Code GUI approaches to creating collections. ## Prerequisites ### Install ansible-creator [code example] Verify installation: [code example] ### Install VS Code Ansible Extension (Optional) 1. Open VS Code 2. Go to Extensions (Ctrl+Shift+X) 3. Search for "Ansible" by Red Hat 4. Click Install The extension includes `ansible-creator` integration with a graphical interface. ## Method 1: CLI with ansible-creator ### Initialize a New Collection [code example] This creates the full collection structure: [code example] ### CLI Options | Option | Description | |--------|-------------| | `--init-path` | Directory to create the collection in | | `--force` | Overwrite existing collection (re-scaffold) | | `--verbosity` | Output detail level (0-3) | | `--log-file` | Write output to a log file | ### Example with All Options [code example] ## Method 2: VS Code GUI ### Step 1: Open the Ansible Creator 1. Open VS Code and click the **Ansible icon** in the Activity Bar 2. Click **"Get Started"** in the Ansible Creator section 3. The System Requirements box shows the status of ansible, Py... --- ## Creating Custom Ansible Plugins to Fetch API Data Easily URL: https://www.ansiblebyexample.com/articles/creating-custom-ansible-plugins-to-fetch-api-data-easily Description: Learn how to create custom Ansible plugins to fetch data from APIs. Enhance your automation tasks with this detailed step-by-step guide. ## Introduction Ansible is a powerful automation tool used for configuration management, application deployment, and task automation. While it comes with a rich set of modules and plugins, there are times when you might need to extend its capabilities by writing custom plugins. In this article, we will walk you through the process of creating a custom Ansible plugin to retrieve user data from an API endpoint. ## Why Create a Custom Plugin? Creating a custom plugin allows you to: - Extend Ansible's functionality to meet specific needs. - Integrate with external APIs that are not covered by existing modules. - Simplify complex tasks by encapsulating them in reusable plugins. ## Our Goal We will create a custom lookup plugin that fetches a list of users from `https://reqres.in/api/users?page=2` and makes this data available for use in Ansible playbooks. ## Prerequisites - Basic understanding of Ansible and Python. - Ansible installed on your machine. - Internet connection to access the API. ## Step-by-Step Guide ### Step 1: Directory Structure Create the necessary directory structure for the custom plugin. By default, Ansible looks for plugins in the `lookup_plugins` directory within your project. [code example] ### Step 2: Write the Plugin Code Create a file named `list_users.py` inside the `lookup_plugins` directory with the following content: [code example] This code defines a custom lookup plugin that makes a GET request to the specified API endpoint and retur... --- ## Custom hello-world Ansible Filter Plugin URL: https://www.ansiblebyexample.com/articles/custom-hello-world-ansible-filter-plugin Description: Unveiling Ansible’s “hello-world” Filter Plugin in foo.bar: A glimpse into personalized automation for tailored solutions. ## Introduction In the world of automation and configuration management, Ansible plays a pivotal role in simplifying complex tasks and orchestrating diverse systems. One of the key features that makes Ansible highly versatile is the ability to extend its functionality through plugins. In this article, we’ll dive into the “`hello-world`" filter plugin written in Python for Ansible within the `foo.bar` namespace. ## Understanding the Basics The “`hello-world`” filter plugin is a simple yet illustrative example of a filter plugin in Ansible. The purpose of this plugin is to generate a personalized greeting message, taking a name as input and returning a “`Hello, [name]`” message. [code example] Let’s break down the key components of the provided Python script, `hello_world.py`: 1. Metadata Section: - `name`: Specifies the name of the filter plugin. - `author`: Indicates the author of the plugin along with their contact email. - `version_added`: Denotes the version in which the plugin was added. - `short_description`: Provides a brief overview of the plugin. - `description`: Offers more detailed information about the plugin, including its purpose. - `positional`: Defines the positional arguments that the plugin accepts. - `options`: Describes the options, such as input parameters, that the plugin supports. 2. Filter Implementation: - `_hello_world` function: This private function takes a name as an argument and returns a greeting message. - `FilterModule` class: Defines the... --- ## Customizing Ansible: Ansible Module Creation URL: https://www.ansiblebyexample.com/articles/customizing-ansible-ansible-module-creation Description: Learn how to create custom Ansible modules in Python, utilizing Ansible Module Utils for efficient development. Follow best practices and explore an. ***Original author: Nikhil Kumar in Customizing Ansible: Ansible Module Creation *** ## Introduction Ansible is a powerful open-source software used for configuration management, provisioning, and application deployment. It belongs to the realm of Infrastructure as Code (IaC), where infrastructure is defined and managed through code. Ansible enables you to create and deploy infrastructure on various platforms, including cloud services like AWS and Azure, as well as hypervisors. One of the key components that makes Ansible so versatile and extensible is the concept of Ansible Modules. These modules are reusable, standalone units of code designed to perform specific tasks on managed or target nodes. While Ansible modules can be written in any language capable of producing JSON output, Python is the most popular and recommended choice. This is because Ansible itself is written in Python, which makes it seamlessly integrate with JSON data. In this article, we will explore the steps involved in creating custom Ansible modules using Python. We’ll also provide an example to illustrate the process. ## Creating Custom Ansible Modules in Python To create a custom Ansible module in Python, follow these steps: 1. Set Up Your Environment: Begin by creating a library directory in your working environment where you will store your custom modules. This directory will contain the Python files for your modules. Let’s call it library. 2. Create Your Module File: Inside the library director... --- ## Decoding Ansible Syntax Errors: A Troubleshooting Guide URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-syntax-error Description: Discover practical solutions for resolving syntax errors in Ansible playbooks through live Playbooknstrations and troubleshooting guidance. ## Introduction Today we're going to talk about Ansible troubleshooting and specifically about Syntax Errors. ## Demo The best way of talking about Ansible troubleshooting is to jump into a live Playbook to show you practically the syntax error and how to solve it! ## Error Code **report.txt:** [code example] **syntax_error.yml:** [code example] ## Error Execution Output: [code example] ## Fix Code **syntax_fix.yml:** [code example] ## Fix Execution Output: [code example] Code with ❤️ in GitHub ## Conclusion Now you know better how to troubleshoot the Ansible Syntax Error. --- ## Decrypt Ansible Vault — Complete ansible-vault Guide URL: https://www.ansiblebyexample.com/articles/decrypt-an-ansible-vault-ansible-vault Description: Decrypt Ansible Vault files with ansible-vault decrypt. Complete guide covering password files, vault IDs, inline encrypted variables, and CI/CD. ## Introduction `ansible-vault decrypt` converts an encrypted vault file back to plaintext. This is essential for editing secrets, migrating to a new encryption method, or debugging vault-related issues. This guide covers all decryption methods — interactive, password files, vault IDs, and CI/CD automation. ## Prerequisites `ansible-vault` is included in every Ansible installation — no separate install needed. [code example] ## Basic Decryption ### Interactive (Prompt for Password) [code example] **Before:** [code example] **After:** [code example] ### With Password File [code example] ### With Environment Variable [code example] ## Decrypt to stdout (Don't Modify File) View encrypted content without changing the file: [code example] Or decrypt to a different file: [code example] ## Vault IDs (Multiple Passwords) When using different passwords for different environments: [code example] ## Decrypt Inline Encrypted Variables When only specific variables are encrypted (not the whole file): [code example] View the decrypted value: [code example] ## Using Decryption in Playbooks You don't need to manually decrypt files to use them in playbooks: [code example] ### ansible.cfg Configuration [code example] Now all vault operations work without flags: [code example] ## Script-Based Password Source For dynamic password retrieval (e.g., from a password manager): [code example] [code example] ## CI/CD Patterns ### GitHub Actions [code example] ###... --- ## Delete a group — Ansible module group URL: https://www.ansiblebyexample.com/articles/delete-a-group-ansible-module-group Description: How to delete the \ Step-by-step Ansible tutorial with practical examples and best practices."example\" group or verify that is not present on your. ## How to delete a group in Linux with Ansible? ## Ansible deletes a group account - `ansible.builtin.group` - Add or remove groups Today we're talking about the Ansible module group. The full name is ansible.builtin.group, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years. It adds or removes groups. It supports a huge variety of Linux distributions and macOS. It relies on three Linux commands: `groupadd`, `groupdel` and `groupmod`. For Windows, use the `ansible.windows.win_group` module instead. ## Parameters - name string - group name - state string - present/absent - local string - "local" command alternatives This module has some parameters to perform some tasks. The only required is "name", which is the group name. The "state" parameter allows us to create or delete a group, in our use case set to "absent" to delete a group. The "local" parameter allows using the "local" command alternatives on platforms that implement it if you have a central authentication system. ## Playbook Let's jump in a real-life Ansible Playbook to delete a group. ### code - group_delete.yml [code example] ### execution output [code example] ### verification [code example] code with ❤️ in GitHub ## Conclusion Now you know how to delete a group in Linux with Ansible. --- ## Delete a VMware Virtual Machine Snapshot — Ansible module vmware_guest_snapshot URL: https://www.ansiblebyexample.com/articles/delete-a-vmware-virtual-machine-snapshot-ansible-module-vmware-guest-snapshot Description: How to automate the delete of snapshot named “Ansible Managed Snapshot” in a VMware Virtual Machine “myvm” Ansible Playbook and vmware_guest_snapshot. ## How to Delete a VMware Virtual Machine Snapshot with Ansible? ## Ansible Delete a VMware Virtual Machine Snapshot - `community.vmware.vmware_guest_snapshot` - Manages virtual machines snapshots in vCenter Let's talk about the Ansible module `vmware_guest_snapshot`. The full name is `community.vmware.vmware_guest_snapshot`, which means that is part of the collection of modules to interact with VMware, community-supported. It manages virtual machine snapshots in vCenter. ## Parameters - hostname string / username string / password string / datacenter string / validate_certs boolean - connection details - state string - present / absent / revert / remove_all - remove_children boolean - no/yes - snapshot_name string description string - Name/description of the virtual machine to work with The following parameters are useful in order to Take a VMware Virtual Machine Snapshot using the module `vmware_guest_snapshot`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the desired snapshot state, in this case, "absent" to delete a snapshot. You could also manage a snapshot with the same Ansible module. If you want to remove a snapshot you could also remove all the dependent snapshots using the parameter `remove_children`. You need to specify the exact sna... --- ## Deploy Apache HTTPD on Docker Container with Ansible URL: https://www.ansiblebyexample.com/articles/deploy-apache-web-server-in-a-docker-container-for-debian-like-systems-ansible-modules-docker-image-and-docker-container Description: Automate the deployment of Apache HTTPD in a Docker container using Ansible. Manage system packages, Docker images, and web content effortlessly. ## How to Setup Apache Web Server in a Docker Container for Debian-like systems with Ansible? ## Setup Apache Web Server in a Docker Container for Debian-like systems - install packages => `ansible.builtin.apt` - docker py module => `ansible.builtin.pip` - pull image => `community.docker.docker_image` - document root => `ansible.builtin.file` - custom index.html => `ansible.builtin.copy` - run container => `community.docker.docker_container` Today we're talking about how to deploy a web server apache httpd in a Docker Container for Debian-like Linux systems. The full process requires six steps that you could automate with different Ansible modules. Firstly you need to install some python packages and dependencies using the `ansible.builtin.apt` Ansible module. Secondly, you need to install the Docker Module for Python using the `ansible.builtin.pip` Ansible module. Thirdly, you need to pull the image for the docker hub registry using the `community.docker.docker_image` Ansible module. Fourthly, you need to create the document root with the right permission with the `ansible.builtin.file` module. Fifty, you need to create the custom index.html with `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Finally, you could run the `webserver` container setting the right port and volume settings using the `community.docker.docker_container` Ansible module. ## Links - httpd image on docker hub - community.docker.docker_image - communit... --- ## Deploy Apache HTTPD with Podman Using Ansible Playbook URL: https://www.ansiblebyexample.com/articles/deploy-apache-web-server-in-a-podman-container-for-redhat-like-systems-ansible-modules-podman-image-and-podman-container Description: Automate Apache HTTPD deployment in a Podman container with Ansible. Manage Podman installation, image pulling, and container configuration. ## How to Setup Apache Web Server in a Podman Container for RedHat-like systems with Ansible? ## Setup Apache Web Server in a Podman Container for RedHat-like systems - install packages => `ansible.builtin.yum` - pull image => `containers.podman.podman_image` - run container => `containers.podman.podman_container` Today we're talking about how to Deploy a web server apache httpd in a Podman Container for RedHat-like Linux systems. The full process requires three steps that you could automate with different Ansible modules. Firstly you need to verify that `podman` and its dependency is successfully installed on the target system using the `ansible.builtin.yum` Ansible module. Secondly, you need to pull the image for the container hub registry using the `containers.podman.podman_image` Ansible module. Finally, you could run the `webserver` container setting the right port and settings using the `containers.podman.podman_image` Ansible module. ## Links - containers.podman.podman_image - containers.podman.podman_container - httpd image ## Playbook How to Setup Apache Web Server in a Podman Container for RedHat-like systems with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to set up Apache Web Server in a Podman Container for RedHat-like systems with Ansible. --- ## Deploy Kubernetes Resources with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/apply-multiple-yaml-files-at-once-on-kubernetes-k8s-or-openshift-ocp-ansible-module-k8s-and-lookup-plugin-fileglob Description: Learn how to deploy Kubernetes resources using Ansible. Follow this guide to create namespaces, pods, and services with an Ansible playbook. ## How to Apply Multiple Yaml Files at Once on Kubernetes K8s or OpenShift OCP with Ansible? ## Ansible Apply Multiple YAML Files at Once on K8s or OCP - `kubernetes.core.k8s` - Manage Kubernetes (K8s) objects - `ansible.builtin.fileglob` - list files matching a pattern Let's talk about the Ansible module `k8s` and the Ansible lookup plugin fileglob. The full name is `kubernetes.core.k8s`, which means that is part of the collection of modules of Ansible to interact with Kubernetes and Red Hat OpenShift clusters. It manages Kubernetes (K8s) objects. Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources. The full name is `ansible.builtin.fileglob`, it's part of `ansible-core` and is included in all Ansible installations. The purpose of the lookup plugin is to list files matching a pattern. ## k8s module parameters - `name` string - object name - `namespace` string - namespace - `state` string - present/absent/patched - `definition` string - YAML definition - `src` path - path for YAML definition There is a long list of parameters of the `k8s` module. Let me summarize the most used. Most of the parameters are very generic and allow you to combine them for many use-cases. The `name` and `namespace` specify object name and the object namespace. The `api_version` parameter specifies the Kubernetes API version, the default is "v1" for version 1. The `state` like for ot... --- ## Deploy Squid Proxy on RedHat Systems with Ansible URL: https://www.ansiblebyexample.com/articles/deploy-a-proxy-server-squid-on-redhat-like-systems-ansible-modules-yum-template-service-and-firewalld Description: Learn to deploy and configure a Squid proxy server on RedHat-like systems using Ansible. Follow our step-by-step guide with simple Ansible code examples. ## How to deploy a proxy server squid on RedHat-like systems with Ansible? ## Deploy a proxy server squid on RedHat-like - install packages => `ansible.builtin.yum` - configuration => `ansible.builtin.template` - start service => `ansible.builtin.service` - open firewall => `ansible.posix.firewalld` Today we're talking about how to deploy a proxy server squid on RedHat-like Linux systems. The full process requires four steps that you could automate with different Ansible modules. Firstly you need to install the `squid` package and dependency using the `ansible.builtin.yum` Ansible module. Secondly, you need to create the custom configuration with the `ansible.builtin.template` Ansible module. Thirsty you need to start the `squid` service and enable it on boot and all the dependant using the `ansible.builtin.service` Ansible module. Fourthly you need to open the relevant firewall service-related ports using the `ansible.posix.firewalld` Ansible module. ## Playbook Deploy a proxy server squid on RedHat-like with Ansible Playbook. ### code - proxy_redhat.yml [code example] - templates/squid.conf.j2 [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to deploy a proxy server squid on RedHat-like with Ansible. --- ## Detect Apache Log4j CVE-2021-44228 with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/vulnerability-scanner-detector-log4shell-remote-code-execution-log4j-cve-2021-44228-ansible-log4j-cve-2021-44228 Description: Use Ansible to automate the detection of Apache Log4j CVE-2021-44228 vulnerability. Follow this guide to set up and run detection scripts efficiently. ## How to automate the Detector Log4Shell Remote Code Execution Log4j (CVE-2021–44228)? ## Log4Shell Remote Code Execution Log4j (CVE-2021–44228) Remember 2014? Heartbleed was a bug in OpenSSL, the most popular open-source code library for Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols usage in encrypting websites and software. At the time the flaw allowed to read confidential information allowing the hackers to trick a vulnerable web server with encryption keys. Back to the present! Log4j - the Java program compromised by the Log4Shell bug - is a widely used, multi-platform open-source Java logging framework library developed and maintained under the volunteer Apache Software Foundation. Log4j is widely used on servers to record users' activities to analyze later by security or development teams. Hackers could use the Log4Shell flaw to access sensitive information on a variety of devices, plant ransomware attacks, and take over machines to mine cryptocurrencies. The vulnerability was discovered almost by happenstance when Microsoft announced it had found suspicious activity in Minecraft: Java Edition, a popular video game it owns. The flaw was officially founded by Chen Zhaojun of Alibaba's Cloud Security Team on the 24th of November 2021. Some estimation to Wiz and EY, the vulnerability affected 93% of enterprise cloud environments. Affected commercial services include Amazon Web Services, Cloudflare, iCloud, Minecraft: Java Edition, Steam, Tencent... --- ## Discover Ansible Automation at Cloud Native London 2023 URL: https://www.ansiblebyexample.com/articles/cloud-native-london-december-2023 Description: Join Cloud Native London 2023 to explore Ansible automation with Luca Berton, AWS observability with Nagaraju Basavaraju, and cloud strategies with. ## Introduction The Cloud Native London meetup promises to be an exciting gathering of professionals immersed in the world of containers, Kubernetes, open source, and more. Among the distinguished speakers, Luca Berton, an Ansible Automation Expert, will be taking the stage to share his insights and experiences in building the Ansible Pilot Community. ## Livestream recording {{}} ## The Journey to Success with Ansible Automation In his presentation, Luca Berton aims to empower creative professionals in Automation, DevOps, Cloud Engineering, System Administration, and IT to excel with Ansible technology. His talk promises to provide valuable insights, behind-the-scenes stories, and lessons learned from establishing the Ansible Pilot Community. Attendees will delve into the world of Ansible automation and learn how to automate more efficiently day by day. One highlight of Luca’s achievements is the publication of the best-selling Ansible By Example(s) practical book series. Notable works include “Ansible for VMware by Examples” and “Ansible for Kubernetes by Examples.” These books serve as guides for professionals seeking practical, hands-on expertise in leveraging Ansible for different technology stacks. Luca Berton’s expertise extends beyond his role as an Ansible Automation Expert. With over 15 years of experience as a System Administrator, he has honed his skills in Infrastructure Hardening and Automation. Luca has made significant contributions to the open-source comm... --- ## Discover Ansible Self-Paced Labs: Hands-On Training Guide URL: https://www.ansiblebyexample.com/articles/ansible-resources-ansible-self-paced-labs Description: Explore Ansible Self-Paced Labs for hands-on experience with Ansible. Learn to write playbooks and enhance your skills with interactive training sessions. # Discover Ansible Self-Paced Labs: Hands-On Training Guide ## Introduction Discover Ansible Self-Paced Labs: Hands-On Training Guide. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Discover Ansible Self-Paced Labs: Hands-On Training Guide requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6... --- ## Download and Use Ansible Galaxy Collection — ansible-galaxy and requirements.yml URL: https://www.ansiblebyexample.com/articles/download-and-use-ansible-galaxy-collection-ansible-galaxy-and-requirements Description: Learn how to download and use the Ansible Galaxy Collection community.general with ansible-core in a system, including a real-life example. ## How to Download and Use Ansible Galaxy Collection with ansible-galaxy and requirements.yml? I’m going to show you a live Playbook with some simple Ansible code. ## What is an Ansible Collection? - distribution format for Ansible content - it contains the package and distributes playbooks, roles, modules, and plugins using collections - easy to download and share via Ansible Galaxy An Ansible **Collection** is a distribution format for Ansible content. It solves one problem and contains all the relevant contains the package and distributes playbooks, roles, modules, and plugins. For Users, the Ansible Collection is easy to download and share via Ansible Galaxy. For Developers the Ansible Collection is easy to upload and share via Ansible Galaxy. Plus an Ansible Collection has a defined standard directory structure and format. ## What is Ansible Galaxy? - Ansible Galaxy The website is available at the URL https://galaxy.ansible.com/. The search engine, Tags, and Platform make it easy to find any content inside. I recommend you carefully evaluate the quality of content before using it in your system. Quality indicators are usually the quality assurance of code, the supported operating systems and platforms, the documentation, the release numbers, the presence of Changelog, the number of downloads, and the author or creator. Please notice that the website contains Ansible Roles and Ansible Collections. Today we’re focusing on Ansible Role content. ## Links - Ansible Co... --- ## Download and Use Ansible Galaxy Role — ansible-galaxy and requirements.yml URL: https://www.ansiblebyexample.com/articles/download-and-use-ansible-galaxy-roles-ansible-galaxy-and-requirements Description: Learn how to download and use the Ansible Galaxy Role lucab85.ansible_role_log4shell with ansible-core, including a step-by-step example. How to Download and Use Ansible Galaxy Role with ansible-galaxy and requirements.yml? I’m going to show you a live Playbook with some simple Ansible code. ## What is an Ansible Role? - re-usable Ansible artifacts - one role contains tasks, variables, defaults, handlers, modules, or other plugins - easy to download and share via Ansible Galaxy An Ansible **Role** is a set of re-usable Ansible artifacts. It solves one problem and contains all the relevant tasks, variables, defaults, handlers, modules, or other plugins. For Users, the Ansible Role is easy to download and share via Ansible Galaxy. For Developers the Ansible Role is easy to upload and share via Ansible Galaxy. Plus an Ansible role has a defined standard directory structure and format. ## What is Ansible Galaxy? - Ansible Galaxy - lucab85/ansible_role_log4shell The website is available at the URL https://galaxy.ansible.com/. The search engine, Tags, and Platform make it easy to find any content inside. I recommend you carefully evaluate the quality of content before using it in your system. Quality indicators are usually the quality assurance of code, the supported operating systems and platforms, the documentation, the release numbers, the presence of Changelog, the number of downloads, and the author or creator. Please notice that the website contains Ansible Roles and Ansible Collections. Today we’re focusing on Ansible Role content. ## Links - https://docs.ansible.com/ansible/latest/user_guide/playbook... --- ## Download Windows 10 Professional ISO File with Ansible URL: https://www.ansiblebyexample.com/articles/download-windows-10-professional-iso-file-officially Description: Get the official Windows 10 Professional ISO file. Learn how to download, create bootable media, install or upgrade, and automate the process with Ansible. When upgrading or performing a clean installation of **Windows 10 Professional**, having access to the official **ISO file** is crucial. With the added power of **Ansible automation**, you can simplify downloading, creating bootable media, and deploying installations across multiple systems efficiently. --- ## What Is a Windows 10 Professional ISO File? An **ISO file** is a digital replica of an optical disc that contains all the installation files for the Windows operating system. The Windows 10 Professional ISO file enables you to: - Perform a clean installation of Windows 10 Professional. - Upgrade from another version of Windows. - Create bootable installation media such as a USB drive or DVD. - Automate ISO handling and deployment using Ansible. --- ## Why Use Ansible with Windows 10 Professional ISO? - **Automation at Scale**: Manage downloads, create media, and deploy installations across multiple devices programmatically. - **Consistency**: Avoid manual errors by using repeatable Ansible playbooks. - **Efficiency**: Save time by automating repetitive tasks like formatting USB drives or setting up installations. --- ## How to Download the Windows 10 Professional ISO File ### Manual Steps 1. **Visit the Microsoft Download Page**: - Go to the Microsoft Software Download page. 2. **Select Edition**: - Choose "Windows 10" and ensure that the Professional edition is included in your version. 3. **Download the Media Creation Tool**: - Click "Download Tool... --- ## Dynamic Data Construction in Ansible: Managing Users and Groups URL: https://www.ansiblebyexample.com/articles/dynamic-data-construction-in-ansible Description: Explore a practical guide on dynamically managing user accounts and groups in Ansible. Learn how to use Jinja2 templates and set_fact for scalable. Dynamically constructing and managing data structures is a crucial skill in Ansible automation, especially for tasks that require flexible and reusable configurations. In this article, we’ll explore this concept using a practical example: managing user accounts and groups on Linux systems. ## Scenario: Dynamic User and Group Management Imagine you have a `user_list` variable defining multiple users and their associated groups: [code example] Your goal is to: - Dynamically construct a user and group data structure. - Use this structure to manage user accounts and assign them to the appropriate groups. ## The Ansible Playbook Here’s how you can achieve this using `set_fact` and Jinja2 templating: [code example] ## Key Components 1. **Data Construction with `set_fact`**: - The `set_fact` task dynamically builds `user_data` as a list of dictionaries, each containing: - `name`: The username. - `groups`: The list of groups. Example output: [code example] 2. **Dynamic User Management**: - The `ansible.builtin.user` module iterates through `user_data`, creating users and assigning them to their respective groups. The `groups` field is converted to a comma-separated string using `join(',')`. 3. **Debugging**: - The `debug` task ensures that the `user_data` structure is correct before applying it. ## Benefits of This Approach - **Dynamic and Reusable**: - Adapts to changes in the input `user_list` without modifying the playbook logic. - **Centra... --- ## Edit Single Lines in Files — Ansible lineinfile Module Guide URL: https://www.ansiblebyexample.com/articles/edit-single-line-text-ansible-module-lineinfile Description: Master the Ansible lineinfile module — insert, replace, and remove single lines in files. Complete guide with regexp matching, validation, backreferences,. ## Introduction The `ansible.builtin.lineinfile` module edits single lines in text files — inserting, replacing, or removing lines based on regular expressions. It's the go-to module for configuration file changes where you need to modify one specific setting without templating the entire file. For multi-line edits, use `blockinfile`. For full file management, use `template`. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `path` | string | Yes | File path to edit | | `line` | string | No* | Text to insert or replace | | `regexp` | string | No | Regex to find the line to replace | | `state` | string | No | `present` (default) or `absent` | | `insertafter` | string | No | Insert after this regex (or `EOF`) | | `insertbefore` | string | No | Insert before this regex (or `BOF`) | | `create` | bool | No | Create file if it doesn't exist | | `backup` | bool | No | Create a backup before editing | | `validate` | string | No | Command to validate after editing | | `owner` | string | No | File owner | | `group` | string | No | File group | | `mode` | string | No | File permissions | *Required when `state: present`. ## Basic Usage ### Replace a Line [code example] This finds any line starting with `PasswordAuthentication` and replaces it entirely. ### Insert a Line at End of File [code example] If the line already exists, no change is made (idempotent). ### Remove a Line [code example] ## Practical Examp... --- ## Effective Techniques to Clear Host Errors in Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/effective-techniques-to-clear-host-errors-in-ansible-playbooks Description: Discover practical methods to handle and clear host errors in Ansible, ensuring smooth automation and effective error management in your infrastructure. ## Handling Host Errors in Ansible In any automation system, handling errors efficiently is crucial to ensure smooth operations. Ansible, a popular IT automation tool, provides several mechanisms to manage errors during playbook execution. One common scenario is the need to clear or handle host errors to maintain an efficient and error-free automation environment. Below, we'll explore the strategies to manage host errors effectively in Ansible, including retry mechanisms, failure conditions, and error handling practices. ## Understanding Host Errors Host errors in Ansible typically occur when there is an issue connecting to a host or executing a task on a host. These can include connection failures, unreachable hosts, task failures, or issues with privilege escalation. Ansible marks these hosts as "failed" and, by default, will not proceed with subsequent tasks for those hosts unless instructed otherwise. ## Strategies to Clear Host Errors 1. **Ignore Errors Using `ignore_errors`:** You can tell Ansible to ignore errors for specific tasks using the `ignore_errors` directive. This is useful when you want the playbook to continue executing even if a particular task fails. [code example] 2. **Handle Failed Hosts with `rescue` and `always`:** Ansible’s `block`, `rescue`, and `always` directives provide structured error handling. `rescue` runs if there is a failure within a block, and `always` runs regardless of the block’s outcome. [code example] 3. **Use t... --- ## Efficient Automation with Ansible URL: https://www.ansiblebyexample.com/articles/efficient-automation-with-ansible Description: A Practical Guide for DevOps Professionals by Michael Knyazev, Gineesh Madapparambath, and Nicholas Wong. With tested, real-world examples. **Efficient Automation with Ansible: A Practical Guide for DevOps Professionals** *By Michael Knyazev, Gineesh Madapparambath, and Nicholas Wong* ## Introduction In the fast-paced world of technology, automation has become an indispensable tool for streamlining processes, enhancing efficiency, and delivering value to customers. To guide professionals through the intricacies of automation, Red Hat presents a comprehensive and practical guide titled "Efficient Automation with Ansible." Authored by experts in the field, including Michael Knyazev, Gineesh Madapparambath, and Nicholas Wong, this 48-page resource is a valuable asset for DevOps professionals, engineers, architects, product owners, and operations managers. ### Overview of the Guide The guide employs a case study as its foundation, providing real-world scenarios and practical insights to support a broad community of automation specialists. It offers a hands-on approach, allowing readers to apply the acquired knowledge immediately in their respective environments. The content is structured to simulate automation progression from the initial stages to the delivery of a Minimum Viable Product (MVP), making it accessible and applicable for a diverse audience. ### Practical Implementation The guide's style is deeply practical, with alternating sections that introduce corresponding practices and provide focused recommendations. These insights are complemented by a real-life "sample project" of automation, offering a ... --- ## Efficient Web Server Setup Using Ansible Playbook URL: https://www.ansiblebyexample.com/articles/deploy-a-web-server-apache-httpd-on-redhat-like-systems-ansible-modules-yum-copy-service-firewalld Description: Set up a web server effortlessly with our Ansible playbook tutorial. Follow step-by-step instructions for installing and configuring HTTPD service. ## How to deploy a webserver apache httpd on RedHat-like systems with Ansible? ## Deploy a web server apache httpd on RedHat-like systems - install packages => `ansible.builtin.yum` - custom index.html => `ansible.builtin.copy` - start service => `ansible.builtin.service` - open firewall => `ansible.posix.firewalld` Today we're talking about how to Deploy a web server apache httpd on RedHat-like Linux systems. The full process requires four steps that you could automate with different Ansible modules. Firstly you need to install the `httpd` package and dependency using the `ansible.builtin.yum` Ansible module. Secondly, you need to create the custom index.html with `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Thirsty you need to start the `httpd` service and enable on boot and all the dependant using the `ansible.builtin.service` Ansible module. Fourthly you need to open the relevant firewall service-related ports using the `ansible.posix.firewalld` Ansible module. ## Playbook Deploy a web server apache httpd on RedHat-like systems with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to deploy a web server apache httpd on RedHat-like systems with Ansible. --- ## Efficient YouTube Playlist Video Metadata Extraction URL: https://www.ansiblebyexample.com/articles/automating-youtube-playlist-information-retrieval-with-python-pytube-library Description: Learn to automate YouTube playlist metadata extraction using Python. Efficiently retrieve video titles and IDs, saving time and effort in data collection. ## Introduction YouTube is a vast repository of videos covering a multitude of topics. Sometimes, you may find yourself needing to gather information about multiple videos from a playlist efficiently. In this article, we will explore how to use Python's Pytube library to automate the retrieval of video details from a YouTube playlist. ## Setting Up Pytube Pytube is a lightweight library that enables you to access YouTube videos and playlists easily. Before you begin, make sure to install the Pytube library by running the following command: [code example] Now that we have Pytube installed, let's dive into a simple script that fetches details from a YouTube playlist. ## The Script [code example] Understanding the Script: 1. **Importing Libraries:** - We import the `time` module to measure the script's execution time. - We import the `YouTube` and `Playlist` classes from the Pytube library. 2. **Providing Playlist Link:** - Replace the `playlist_link` variable with the URL of the YouTube playlist you want to analyze. 3. **Fetching Video URLs:** - We create a `Playlist` object using the provided link and extract all video URLs from the playlist. 4. **Retrieving Video Details:** - For each video URL, we extract the video ID and title using the `YouTube` class from Pytube. 5. **Printing and Recording Information:** - The script prints the video ID and title for each video in the playlist. - It also records the video titles in the `video_titles` lis... --- ## Enhance Business Efficiency with Retrieval-Augmented Generation (RAG) URL: https://www.ansiblebyexample.com/articles/enhance-business-efficiency-with-retrieval-augmented-generation Description: Learn how Retrieval-Augmented Generation (RAG) boosts business efficiency by delivering accurate, context-aware AI responses for better customer support. ## Introduction In the ever-evolving landscape of artificial intelligence (AI), finding the right information quickly and accurately is crucial. Whether you're working in customer support, data analysis, or content creation, the need for precise and context-aware responses has never been higher. This is where Retrieval-Augmented Generation (RAG) comes into play—a cutting-edge AI technology that combines the power of information retrieval with advanced generative models to deliver top-tier results. ## What is Retrieval-Augmented Generation (RAG)? At its core, RAG is an AI framework designed to enhance the capabilities of Large Language Models (LLMs) by integrating a two-part system: the **Retriever** and the **Generator**. 1. **The Retriever**: Think of the Retriever as a highly efficient search engine. When a query is made, it scours through vast amounts of data—whether it's internal databases, external sources, or both—to find the most relevant information. The Retriever's job is to ensure that the most accurate and contextually appropriate data is available for the next step. 2. **The Generator**: Once the Retriever has gathered the relevant information, the Generator steps in. This component processes the retrieved data and generates a response that is not only accurate but also context-aware, making it feel more human-like and tailored to the specific query. This combination of retrieval and generation is what makes RAG so powerful. By pulling in only the most perti... --- ## Enhancing Ansible Documentation URL: https://www.ansiblebyexample.com/articles/enhancing-ansible-documentation Description: Join the Initiative to Enhance Module Connections through 'See Also' Suggestions. With clear, copy-paste, step-by-step examples. ## Introduction In a recent development within the Ansible community, an initiative has been taken to enhance the usefulness and comprehensiveness of module documentation through the expansion of the "See also" sections. This initiative, brought to light by the community team at Red Hat during CfgMgmtCamp 2024, aims to leverage community insights to refine and extend documentation to better serve users' needs. ## The "See Also" Section: A Gateway to Related Modules The "See also" section in Ansible documentation plays a crucial role in guiding users through the vast landscape of modules available within Ansible's ecosystem. It directs users to related modules that may serve similar functions or complement the functionality of the module being viewed. This section is especially beneficial for users navigating through modules with overlapping capabilities or those designed for specific use cases across different platforms. For example, the `ansible.builtin.copy` module's documentation includes a "See also" section that points users towards related modules, offering alternatives or supplementary options that could better fit their automation tasks. ## Call to Action: Empowering the Community to Contribute Recognizing the potential for improvement in making these connections more visible and useful, the Ansible community team has opened the floor for suggestions from the user community. By contributing ideas for modules that share similarities or have relational functionali... --- ## Enhancing Ansible Role Development with Best Practices with ansible-later URL: https://www.ansiblebyexample.com/articles/enhancing-ansible-role-development-with-best-practices-with-ansible-later Description: Discover ansible-later, a fast and user-friendly linting tool for Ansible roles. Learn about its installation, configuration, and default settings to. ## Introduction When it comes to developing Ansible roles in a collaborative environment, adhering to coding and best practices is essential. It ensures that roles are readable, maintainable, and minimizes troubleshooting time. `ansible-later` is a valuable tool designed to serve as a best practice scanner and linting tool for Ansible resources. ## What is ansible-later? `ansible-later` focuses on providing a fast and user-friendly linting experience for Ansible roles. While it may not offer the depth of analysis provided by some other tools like `ansible-lint`, it serves as an excellent choice for quickly identifying and enforcing best practices within your Ansible codebase. ### Installation To get started with `ansible-later`, ensure that Ansible is installed on your system. You can install `ansible-later` using `pip` with one of the optional dependency groups – either `ansible` or `ansible-core`: - install for the current user [code example] - install system-wide [code example] ## Configuration By default, `ansible-later` ships with configurations that are suitable for most users. However, customization is possible through YAML configuration files or CLI options. The configuration options include settings for custom Ansible modules, variable formatting rules, allowed literal bools, and more. It follows a hierarchy for configuration, with CLI options having the highest priority, allowing users flexibility in setting their preferences. ## Default Settings The def... --- ## EU Cyber Resilience Act (CRA) and Ansible — What You Need to Know URL: https://www.ansiblebyexample.com/articles/eu-cyber-resilience-act-cra-and-ansible Description: The EU Cyber Resilience Act (CRA) introduces mandatory cybersecurity requirements for software products. Learn how it impacts Ansible, Red Hat's Open. ## Introduction The European Union's Cyber Resilience Act (CRA), officially Regulation (EU) 2024/2847, introduces mandatory cybersecurity requirements for all products with digital elements sold in the EU market — including software. For the Ansible ecosystem, this represents a significant shift from voluntary best-effort security practices to formal compliance obligations. Red Hat has announced it will serve as the Open Source Software Steward for Ansible, absorbing the administrative compliance burden while shielding community volunteers from regulatory liability. This article explains what the CRA requires, its timeline, how it impacts Ansible contributors, maintainers, and enterprise users, and what you should prepare for. ## What Is the Cyber Resilience Act? The CRA is EU legislation that establishes baseline cybersecurity standards for hardware and software products throughout their lifecycle. It targets three goals: 1. **Reduce vulnerabilities** in digital products before they reach the market 2. **Ensure cybersecurity is maintained** throughout a product's entire lifecycle 3. **Enable users to make informed decisions** about the security of products they use ### Key Requirements | Requirement | Description | |---|---| | Secure by default | Products must be designed with security as a core principle | | Vulnerability management | Manufacturers must handle, document, and remediate vulnerabilities | | Incident reporting | Actively exploited vulnerabilities must be... --- ## Event-Driven Ansible — IT Operations URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-2-4-event-driven-ansible-controller-installation Description: Automate IT operations with Event-Driven Ansible (EDA). Rulebooks, event sources, triggers, ServiceNow integration, and real-time remediation examples. ## Event-Driven Ansible In today’s rapidly evolving digital landscape, organizations face the challenge of managing complex IT environments while striving to deliver innovative solutions. Manual tasks and repetitive operations can consume valuable time and resources, hindering teams from focusing on strategic initiatives. To address these issues, Red Hat® Ansible® Automation Platform introduces Event-Driven Ansible. This event-handling capability empowers organizations to automate time-consuming tasks and respond to changing conditions across any IT domain. Event-Driven Ansible enables processing events containing critical intelligence about the IT environment. It intelligently determines the appropriate response to each event and executes automated actions to address or remediate them. While IT service management tasks, such as ticket enhancement, remediation, and user management, are excellent starting points, Event-Driven Ansible offers the flexibility to automate a wide range of tasks throughout the IT infrastructure. One of the key benefits of Event-Driven Ansible is its ability to work as a powerful, unified platform for automation. Organizations can choose between manual or automatic automation styles, all within a single, cohesive platform. This versatility allows teams to work smarter and deliver IT services precisely while freeing time to focus on critical and innovative work that drives value for the business. By leveraging event-driven automation, organization... --- ## Event-Driven Ansible (EDA): Automate Responses to Events URL: https://www.ansiblebyexample.com/articles/event-driven-ansible-eda-automate-responses-to-events Description: Introduction to Event-Driven Ansible (EDA) — automatically trigger playbooks from webhooks, monitoring alerts, log events, and system changes. Learn. ## What is Event-Driven Ansible? **Event-Driven Ansible (EDA)** automatically triggers actions in response to events — monitoring alerts, webhook calls, log patterns, and system changes. Instead of running playbooks manually, events trigger them. [code example] ## How It Works ### 1. Event Sources Sources generate events from external systems: - **Webhooks** — GitHub, GitLab, Jira, PagerDuty - **Monitoring** — Prometheus Alertmanager, Nagios, Zabbix - **Message queues** — Kafka, RabbitMQ - **Cloud events** — AWS EventBridge, Azure Event Grid - **Log watchers** — file changes, syslog - **Custom sources** — any Python plugin ### 2. Rulebooks Rulebooks define what events to listen for and what actions to take: [code example] ### 3. Actions What happens when a condition matches: - `run_playbook` — Execute an Ansible playbook - `run_module` — Run a single module - `set_fact` — Store data for later rules - `post_event` — Forward to another rulebook - `print_event` — Log the event (debugging) - `noop` — Do nothing (useful for testing) ## Practical Examples ### Auto-Remediate Disk Full [code example] ### Auto-Scale on High CPU [code example] ### Restart Service on Failure [code example] ### GitHub Webhook Deployment [code example] ## Getting Started ### Install [code example] ### Run a Rulebook [code example] ## EDA vs Traditional Ansible | Aspect | Traditional | Event-Driven | |--------|------------|--------------| | **Trigger** | Manual / cron / CI | Autom... --- ## Event-Driven Ansible 2026 — 12 New Collections and Platform Updates URL: https://www.ansiblebyexample.com/articles/event-driven-ansible-2026-12-new-collections-and-platform-updates Description: Everything new in Event-Driven Ansible: 12 content collections, Azure and AWS event bus integration, gateway-only architecture, and PostgreSQL 17. # Event-Driven Ansible 2026 — 12 New Collections and Platform Updates ## Introduction Event-Driven Ansible (EDA) in 2026 expands from a niche reactive automation tool to a full enterprise event processing platform. With 12 new source collections, cloud event bus integration, and architectural improvements, EDA handles everything from infrastructure alerts to business process automation. ## 12 New Event Source Collections ### Cloud Providers [code example] [code example] ### Monitoring & Observability [code example] ### ITSM & Collaboration [code example] ### DevOps & CI/CD [code example] ## Platform Architecture Changes ### Gateway-Only Architecture (New) [code example] Benefits: - Single TLS endpoint - Unified authentication - Centralized audit logging - Simplified firewall rules ### Infrastructure Updates | Component | Old | New | |-----------|-----|-----| | PostgreSQL | 13 | **17** | | Django | 4.2 | **5.2 LTS** | | Python | 3.9 | **3.11** | | Redis | 6 | **7** | ## Rulebook Best Practices [code example] ## Common Patterns ### Auto-Remediation with Escalation [code example] ### Event Correlation [code example] ## Troubleshooting | Issue | Fix | |-------|-----| | Events not received | Check source plugin connectivity and auth | | Rule never triggers | Verify condition matches event structure (`-vvv`) | | Duplicate actions | Add `throttle` with `once_within` | | High memory usage | Limit event buffer size, add filters at source | ## Best Practices... --- ## Event-Driven Ansible: Revolutionizing IT Automation URL: https://www.ansiblebyexample.com/articles/event-driven-ansible Description: Discover how Event-Driven Ansible revolutionizes IT automation by enabling real-time responses to changes, ensuring agility, efficiency, and consistency. ## Event-Driven Ansible: Revolutionizing IT Automation Event-Driven Ansible (EDA) represents a significant leap forward in the realm of IT automation, offering a dynamic and responsive approach to managing IT environments. This article delves into what Event-Driven Ansible is, its components, benefits, and practical applications. ## What is Event-Driven Ansible? Event-Driven Ansible is a feature within the Red Hat Ansible Automation Platform that enables automation to be triggered by specific events. This allows IT operations to become more responsive and efficient by automating the response to changes, alerts, and conditions within the IT environment. The core of Event-Driven Ansible is the Ansible Rulebook, a YAML document that defines the rules and actions for automation . ## Key Components of Event-Driven Ansible 1. **Event Sources**: These are the origins of events that trigger automation. Event sources can include webhook events, changes in file status, messages from Kafka topics, or alerts from monitoring tools like Alertmanager . 2. **Rules**: Each event is evaluated against a set of rules defined in the Ansible Rulebook. A rule includes a condition that, when met, triggers an action. This condition could be anything from receiving a specific HTTP status code to a file change event . 3. **Actions**: Actions are the tasks that are executed when the conditions of a rule are met. These can range from running an Ansible playbook to executing specific modules o... --- ## Exciting Ansible Updates: Core, Community, AWX, and DevTools URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-core-community-awx-and-devtools Description: The Ansible ecosystem is buzzing with new releases and updates! Ansible Core 2.17.1 now supports running as a non-root user, while the Community Package. ## Exciting Updates in the Ansible World: Core, Community, AWX, and DevTools Hi friends! We have a lot of exciting news from our favorite automation tool, Ansible. If you're not familiar with it, Ansible originated in the Bull City, Durham. Long story short, everything is summarized in the latest newsletter, but today we’ll dive into the new Ansible Core, the Ansible Community package, the new AWX Operator package, and the Ansible DevTools aimed at creating a wonderful developer experience. ## Ansible Core 2.17.1 Let's start with the meaty part. The Ansible Core is getting an update to release 2.17.1. This update has been eagerly discussed, and there are many exciting features to look forward to. One of the most notable improvements is the ability to run Ansible as a non-root user. This update brings a polished interface that visualizes many underlying processes, providing a solid foundation for all your projects. ## Ansible Community Package 10.0 As usual, a new community package is also being released. Version 10.0 includes numerous bug fixes and is set to be released today, June 18, 2024. This package ensures that the community-driven modules and plugins are up-to-date and reliable for all users. ## AWX Operator 2.19 Additionally, the AWX Operator package is receiving an update to version 2.19. The AWX Operator streamlines the installation and management of AWX, the open-source version of Ansible Tower, making it easier to deploy and manage your automation infrastru... --- ## Execute command on the Ansible host — Ansible localhost URL: https://www.ansiblebyexample.com/articles/execute-command-on-the-ansible-host-ansible-localhost Description: How to execute Ansible command(s) or task(s) on localhost using the connection plugin local and the right ansible internals variables. ## How to Execute command on the Ansible host? When Ansible becomes part of your daily workflow it is natural you would like to automate also task in your local machine. ## Execute command on the Ansible host options - `connection plugin` - `delegate_to: localhost` - `local_action` There are three ways to execute modules and commands on the Ansible Controller host. The first and my favorite is using the connection plugin `local` and applying it to the Ansible Play level of your Playbook. The tricky was is to adjust some ansible variables about the python interpreter. I consider it the best way nowadays. The second way is using the `delegate_to` at the Task level. This has the advantage to delegate only one task to localhost but still needs only the implicit localhost scheme. The third way is using the `local_action` statement. I personally don't like it but it's one alternative as well at Task level, so same as the previous. ## Links - Controlling where tasks run: delegation and local actions - Implicit ‘localhost’ ## Playbook How to Execute command on the Ansible host using connection: local method. ### code [code example] ### execution [code example] ### idempotency [code example] ## Conclusion Now you know how to Execute commands and tasks on the Ansible localhost. You know how to use it based on your use case. --- ## Executing Custom Lookup Plugins in the Ansible Automation Platform URL: https://www.ansiblebyexample.com/articles/executing-custom-lookup-plugins-in-the-ansible-automation-platform Description: How to execute two custom Ansible Lookup Plugins to interact with API and read the contents of files in the local Ansible Controller. ## Introduction Ansible, an open-source automation tool, offers a wide range of built-in modules and plugins to simplify infrastructure management. However, sometimes, you may need to extend its functionality by creating custom plugins tailored to your needs. In this article, we’ll explore the creation of a custom Ansible lookup plugin in Python and execute it in Ansible Controller (part of Ansible Automation Platform). ### What is a Lookup Plugin? Ansible lookup plugins are used to retrieve data dynamically during playbook execution. They allow you to fetch information from various sources, such as databases, APIs, or external files, and use that data in your Ansible tasks. ## Links - https://docs.ansible.com/ansible/latest/dev_guide/developing_plugins.html#lookup-plugins - https://docs.ansible.com/ansible/latest/plugins/lookup.html#lookup-plugins - https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-lookup-plugin-path ## Step by Step To execute a custom Ansible lookup plugin in the Ansible Automation Platform, you’ll need to follow these steps: 1. Create the Custom Lookup Plugin: - Write your custom lookup plugin in Python. You can create a Python script file with the plugin code. - Save the plugin file in a directory named `lookup_plugins` in your Ansible project directory, or you can create a Python package for it. - Ensure that the plugin file has the `.py` extension. 2. Here’s an example of a simple custom lookup plugin: - token.py [... --- ## Expand a Virtual Disk in VMware vSphere Virtual Machine — Ansible module vmware_guest_disk URL: https://www.ansiblebyexample.com/articles/expand-a-virtual-disk-in-vmware-vsphere-virtual-machine-ansible-module-vmware-guest-disk Description: How to automate the expansion from 1GB to 2GB size Virtual Disk connected to VMware Virtual Machine guest named “myvm” using Ansible Playbook. ## How to Expand a Virtual Disk in VMware vSphere Virtual Machine with Ansible? ## Ansible Expand a Virtual Disk in VMware vSphere Virtual Machine - `community.vmware.vmware_guest_disk` - Manage disks related to a virtual machine in a given vCenter infrastructure Let's talk about the Ansible module `vmware_guest_disk`. The full name is `community.vmware.vmware_guest_disk`, which means that is part of the collection of modules to interact with VMware, community-supported. It manages disks related to a virtual machine in a given vCenter infrastructure. ## Parameters - hostname string / username string / password string / datacenter string / validate_certs boolean - connection details - datacenter string - The datacenter name to which the virtual machine belongs to - scsi_controller / unit_number / scsi_type string - SCSI controller details - size / size_kb / size_mb / size_gb / size_tb string - Disk storage size - disk_mode string - persistent / independent_persistent / independent_nonpersistent The following parameters are useful in order to Expand a Virtual Disk in VMware vSphere Virtual Machine using the module `vmware_guest_disk`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora self-explicative parameters: `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the desired disk configuration, in this expansion, a disk is connected ... --- ## Exploring Ansible Playbook Gather Facts for Displaying Network Information URL: https://www.ansiblebyexample.com/articles/exploring-ansible-playbook-gather-facts-for-displaying-network-information Description: Streamlining Network Information Retrieval with Ansible’s Declarative Playbooks using the setup Ansible module. With clear, copy-paste, step-by-step examples. ## Introduction In the realm of IT automation, Ansible stands out as a powerful tool for configuring and managing systems with simplicity and efficiency. Ansible employs a declarative approach to automation, allowing administrators and engineers to define the desired state of their infrastructure without diving into complex scripting languages. In this article, we will dive into a specific Ansible playbook that showcases how to gather and display network information using Ansible’s intuitive playbook syntax. ## Links - https://docs.ansible.com/ansible/latest/collections/ansible/builtin/setup_module.html ## Step by step The following Ansible playbook snippet Playbooknstrates how to gather and display network information from a set of target hosts. This is an example setup.yml Playbook that displays the IPv4 addresses of the machines: [code example] The provided code snippet is written in YAML and represents an Ansible playbook. Ansible is an open-source automation tool used for configuring and managing systems, deploying applications, and performing various IT tasks through a declarative approach. Let’s break down the code step by step: 1. `---`: This is a YAML document delimiter that indicates the start of a new YAML document. 2. `name: Display network information`: This is a playbook task with a name describing what the task will do. In this case, it's intended to display network information. 3. `hosts: all`: This specifies the target hosts on which the playbook tasks w... --- ## Extend Kubernetes API with Custom Resource Definitions (CRDs) URL: https://www.ansiblebyexample.com/articles/kubernetes-custom-resource-definitions Description: Discover how to define, apply, and manage Custom Resource Definitions (CRDs) in Kubernetes to extend the API for custom resources. ## Introduction A **Custom Resource Definition (CRD)** in Kubernetes allows you to extend the Kubernetes API by defining your own custom resources. These custom resources can represent any kind of domain-specific entity, and you can manage them using standard Kubernetes tools like `kubectl`. ### Overview of Custom Resource Definitions (CRDs) - **Custom Resources:** These are extensions of the Kubernetes API. They allow you to create your own custom resource types that can be managed like built-in resources (e.g., Pods, Services). - **Custom Resource Definitions (CRDs):** These are used to define the schema and behavior of custom resources. Once a CRD is created, you can create instances of the custom resource it defines. ### Steps to Create and Use a Custom Resource Definition #### Step 1: Define the Custom Resource Definition (CRD) The CRD defines the structure and behavior of your custom resource. Here is an example of a simple CRD for a custom resource called `MyApp`. [code example] ### Explanation: - **`apiVersion`**: The API version for CRDs is `apiextensions.k8s.io/v1`. - **`kind`**: This is `CustomResourceDefinition` since you are defining a new custom resource. - **`metadata.name`**: The name of the CRD should be in the form of `plural.group`. In this case, it's `myapps.example.com`. - **`spec.group`**: The API group your custom resource belongs to. In this case, it's `example.com`. - **`spec.versions`**: The different versions of your custom resource. Each ve... --- ## Extract an archive in Windows-like systems — Ansible module win_unzip URL: https://www.ansiblebyexample.com/articles/extract-an-archive-in-windows-like-systems-ansible-module-win-unzip Description: How to automate the extraction of an example ZIP compressed archive with a text file inside creating the output directory on a Windows-like system with. ## How to extract a ZIP compressed archive in Windows-like systems in Ansible? ## Ansible extracts an archive in Windows-like systems - `community.windows.win_unzip` - Unzips compressed files and archives on the Windows node Today we're talking about the Ansible module `win_unzip`. The full name is `community.windows.win_unzip`, which means that is part of modules maintained by the community for Windows target hosts. It unzips compressed files and archives on the Windows node. It supports .zip files natively and can handle also other 7zip formats when combined with the Powershell Community Extensions (PSCX) module. For Linux targets, use the `ansible.builtin.unarchive` module. ## Parameters - src string - remote path - dest string - remote path - password string - password (require PSCX) - recurse boolean - no/yes - recursively expand zip files (require PSCX) The parameters of module `win_unzip`. The only mandatory parameters are "src" and "dest" which are the source and destination paths. The "src" is quite special because is supposed to be a remote path on Windows-like systems. The following two parameters require Powershell Community Extensions (PSCX) module. You could specify the encryption password to expand the archive in the "password" parameter. You could recursively expand zip files inside an archive enabling the "recurse" boolean. ## Links - Ansible module win_unzip ## Playbook How to extract an archive in Windows-like systems with Ansible Playbook. ### ... --- ## Extract Archives with Ansible — unarchive Module Guide URL: https://www.ansiblebyexample.com/articles/extract-an-archive-ansible-module-unarchive Description: Extract zip, tar.gz, and tar.bz2 archives with the Ansible unarchive module. Copy from local or remote URLs, set permissions, and run handlers on extract. ## Introduction The `ansible.builtin.unarchive` module extracts archives on remote hosts — handling `.zip`, `.tar`, `.tar.gz`, `.tar.bz2`, `.tar.xz`, and `.tar.zst` files. It can copy from the controller, extract files already on the remote, or download from a URL. This makes it the standard tool for deploying application packages, extracting backups, and distributing release artifacts. ## Module Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `src` | path/URL | Yes | Archive source — local path, remote path, or URL | | `dest` | path | Yes | Directory to extract into | | `remote_src` | bool | No | Source is on the remote host (default: `false`) | | `creates` | path | No | Skip extraction if this path exists (idempotency) | | `include` | list | No | Only extract these files/directories | | `exclude` | list | No | Skip these files/directories | | `extra_opts` | list | No | Extra command-line options for the extractor | | `keep_newer` | bool | No | Don't replace newer files on remote | | `validate_certs` | bool | No | Validate SSL certs for URL sources (default: `true`) | | `mode` / `owner` / `group` | string | No | Set permissions on extracted files | | `list_files` | bool | No | Return list of extracted files | ## Requirements The remote host needs: | Archive Type | Required Package | |-------------|-----------------| | `.zip` | `unzip`, `zipinfo` | | `.tar`, `.tar.gz`, `.tar.bz2`, `.tar.xz` | `gtar` (GNU tar) | | ... --- ## Extracting JSON Data with Ansible URL: https://www.ansiblebyexample.com/articles/extracting-json-data-with-ansible Description: Learn how to use Ansible to extract specific JSON data efficiently with the json_query filter, showcasing an example of retrieving folder values based. ## Introduction JSON (JavaScript Object Notation) is a common data format for APIs and configuration management. In modern IT operations, querying JSON data is essential for automation. Ansible, a powerful tool for automating IT tasks, offers a robust `json_query` filter that simplifies querying and extracting data. In this article, we will demonstrate how to use Ansible to extract a folder value from a JSON structure based on a specific name. --- ## 1. Why Automate JSON Queries? JSON queries can become repetitive and error-prone when done manually. Automating this process with Ansible provides several advantages: - **Consistency**: Avoid manual errors by standardizing queries. - **Efficiency**: Save time with automated data extraction. - **Flexibility**: Adapt quickly to changes in JSON structures. --- ## 2. Example Use Case: Extracting Folder Value by Name Let’s consider a scenario where you need to extract the folder value for a specific name from JSON data. ### The JSON Data Here’s an example JSON structure: [code example] ### The Goal Retrieve the `folder` value for `name: foo` using Ansible. --- ## 3. The Playbook Below is the Ansible playbook for this task: [code example] --- ## 4. Understanding the Playbook ### JSON Data The `json_data` variable represents the data to be queried. It’s a list of dictionaries with `name` and `folder` fields. ### Query Syntax The `json_query` filter uses JMESPath syntax for querying: - `?name=='{{ lookup_name }}'`: Filte... --- ## Failed installation of Ansible in Amazon Linux 2022 Preview (AWS EC2) — Ansible install URL: https://www.ansiblebyexample.com/articles/failed-installation-of-ansible-in-amazon-linux-2022-preview Description: Failed installation of Ansible in Amazon Linux 2022 Preview (AWS EC2) using the internal and the EPEL (Extra Packages for Enterprise Linux) repositories.. ## How to install Ansible in Amazon Linux version 2022 Preview? Today I'm trying to install Ansible in the newest Amazon Linux 2022 Preview. Spoiler alert: it didn't go well! ## Links https://aws.amazon.com/it/linux/amazon-linux-2022/ https://aws.amazon.com/it/linux/amazon-linux-2022/faqs/ https://github.com/amazonlinux/amazon-linux-2022/issues/57 ## Playbook Let's jump in a quick live Playbook of how I tried to install the latest of Ansible in Amazon Linux 2022 Preview. ### code - Install-Ansible-Amazon Linux2022.sh [code example] ### execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how I tried to install Ansible in Amazon Linux 2022 and open a Package Request to the Amazon developer team. --- ## Farewell to JetPorch Automation URL: https://www.ansiblebyexample.com/articles/farewell-to-jetporch-automation Description: The JetPorch automation project by Michael DeHaan has been discontinued. What happened, lessons learned, and the future of Ansible alternatives. ## Introduction In the ever-evolving world of open-source software, projects come and go, driven by the passion and dedication of their creators. One such project, Jet, had been quietly making waves in the IT community until its recent discontinuation. Michael DeHaan, the mind behind Jet, recently shared his decision to step away from the project in a heartfelt post on Jetporch. In this article, we'll explore Michael's decision and its implications for the open-source community. ## JetPorch Automation Jet, a project designed to simplify IT management, garnered attention for its innovative approach and user-friendly module system. Michael expressed his gratitude to the community for their interest, patches, and discussions around the project. However, he revealed that he had decided to discontinue work on Jet, citing a lack of outward excitement as the primary reason. ## Michael’s post In his candid post, Michael explained that the absence of personal IT management needs and the dwindling stimulation from the project had led him to explore new endeavors. He emphasized his desire to engage in projects that genuinely excited him, a sentiment many open-source enthusiasts can relate to. While this announcement may come as a disappointment to some, Michael offered a glimmer of hope for Jet's users. He reassured the community that the project's code and documentation would remain accessible. He outlined his plans for the project's decommissioning: 1. The Jet Discord server h... --- ## Federated Learning and Privacy-preserving RAGs URL: https://www.ansiblebyexample.com/articles/pluralsight-federated-learning-and-privacy-preserving-rags Description: Discover how to implement federated learning and privacy-preserving RAG models for accurate and secure AI solutions. Tested, copy-paste examples included. {{}} ## Introduction In the ever-evolving landscape of AI and machine learning, customer support is a field that demands quick and precise responses. Conventional AI systems often struggle to deliver contextually accurate answers, particularly when the information needed is specific and detailed. This is where Retrieval Augmented Generation (RAG) comes into play, offering a transformative approach by integrating advanced information retrieval with generative language models to enhance response accuracy and relevance. Luca Berton, a leading figure in AI, has introduced a new course on Pluralsight titled “Federated Learning and Privacy-preserving RAGs.” This course is specifically designed for those who are familiar with AI concepts and are looking to advance their skills in building RAG systems while maintaining data privacy. ## What is RAG and Why is it Important? RAG combines the capabilities of large language models (LLMs) with sophisticated retrieval mechanisms, enabling AI to not only generate text but also to pull in relevant data from external sources. This dual mechanism significantly improves the precision and context-awareness of responses, making RAG an ideal solution for customer support scenarios where accuracy is crucial. ## Key Highlights of the Course This course is concise yet filled with actionable insights for developers. Here’s what you’ll learn: **1. Understanding Federated Learning and Privacy-Preserving Techniques:** Learn how federated learnin... --- ## Find All Files with Extension — Ansible module find URL: https://www.ansiblebyexample.com/articles/find-all-files-with-extension-ansible-module-find Description: How to automate the finding of all files with “.cnf” extension under the “example” directory of “devops” user using Ansible Playbook and find module. ## How to Find All Files with a specific Extension with Ansible? ## Ansible Find All Files with Extension - `ansible.builtin.find` - Return a list of files based on specific criteria Today we're talking about the Ansible module `find`. The full name is `ansible.builtin.find`, which means that is part of the collection included in the `ansible-core` builtin collection. This module returns a list of files based on specific criteria using the `find` popular Unix command. ## Parameters - paths string - List of paths of directories to search - hidden boolean - no/yes - recurse boolean - recursively descend into the directory looking for files - file_type string - file/directory/any/link - patterns list - search (shell or regex) pattern(s) - use_regex boolean - no/yes - file globs (shell) / python regexes The most important parameters of the `find` module for this use case. The mandatory parameter `paths` specify the list of paths of directories to search. You could include hidden files with the `hidden` parameter. As well as recurse in any directory under the main path with the `recurse` parameter. Another useful parameter is `file_type`, which defaults to `file` but you could filter for `directory`, `link`, or `any` filesystem object type. Specify what to search under the `patterns` list. Ansible by default uses file globs (shell) patterns but you could specify also python regexes enabling the `use_regex` parameter. ## Links - `ansible.builtin.find` ## Playbook How to Fi... --- ## Five Reasons for Upgrading to Ansible Core 2.14 or Ansible Community 7.0 URL: https://www.ansiblebyexample.com/articles/five-reasons-for-upgrading-to-ansible-core-2-14-or-ansible-community-7-0 Description: From the user perspective, upgrading to the Ansible Core 2.14 release in your organization is pushing the Future of Automation! ## Introduction In the ever-evolving landscape of IT infrastructure management and automation, staying up-to-date with the latest tools and technologies is essential. One such tool, Ansible, has been a cornerstone for many IT professionals, simplifying tasks and streamlining operations. With the release of Ansible 2.14, there are compelling reasons to consider migrating from previous Ansible versions. In this article, we will explore the major changes and advantages of making this migration. ### 1. Improved Handler Processing Ansible’s architecture is designed to be flexible and efficient, ensuring that tasks and actions are executed in the right sequence. One significant change in Ansible 2.14 is the enhancement of handler processing. Handlers are essential for executing specific tasks after playbook execution. With this migration, handler processing has been moved into a new “PlayIterator” phase. This allows you to use the configured strategy more effectively, ensuring that actions are executed in the correct order. The result is more precise and efficient post-playbook processing. ### 2. Python 3.9 Compatibility The backbone of Ansible is Python, and staying current with Python versions is crucial for both security and performance. Ansible 2.14 raises the minimum Python requirement to Python 3.9 for CLI utilities and controller code. This ensures that Ansible is compatible with the latest Python versions, taking advantage of performance improvements and security updat... --- ## Fix Ansible "dict object has no attribute" Error — Variable Access Guide URL: https://www.ansiblebyexample.com/articles/fix-ansible-dict-object-has-no-attribute-error Description: Resolve the common Ansible 'dict object has no attribute' error. Learn proper dictionary access patterns, default filters, and debugging techniques. # Fix Ansible "dict object has no attribute" Error ## The Error [code example] ## Why It Happens You're accessing a dictionary key that doesn't exist: [code example] ## Solution 1: Use Bracket Notation with Default Filter [code example] ## Solution 2: Check if Key Exists First [code example] ## Solution 3: Use the `default` Filter [code example] ## Solution 4: Debug the Actual Variable Content [code example] ## Common Causes ### Register Output Structure [code example] ### Ansible Facts Not Gathered [code example] ### Nested Dictionary Access [code example] ## Conclusion Always use `| default()` when accessing dictionary keys that might not exist. Use `debug: var:` to inspect variable contents when troubleshooting. --- ## Fix Ansible "Gathering Facts" Timeout & Slow Playbooks — Speed Up by 10x URL: https://www.ansiblebyexample.com/articles/fix-ansible-gathering-facts-timeout-slow-playbooks Description: Fix Ansible playbooks stuck on 'Gathering Facts'. Learn to disable unnecessary facts, use fact caching, and optimize playbook execution speed. # Fix Ansible "Gathering Facts" Timeout & Slow Playbooks ## The Problem Your playbook hangs on "Gathering Facts" for minutes, or times out entirely: [code example] ## Solution 1: Disable Facts When Not Needed [code example] ## Solution 2: Gather Only What You Need [code example] Minimum facts (fastest): [code example] ## Solution 3: Enable Fact Caching [code example] Or use Redis for multi-user environments: [code example] ## Solution 4: Increase Timeout [code example] ## Solution 5: Use Async & Forks [code example] ## Performance Comparison | Method | 100 Hosts | Improvement | |--------|-----------|-------------| | Default | ~200s | baseline | | gather_subset: min | ~80s | 2.5x faster | | gather_facts: false | ~20s | 10x faster | | Fact caching (warm) | ~5s | 40x faster | | forks=20 | ~40s | 5x faster | ## Conclusion For maximum speed: disable facts when possible, use `gather_subset` when you need them, and enable fact caching for repeated runs. Combining these techniques can speed up playbooks by 10-40x. --- ## Fix Ansible "Missing sudo Password" & Become Errors — Privilege Escalation Guide URL: https://www.ansiblebyexample.com/articles/fix-ansible-sudo-become-privilege-escalation-errors Description: Configure Ansible become without password: NOPASSWD sudoers, Ansible Vault, SSH keys. Complete privilege escalation guide with tested solutions. # Fix Ansible "Missing sudo Password" & Become Errors ## The Error [code example] ## Solution 1: Pass sudo Password at Runtime [code example] ## Solution 2: Configure NOPASSWD in sudoers On the remote host: [code example] Or for specific commands only: [code example] ## Solution 3: Store Password in Vault [code example] [code example] ## Solution 4: Set become in ansible.cfg [code example] ## Solution 5: Per-Task Become [code example] ## Common Mistakes ### Wrong become_method [code example] ### become_user vs become [code example] ### Timeout Waiting for Password Prompt [code example] ## Debugging [code example] ## Conclusion Use `--ask-become-pass` for interactive use, `NOPASSWD` in sudoers for automation, and Ansible Vault for stored passwords. Always use `become: true` only on tasks that actually need root. --- ## Fix Ansible "MODULE FAILURE" Error — Debug & Resolve Module Crashes URL: https://www.ansiblebyexample.com/articles/fix-ansible-module-failure-error Description: Troubleshoot Ansible MODULE FAILURE errors. Debug with -vvv, fix Python dependencies, check module arguments, and resolve common module crashes. # Fix Ansible "MODULE FAILURE" Error ## The Error [code example] ## Step 1: Get More Details with -vvv [code example] The verbose output usually reveals the actual Python traceback. ## Step 2: Common Causes & Fixes ### Missing Python Library on Remote Host [code example] [code example] ### Wrong Module Arguments [code example] Check valid parameters: [code example] ### JSON Parsing Error [code example] Your remote host is printing something before the module output. Common causes: - `/etc/profile` or `.bashrc` prints messages - MOTD or login banners [code example] ### Permission Issues [code example] ## Step 3: Test Module Directly [code example] ## Step 4: Check Module Compatibility [code example] ## Conclusion MODULE FAILURE almost always means a Python error on the remote host. Use `-vvvv` for the full traceback, check Python dependencies, and verify module arguments with `ansible-doc`. --- ## Fix Ansible "Permission Denied" SSH Error — 5 Solutions That Work URL: https://www.ansiblebyexample.com/articles/fix-ansible-permission-denied-ssh-error Description: Resolve the Ansible SSH Permission Denied error with step-by-step solutions covering SSH keys, become privileges, known_hosts, and file permissions. # Fix Ansible "Permission Denied" SSH Error — 5 Solutions That Work The "Permission denied" SSH error is one of the most common Ansible issues. Here are the 5 most effective solutions. ## The Error [code example] ## Solution 1: Check SSH Key Configuration The most common cause is a missing or incorrect SSH key. [code example] Test SSH connectivity first: [code example] ## Solution 2: Fix SSH Key Permissions SSH refuses keys with incorrect permissions. [code example] ## Solution 3: Use ansible_ssh_private_key_file Set the key per host in your inventory: [code example] ## Solution 4: Fix become (sudo) Permission Denied If SSH works but tasks fail with permission denied, it's a `become` issue: [code example] Run with `--ask-become-pass` if sudo requires a password: [code example] ## Solution 5: Add Host to known_hosts First connection to a new host may fail if host key checking is strict: [code example] Or add the host key first: [code example] ## Quick Diagnostic Checklist [code example] ## Conclusion SSH Permission Denied errors in Ansible almost always come down to key configuration, file permissions, or become privileges. Start with the SSH connection test and work your way through each solution. --- ## Fix Ansible "Skipping: No Hosts Matched" — Why Your Playbook Runs on Zero Hosts URL: https://www.ansiblebyexample.com/articles/fix-ansible-skipping-no-hosts-matched Description: Troubleshoot the 'skipping: no hosts matched' warning in Ansible. Learn about inventory mismatches, host patterns, and the most common causes. # Fix Ansible "Skipping: No Hosts Matched" ## The Warning [code example] Your playbook runs but does absolutely nothing. Here's why and how to fix it. ## Cause 1: Typo in hosts or Group Name [code example] [code example] **Fix:** Double-check spelling in both playbook `hosts:` and inventory group names. ## Cause 2: Wrong Inventory File [code example] Or set it in `ansible.cfg`: [code example] ## Cause 3: Host Pattern Mismatch [code example] Verify your inventory: [code example] ## Cause 4: Limit Flag Filtering Everything Out [code example] ## Cause 5: Dynamic Inventory Returns Empty [code example] ## Quick Fix Checklist 1. `ansible-inventory --graph` — see what Ansible actually knows about 2. Check `hosts:` in playbook matches a group or host name exactly 3. Verify inventory file path with `-i` 4. Remove `--limit` flags temporarily 5. Check for YAML indentation issues in inventory ## Conclusion "No hosts matched" almost always means Ansible can't find the hosts you specified. Verify your inventory path, check for typos, and use `ansible-inventory --graph` to see what's actually loaded. --- ## Fix Ansible "UndefinedError" — Jinja2 Variable Not Defined Solutions URL: https://www.ansiblebyexample.com/articles/fix-ansible-jinja2-undefined-variable-error Description: Resolve Ansible Jinja2 UndefinedError when variables are not defined. Use default filter, omit, mandatory, and conditional checks. # Fix Ansible Jinja2 "UndefinedError" ## The Error [code example] ## Solution 1: Use the default Filter [code example] ## Solution 2: Check Before Using [code example] ## Solution 3: Set Variable Defaults in Role [code example] ## Solution 4: Use vars with Defaults [code example] ## Solution 5: Make Variables Mandatory [code example] ## Common Causes ### Variable Scope Issues [code example] ### Typos [code example] ### Missing group_vars/host_vars [code example] ## Conclusion Always use `| default()` for optional variables. Use `is defined` checks for conditional logic. Set defaults in `roles/*/defaults/main.yml` for role variables. --- ## Fix Ansible \"Could Not Resolve Hostname\" — DNS & Inventory Troubleshooting URL: https://www.ansiblebyexample.com/articles/fix-ansible-could-not-resolve-hostname Description: Troubleshoot Ansible 'could not resolve hostname' errors. Fix DNS issues, inventory misconfigurations, SSH connection problems, and VPN/network issues. ## The Error [code example] This means the control node's DNS can't resolve the hostname in your inventory to an IP address. ## Quick Diagnosis [code example] If FQDN works but short name doesn't, the issue is DNS search domain configuration. ## 5 Solutions ### Solution 1: Use ansible_host with IP Addresses (Most Reliable) [code example] [code example] This decouples the inventory name from DNS — the most reliable approach. ### Solution 2: Use FQDNs in Inventory [code example] ### Solution 3: Add Entries to /etc/hosts [code example] Or automate with Ansible (on a working host): [code example] ### Solution 4: Fix DNS Configuration [code example] ### Solution 5: Fix DNS Search Domain If short hostnames should resolve via a domain suffix: [code example] Now `myserver` resolves as `myserver.example.com`. ## Common Causes | Cause | Symptom | Fix | |-------|---------|-----| | Typo in inventory | One host fails | Check spelling | | DNS server down | All hosts fail | Check `/etc/resolv.conf` | | VPN not connected | Private hosts fail | Connect VPN first | | Wrong inventory file | Wrong hosts targeted | `ansible-playbook -i correct_inventory` | | Cloud instance rebuilt | IP changed | Update `ansible_host` | | Split DNS (VPN) | Internal names fail | Check DNS over VPN | ## Debugging Steps ### 1. Verify Which Inventory Ansible Uses [code example] ### 2. Test SSH Directly [code example] ### 3. Increase Verbosity [code example] ### 4. Check for Stale DNS Ca... --- ## Fix Ansible Error 303 — Use Module URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-303-command-instead-of-module Description: Rule 303, command-instead-of-module, advises using Ansible modules over raw commands for improved playbook reliability." ## Introduction In the world of Ansible automation, best practices and efficiency are paramount. Ansible-Lint, a popular linting tool for Ansible playbooks, comes with a variety of rules to help you follow best practices, maintain consistency, and avoid common pitfalls. One such rule, Rule 303, "`command-instead-of-module`", in Ansible-Lint recommends using specific Ansible modules in place of commands for tasks where modules are a more reliable and feature-rich choice. ## Understanding Rule 303 Rule 303, "`command-instead-of-module`", serves as a friendly reminder that, in many cases, using Ansible modules is a better approach than running raw shell commands. Modules provide various benefits, including improved reliability, better messaging, and additional features like retry capabilities. By adhering to this rule, you can enhance the quality and maintainability of your Ansible playbooks. ## Problematic Code Let's examine a common issue that Rule 303 can help identify in your playbooks: [code example] In this code snippet, a raw command (`apt-get update`) is used to update the apt cache. While this approach may work, it's not the most efficient or reliable way to achieve the task. Output: [code example] ## Correct Code Here's the corrected code that aligns with Rule 303: [code example] In the improved version, the "ansible.builtin.apt" module is utilized to update the apt cache. This module is purpose-built for managing packages and repositories, making the play... --- ## Fix Ansible FQCN Error — Use Fully Qualified Names URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-fqcn Description: Fix Ansible FQCN errors by using fully-qualified collection names like ansible.builtin.copy instead of short names. Migration guide with before/after. ## Using Fully-Qualified Collection Names (FQCN) in Ansible Content In the world of automation and orchestration, Ansible has established itself as a popular choice for managing IT infrastructure and application deployments. Ansible allows you to create powerful automation scripts, or playbooks, to streamline tasks and manage resources efficiently. However, as with any coding or scripting language, adhering to best practices is essential for maintaining code quality and avoiding potential pitfalls. This article focuses on a specific Ansible linting rule called "`fqcn`," which checks for fully-qualified collection names (FQCN) in Ansible content. ## What Is FQCN? A Fully-Qualified Collection Name, or FQCN for short, is a way to specify the full namespace for an Ansible module or action. It serves the purpose of eliminating ambiguity and ensuring that the correct code from the correct collection is executed. In the context of Ansible, collections refer to reusable packages of playbooks, roles, modules, and other components that help streamline automation tasks. The "`fqcn`" rule helps maintain code quality by ensuring that you use FQCNs for module actions. This rule offers several checks, including: - `fqcn[action]`: Encourages the use of FQCN for module actions. - `fqcn[action-core]`: Checks for FQCNs from the `ansible.legacy` or `ansible.builtin` collection. - `fqcn[canonical]`: Promotes the use of canonical module names over aliases or redirects. - `fqcn[deep]`: Discour... --- ## Fix Ansible Galaxy — Timeout Errors URL: https://www.ansiblebyexample.com/articles/fix-ansible-galaxy-install-errors-timeout Description: Resolve ansible-galaxy install failures including timeouts, SSL errors, authentication issues, and requirements.yml configuration. # Fix Ansible Galaxy Install Errors ## Error 1: Timeout [code example] [code example] ## Error 2: SSL Certificate Error [code example] [code example] ## Error 3: Requirements File Errors [code example] [code example] ## Error 4: Permission Denied [code example] ## Error 5: Version Conflict [code example] [code example] ## Error 6: Behind a Proxy [code example] Or in `ansible.cfg`: [code example] ## Verify Installation [code example] ## Offline Installation [code example] ## Conclusion Most Galaxy install errors come from network issues (timeout, SSL, proxy) or permission problems. Increase timeouts, update certificates, and use `--force` for version conflicts. --- ## Fix Ansible Galaxy Install Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-ansible-galaxy-installation-issues-the-case-of-the-missing-amazon-aws-collection Description: Fix ansible-galaxy install errors for collections and roles. Resolve timeout, authentication, namespace, and dependency issues with step-by-step solutions. ## Introduction A common Ansible Galaxy error occurs when users try to install a **collection** using the **role** install command. The `ansible-galaxy install` command defaults to roles, but most modern Ansible content (like `amazon.aws`) is packaged as collections. Understanding the difference prevents frustrating "not found" errors. ## The Error [code example] ## Root Cause: Roles vs Collections | Content Type | Install Command | Example | |-------------|----------------|---------| | **Role** | `ansible-galaxy install` | `ansible-galaxy install geerlingguy.docker` | | **Collection** | `ansible-galaxy collection install` | `ansible-galaxy collection install amazon.aws` | `amazon.aws` is a **collection**, not a role. The role install command looks in a different API endpoint, finds nothing, and fails. ## The Fix [code example] Successful output: [code example] ## Install Specific Version [code example] ## Using requirements.yml (Recommended) Manage all dependencies in a single file: [code example] Install everything: [code example] ## Common Errors and Fixes ### "Not found on Galaxy API" [code example] **Fix:** Use `collection install` instead of `install`. ### Network/Timeout Errors [code example] **Fixes:** [code example] ### Version Compatibility [code example] **Fix:** Check which versions are available: [code example] ### "requires_ansible" Metadata Error [code example] This warning is usually harmless — it comes from another installed co... --- ## Fix Ansible Handlers Not Running — notify, flush_handlers & Common Pitfalls URL: https://www.ansiblebyexample.com/articles/fix-ansible-handlers-not-running Description: Troubleshoot Ansible handlers that don't execute. Fix notify mismatches, understand handler behavior with failures, and use flush_handlers. # Fix Ansible Handlers Not Running ## The Problem You added `notify: restart nginx` but the handler never runs. ## Cause 1: Name Mismatch [code example] Handler names are **case-sensitive**. They must match exactly. ## Cause 2: Task Didn't Change Anything Handlers only run when the task reports `changed`. If the file is already identical: [code example] Force a change to test: [code example] ## Cause 3: Task Failed Before Handler Ran Handlers run at the **end of the play**, not immediately after notify. If a later task fails, handlers are skipped. [code example] Or use `--force-handlers`: [code example] ## Cause 4: Handler in Wrong Section [code example] ## Cause 5: Listen vs Name [code example] ## Debugging Handlers [code example] ## Conclusion Handlers not running? Check: exact name match, task actually changed something, no failures before handler execution. Use `meta: flush_handlers` when you need handlers to run immediately. --- ## Fix Ansible Invalid Plugin Name Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-invalid-plugin-name-regex-replace-error-in-ansible Description: Fix 'Invalid plugin name: regex.replace' in Ansible. Use ansible.builtin.regex_replace FQCN instead of short names. Step-by-step solution with examples. ## Introduction Ansible is a powerful automation tool that allows you to manage multiple servers from a single machine. It can perform tasks such as provisioning, deployment, and configuration management. However, like any tool, Ansible can encounter errors and issues that can cause frustration for users. One such error is the “Invalid plugin name: regex.replace” error, which can occur when using the regex.replace plugin in an Ansible playbook or task. ## What causes the error? The “Invalid plugin name: regex.replace” error occurs when the `regex.replace` plugin is not installed or is not loaded correctly. The `regex.replace` plugin is part of the `ansible.builtin` collection, so if this collection is not installed on the machine running Ansible, the plugin will not be available. Another possible cause is that the Ansible version being used is outdated and does not support the regex.replace plugin. ## How to troubleshoot the error? To troubleshoot the “Invalid plugin name: regex.replace” error, you can follow these steps: ### Step 1: Update Ansible to the latest version One of the reasons may be that the version of Ansible being used does not support the `regex.replace` plugin. To update Ansible to the latest version, run the following command: [code example] ### Step 2: Check the syntax of the playbook or task If the error still occurs after updating Ansible, check the syntax of the playbook or task where the error occurs. Please note that till Ansible 2.9 use the rege... --- ## Fix Ansible Inventory Parsing Errors URL: https://www.ansiblebyexample.com/articles/fix-ansible-inventory-parsing-errors Description: Resolve Ansible inventory parsing failures. Fix YAML syntax, INI format issues, dynamic inventory scripts, and inventory plugin configuration. # Fix Ansible Inventory Parsing Errors ## The Error [code example] ## INI Format Issues ### Correct INI Inventory [code example] ### Common INI Mistakes [code example] ## YAML Format Issues ### Correct YAML Inventory [code example] ### Common YAML Mistakes [code example] ## Dynamic Inventory Issues ### Script Must Be Executable [code example] ### Must Return Valid JSON [code example] ### Expected JSON Format [code example] ## Debugging Inventory [code example] ## Multiple Inventory Sources [code example] ## Conclusion Inventory parsing errors usually come from format issues (wrong YAML indentation, missing `hosts:` key) or dynamic scripts that aren't executable or return invalid JSON. Use `ansible-inventory --list` to debug. --- ## Fix Ansible Jinja2 & Inventory Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-deciphering-ansible-playbook-execution-errors-jinja2-syntax-and-inventory-issues Description: Fix Jinja2 syntax errors, inventory parsing warnings, and variable quoting issues in Ansible playbooks. Complete troubleshooting guide with solutions. ## Introduction Ansible playbook errors can be frustrating, especially when the error message isn't immediately clear. The most common categories are **Jinja2 syntax errors** (unbalanced blocks, incorrect quoting) and **inventory parsing warnings** (no valid hosts found). This guide covers systematic troubleshooting for both. ## Jinja2 Syntax Errors ### Unbalanced Block or Quote The most common Jinja2 error: [code example] **Common causes:** | Problem | Example | Fix | |---------|---------|-----| | Missing closing `}}` | `{{ var }` | `{{ var }}` | | Missing closing `%}` | `{% if x %` | `{% if x %}` | | Unmatched quotes inside variable | `"{{ "hello" }}"` | `"{{ 'hello' }}"` | | Variable at start of value | `{{ var }}` as YAML value | `"{{ var }}"` — must be quoted | ### Variables Must Be Quoted In YAML, a value starting with `{{` must be quoted: [code example] ### Nested Quotes When Jinja2 expressions contain strings, alternate quote types: [code example] ### Quoting in Shell Commands [code example] ### Multiline Jinja2 Expressions [code example] ## Inventory Parsing Errors ### "Unable to parse as an inventory source" [code example] **Common causes and fixes:** #### No Inventory Specified [code example] #### Invalid Inventory Format [code example] #### YAML Inventory Syntax Error [code example] #### File Permissions [code example] ### "Could not match supplied host pattern" [code example] **Fix:** The group name in your playbook doesn't match a... --- ## Fix Ansible macOS Fork Safety Error URL: https://www.ansiblebyexample.com/articles/macos-fork-error-ansible-troubleshooting Description: Fix the macOS fork() crash in Ansible caused by Objective-C runtime safety checks. Learn the root cause, temporary and permanent fixes, and alternative. If you run Ansible on macOS and see a crash about `+[__NSCFConstantString initialize]` and `fork()`, this is a known conflict between Python's multiprocessing, Ansible's forking behavior, and macOS's Objective-C runtime safety checks. Here's exactly what causes it and how to fix it. ## The Error [code example] ## Root Cause Starting with macOS High Sierra (10.13), Apple added a safety check in the Objective-C runtime that **crashes any process that calls `fork()` without immediately calling `exec()`** if Objective-C classes are being initialized in another thread. Ansible uses Python's `multiprocessing` module to fork child processes for parallel task execution. When Python forks on macOS, the child process inherits the parent's memory — including partially-initialized Objective-C classes. macOS detects this as unsafe and kills the process. This affects: - **Ansible with `forks > 1`** (the default is 5) - **Any Python script** that uses `multiprocessing` or `os.fork()` on macOS - **All macOS versions** from High Sierra onward (including Ventura, Sonoma, Sequoia) ## Fix 1: Environment Variable (Recommended) ### Current Terminal Session Only [code example] ### Permanent Fix (All Sessions) Add to your shell profile: [code example] ### Verify It's Set [code example] ## Fix 2: Reduce Forks to 1 If you prefer not to disable the safety check: [code example] Or per-command: [code example] This eliminates forking entirely but runs tasks sequentially (slower for mul... --- ## Fix Ansible Permission Denied Errno 13 URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-permission-denied-errno-13 Description: Learn how to troubleshoot and resolve the Permission Denied Errno 13 error in Ansible with Luca Berton on Ansible Pilot. ## Introduction Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we're delving into Ansible troubleshooting, focusing on the pesky "Permission Denied Errno 13" error. Join me as we explore the intricacies of this issue, reproduce it in a live Playbook, and learn how to effectively resolve it using privilege escalation in Ansible Playbooks. ## The Demo Let's jump right into a live Playbook to understand how to troubleshoot the Ansible fatal error [Errno 13] Permission denied and fix it in an Ansible Playbook. ### Error Code [code example] ### Error Execution [code example] ### Fix Code [code example] ### Fix Execution [code example] ## Conclusion In this tutorial, we've successfully troubleshooted the Ansible [Errno 13] Permission Denied error and implemented a fix in an Ansible Playbook. By leveraging privilege escalation, we overcame the Permission Denied hurdle and ensured seamless execution. I hope this guide proves valuable in unraveling similar challenges during your Ansible automation endeavors. If you found this information helpful, consider subscribing for more Ansible insights. --- ## Fix Ansible PowerShell Sudo Conflict URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-powershell-incompatible-with-the-sudo-become-plugin Description: Fix the 'PowerShell shell family is incompatible with the sudo become plugin' error in Ansible. Understand why become doesn't work with Windows targets. ## Introduction When running Ansible playbooks against Windows hosts, you may encounter this error: [code example] This happens because `sudo` is a Linux concept — Windows uses a completely different privilege escalation model. Here's how to fix it and understand the correct approach for Windows. ## The Error ### Broken Playbook [code example] [code example] ## Root Cause Ansible's default `become_method` is `sudo` — a Linux privilege escalation tool. Windows uses PowerShell, which doesn't have `sudo`. The error occurs when: 1. `become: true` is set (in playbook, `ansible.cfg`, or group vars) 2. The target is a Windows host (PowerShell shell family) 3. `become_method` defaults to `sudo` ## Fix 1: Disable become for Windows The simplest fix — Windows WinRM connections already run with the privileges of `ansible_user`: [code example] [code example] ## Fix 2: Use runas (Windows Privilege Escalation) If you need to run as a different user on Windows, use `runas` instead of `sudo`: [code example] ## Fix 3: Group-Level Configuration Set `become` per group in your inventory to avoid conflicts in mixed environments: [code example] ## Fix 4: Conditional become in Mixed Playbooks [code example] ## Windows Privilege Escalation Methods | Method | Description | Use Case | |--------|-------------|----------| | **None** (`become: false`) | Run as `ansible_user` | Most common — WinRM user has sufficient privileges | | **runas** | Run as different Windows user | Need a... --- ## Fix Ansible Python Version Errors URL: https://www.ansiblebyexample.com/articles/fix-ansible-python-version-interpreter-errors Description: Resolve Ansible Python interpreter errors including 'interpreter_python' warnings, Python 2 vs 3 issues, and virtualenv configuration. # Fix Ansible Python Version Errors ## The Warning [code example] ## Solution 1: Set Python Interpreter Globally [code example] Or specify exactly: [code example] ## Solution 2: Set Per Host in Inventory [code example] ## Solution 3: Set in Playbook [code example] ## Common Scenarios ### No Python on Remote Host [code example] Fix with the `raw` module (doesn't need Python): [code example] ### Python 2 vs Python 3 Module Errors [code example] ### Virtualenv Issues [code example] ## Best Practice Set it once in `ansible.cfg` and forget about it: [code example] This uses auto-detection without the warning. For production, pin the exact version in your inventory. --- ## Fix Ansible Root User Permission Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-this-command-has-to-be-run-under-the-root-user Description: Fix the Ansible error This command has to be run under the root user — become directive, sudo config, and privilege escalation guide. ## Introduction The error `"This command has to be run under the root user"` is one of the most common Ansible errors for beginners. It occurs when a task requires root (superuser) privileges but the playbook is not configured to escalate privileges. This typically happens with package management, service control, user management, and system configuration tasks. This article explains why this error occurs, all the ways to fix it, how Ansible privilege escalation works, and best practices for managing sudo access across your infrastructure. ## Understanding the Error When Ansible connects to a remote host, it runs tasks as the SSH user (often a regular non-root user). Many system operations require root privileges: [code example] The same thing happens in Ansible — the remote module runs as a non-root user and the underlying command fails: [code example] ## Error Playbook This playbook triggers the error because `become: false` prevents privilege escalation: [code example] ### Error Output [code example] ## Solution 1: Enable become at Play Level The most common fix — add `become: true` to the play: [code example] ### Fixed Output [code example] ## Solution 2: Enable become at Task Level If only specific tasks need root, apply `become` per task: [code example] ## Solution 3: Enable become at Role Level [code example] ## Solution 4: Set become in ansible.cfg For environments where you always need privilege escalation: [code example] ## Solution 5: Comm... --- ## Fix Ansible run_once — Common Pitfalls URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-error-run-once Description: Fix run_once issues in Ansible playbooks. Common mistakes with serial, delegation, variable scope, and how to properly run tasks on a single host. ## Understanding the Ansible Playbook Error: `run-once` When developing Ansible playbooks, it's crucial to ensure efficient execution and adhere to best practices. This includes using strategies that align with the desired behavior of your tasks and plays. In the world of Ansible, the `run_once` directive is a powerful tool. It is used to ensure that a particular task runs only once in a playbook. However, its use can become problematic if not handled correctly, especially when used in conjunction with the `strategy: free` configuration. ## What is `run_once`? In Ansible, the `run_once` directive allows you to specify that a task should execute only once, regardless of how many hosts are involved in the playbook. This is particularly useful when you have a task that should be performed only on the control node or a single target host, even in a scenario where multiple hosts are being managed. Here's a quick example: [code example] In this example, the `debug` task will execute only once, even if it's part of a playbook applied to multiple hosts. Ansible Lint Output [code example] ## The Issue with `run_once` and `strategy: free` One common pitfall occurs when you use the `run_once` directive in combination with the `strategy: free` setting. The `strategy: free` tells Ansible to parallelize tasks as much as possible, which can lead to unexpected results when used with `run_once`. This combination may not guarantee that the task runs only once due to the parallel nat... --- ## Fix Ansible SSH & Task Timeout URL: https://www.ansiblebyexample.com/articles/fix-ansible-connection-timeout-ssh-task Description: Resolve all types of Ansible timeouts. Configure SSH connection timeout, task timeout, command timeout, and optimize for slow or unreliable networks. # Fix Ansible Connection Timeout ## Types of Timeouts ### 1. SSH Connection Timeout [code example] [code example] ### 2. Command/Task Timeout [code example] For individual tasks: [code example] ### 3. Privilege Escalation Timeout [code example] [code example] ### 4. Persistent Connection Timeout [code example] ## Optimizing for Slow Networks ### Use Pipelining [code example] ### Use ControlMaster [code example] ### Reduce Forks for Constrained Networks [code example] ## Per-Host Timeout [code example] ## Retry on Timeout [code example] ## All Timeout Settings Reference [code example] ## Conclusion Match your timeout values to your environment. LAN: defaults are fine. WAN/VPN: increase to 30-60s. Cloud instances that spin up slowly: use retries with delay. Always enable pipelining and ControlMaster for better performance. --- ## Fix Ansible SSH Connection Errors URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-ssh-connection-issues Description: Resolve Ansible SSH connection failures: host key verification, permission denied, unreachable hosts, timeout errors, and known_hosts issues. ## Error Overview When running an Ansible playbook, you may encounter the following error message: [code example] This error indicates a failure in SSH connection due to the inability to establish the authenticity of the host. Below, we provide a detailed explanation of the issue and steps to resolve it. ## Error Explanation 1. **Warning**: `ansible-pylibssh not installed, falling back to paramiko` - This warning means Ansible is using `paramiko` for SSH connections because `pylibssh` is not installed. While `paramiko` is functional, `pylibssh` is generally more efficient and secure. 2. **Fatal Error**: `The authenticity of host '10.96.192.10' can't be established.` - This error occurs when the SSH client cannot verify the host's identity because the host key is not in the known hosts file. ## Solutions ### Install pylibssh Installing `pylibssh` can improve SSH connection efficiency and security: [code example] ### Automatically Accept Host Keys You can configure Ansible to automatically accept host keys by setting the `ansible_ssh_common_args` variable in your playbook or inventory to disable host key checking. Note that this method can expose you to security risks, such as man-in-the-middle attacks. Add the following configuration to your `ansible.cfg` file: [code example] Alternatively, set the `ANSIBLE_HOST_KEY_CHECKING` environment variable to `False`: [code example] ### Manually Add the Host Key A more secure approach is to manually add the host ... --- ## Fix Ansible Template Errors — Jinja2 URL: https://www.ansiblebyexample.com/articles/fix-ansible-template-jinja2-errors Description: Fix common Ansible Jinja2 template errors: undefined variables, wrong filters, whitespace control, and syntax mistakes. Debug tips with -vvv. # Fix Ansible Template Errors — Jinja2 Syntax Guide ## Error 1: Unexpected Token [code example] [code example] ## Error 2: Filter Not Found [code example] [code example] ## Error 3: Template File Not Found [code example] [code example] [code example] ## Error 4: Whitespace Issues in Generated Files [code example] ## Error 5: Type Errors in Filters [code example] [code example] ## Useful Debugging Techniques ### Preview Template Output [code example] ### Check Template Syntax [code example] ### Common Filters Cheat Sheet [code example] ## Conclusion Most template errors come from undefined variables (use `| default()`), missing filters (install collections), and whitespace control (use `{%-` and `-%}`). Preview output with `lookup('template')` for debugging. --- ## Fix Ansible Undefined Variable Error URL: https://www.ansiblebyexample.com/articles/ansible-undefined-variable-error-fix-prevent Description: Fix Ansible undefined variable errors. Learn default filters, mandatory checks, variable precedence, and debugging techniques to prevent. ## Introduction The `AnsibleUndefinedVariable` error is one of the most common Ansible errors. It occurs when a playbook references a variable that hasn't been defined anywhere — inventory, group_vars, host_vars, role defaults, or task vars. This guide shows every way to fix, prevent, and debug undefined variable errors. ## The Error [code example] ## Why It Happens [code example] ## Fix 1: The default Filter The most common fix — provide a fallback value: [code example] ## Fix 2: Conditional Checks [code example] ## Fix 3: Mandatory Variables Sometimes you *want* the error — to fail fast when required variables are missing: [code example] ## Fix 4: Variable Precedence [code example] ## Debugging Undefined Variables [code example] ## Nested Variable Errors [code example] ## Common Mistakes [code example] ## Prevent Undefined Variables Globally [code example] ## Related Articles - Ansible Variables - Ansible Jinja2 Templates - Ansible Troubleshooting - Ansible group_vars vs host_vars - Ansible Error Handling ## Conclusion Undefined variable errors have three fixes: `default()` filter for optional variables, `is defined` checks for conditional logic, and `mandatory` filter or `argument_specs` for required variables. Most errors come from typos, wrong host/group scope, or missing role defaults. Use `ansible-playbook -vvv` to trace where variables are loaded from, and use `assert` tasks to validate required variables early in your playbook. --- ## Fix Ansible VARIABLE IS NOT DEFINED URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-variable-is-not-defined-ansible-hostname Description: Fix the VARIABLE IS NOT DEFINED ansible_hostname error — root cause analysis, gather_facts, inventory_hostname, and practical solutions. ## Introduction The `VARIABLE IS NOT DEFINED!` error is one of the most common Ansible troubleshooting scenarios. Most of the time the root cause is a misspelled variable name or a variable that was never set. However, there is a special case involving `ansible_hostname` and other **Ansible facts** that catches many users off guard — the variable exists, is spelled correctly, and yet Ansible reports it as undefined. This article explains why this happens, the difference between `ansible_hostname` and `inventory_hostname`, how `gather_facts` controls fact availability, and multiple strategies to fix and prevent this error. ## Understanding the Error When Ansible encounters an undefined variable during template rendering or task execution, it produces output like this: [code example] or in newer Ansible versions: [code example] This happens because `ansible_hostname` is an **Ansible fact** — a variable that is automatically populated when Ansible gathers facts from the target host. If fact gathering is disabled, the variable simply does not exist. ## Why ansible_hostname Requires gather_facts Ansible facts are collected by the `setup` module, which runs automatically at the beginning of each play when `gather_facts: true` (the default). Facts include: | Fact Variable | Description | Example Value | |---|---|---| | `ansible_hostname` | Short hostname of the target | `webserver01` | | `ansible_fqdn` | Fully qualified domain name | `webserver01.example.com` | | `ansible... --- ## Fix Ansible Vault — No Secrets Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-attempting-to-decrypt-but-no-vault-secrets-found Description: Learn to troubleshoot and resolve "Attempting to decrypt but no vault secrets found" error in Ansible Vault with a live Playbook and practical fix. Today we're going to talk about Ansible troubleshooting, specifically about the attempt to decrypt but no vault secrets found error. ## Link - https://docs.ansible.com/ansible/latest/user_guide/vault.html ## Playbook Live Playbook of Ansible Vault in Playbook problem and fix the error: [code example] The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the connection failed error and how to solve it! Every time we would like to use Ansible Vault to store our sensitive information (passwords, access keys, configuration, etc/) encrypted, we need to specify a password for the decryption of the file. The screen error simply reminds us that the password is incorrect or not specified. The solution is relatively easy once you understand the underlying Ansible Vault concept. ## code - playbook_with_vault.yml [code example] - mypassword.yml [code example] ### error execution [code example] ## fix execution We need to specify the ` --ask-vault-password` or `--vault-password-file` option of the `ansible-playbook` tool when using Ansible Vault file. [code example] ## Conclusion Now you know better how to troubleshoot the Ansible error: attempting to decrypt but no vault secrets found. --- ## Fix Ansible Vault "Attempting to Decrypt but No Vault Secrets Found" Error URL: https://www.ansiblebyexample.com/articles/fix-ansible-vault-no-vault-secrets-found Description: Resolve the Ansible Vault decryption error. Learn to pass vault passwords via --ask-vault-pass, password files, and environment variables. # Fix Ansible Vault "No Vault Secrets Found" ## The Error [code example] This happens when your playbook references vault-encrypted variables but you didn't provide the vault password. ## Solution 1: Pass Password Interactively [code example] ## Solution 2: Use a Password File [code example] Set it permanently in `ansible.cfg`: [code example] ## Solution 3: Environment Variable [code example] ## Solution 4: Multiple Vault IDs [code example] ## Common Mistakes ### Encrypted File in Inventory [code example] ### Wrong Password [code example] This means the password is wrong, not missing. Double-check your vault password. ## Quick Reference [code example] ## Conclusion Always provide the vault password via `--ask-vault-pass`, a password file, or the `ANSIBLE_VAULT_PASSWORD_FILE` environment variable. Set `vault_password_file` in `ansible.cfg` so you never forget. --- ## Fix Ansible VMware Certificate Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-vmware-certificate-verify-failed-connecting-to-vcenter-or-esxi Description: Learn how to resolve the "certificate verify failed" error in Ansible when connecting to VMware vCenter. Follow our step-by-step guide for a smooth fix. ## Ansible troubleshooting - VMware certificate verify failed connecting to vCenter or ESXi Today we're going to talk about Ansible troubleshooting, specifically about the "Unable to connect to vCenter or ESXi API [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (\_ssl.c:897)" message and enable Ansible For VMware. This fatal error message happens when the Ansible controller is not able to connect to your VMware Infrastructure. The root cause might be a self-signed SSL certificate or a chain-of-trust not correctly installed in your Ansible Controller. ## Playbook How to reproduce, troubleshoot, and fix the error "Unable to connect to vCenter or ESXi API[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (\_ssl.c:897)". The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the "Unknown error while connecting to vCenter or ESXi API [Errno -2] Name or service not known" and how to solve it! In this Playbook, I'm going to reproduce the error and fix using the correct VMware hostname and verify the network configuration on a demo machine. ## error code - vm_info.yml [code example] - vars.yml [code example] - inventory [code example] ## error execution [code example] ## fix code It's possible to avoid SSL certificates validation by setting the parameter `validate_certs`. For a self-signed certificate, you need to disable the SSL certificate validation. However, I strongly recommend di create a cu... --- ## Fix Ansible VMware PyVmomi Error URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-vmware-failed-to-import-pyvmomi Description: Let’s troubleshoot together the Ansible fatal error “Failed to import the required Python library (PyVmomi)” to find the root cause, install the. ## Ansible troubleshooting — VMware Failed to Import PyVmomi Today we’re going to talk about Ansible troubleshooting, specifically about the “Failed to import the required Python library (PyVmomi)” message and enable Ansible For VMware. This fatal error message happens when we are trying to execute some code against your VMware Infrastructure without the necessary Python SDK for the VMware vSphere API. These circumstances are usually related to the configuration of your Ansible Controller node and usually are not related to Ansible Playbook. ## Playbook The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically the “Failed to import the required Python library (PyVmomi)” and how to solve it! In this Playbook, I’m going to reproduce the error and fix using the PIP, the Python Package Manager on a demo machine. ### error execution [code example] ### fix code [code example] ### fix execution [code example] ## Conclusion Now you know better how to troubleshoot the Ansible “Failed to import the required Python library (PyVmomi)” message and move forward with your Ansible For VMware project. --- ## Fix Ansible WinRM Connection Errors URL: https://www.ansiblebyexample.com/articles/fix-ansible-winrm-connection-errors-windows Description: Troubleshoot Ansible WinRM connection errors for Windows hosts. Complete setup guide for WinRM, HTTPS certificates, authentication, and pywinrm. # Fix Ansible WinRM Connection Errors ## The Error [code example] ## Step 1: Install pywinrm [code example] ## Step 2: Configure Inventory [code example] ## Step 3: Enable WinRM on Windows Run this PowerShell script **on the Windows host** as Administrator: [code example] Or use the Ansible-provided script: [code example] ## Common Errors ### Connection Refused (port 5985/5986) [code example] ### Certificate Validation Error [code example] ### Authentication Failed [code example] ### Timeout Error [code example] ## Test Connection [code example] ## Conclusion WinRM setup requires configuration on both the Ansible controller (pywinrm) and the Windows host (WinRM listener). Use HTTPS in production, NTLM for authentication, and the Ansible-provided setup script for quick configuration. --- ## Fix Ansible WinRM Errors — PowerShell URL: https://www.ansiblebyexample.com/articles/how-to-solve-winrm-configuration-errors-in-powershell Description: Resolve WinRM configuration errors for Ansible Windows automation. Fix HTTPS listeners, TrustedHosts, certificate issues, and firewall rules. ## Introduction PowerShell Remoting is a powerful feature that allows administrators to manage remote systems seamlessly. However, setting up PowerShell Remoting isn’t always a straightforward process. Sometimes, you may encounter errors like the one below when trying to enable PowerShell Remoting: [code example] This error message indicates that the WinRM (Windows Remote Management) configuration is encountering issues related to network connection types, typically when the network connection is set to “Public.” In this article, we’ll guide you through solving this issue and enabling PowerShell Remoting on your Windows system. ### Understanding the Error The error message you encountered is quite descriptive. It tells us that the WinRM configuration failed because the network connection type is set to “Public.” WinRM firewall exceptions are not enabled for “Public” network profiles, which is a security measure in Windows. To resolve this issue, we need to change the network connection type to either “Domain” or “Private.” ## Step-by-Step Solution Follow these steps to solve the WinRM configuration error and enable PowerShell Remoting: ### 1. Open PowerShell as Administrator Make sure you run PowerShell as an administrator to have the necessary permissions to modify the network settings. ### 2. Check Current Network Connection Profile Run the following command to check the current network connection profile: [code example] This command will provide information about y... --- ## Fix Ansible YAML Syntax Errors — The Complete Debugging Guide URL: https://www.ansiblebyexample.com/articles/fix-ansible-yaml-syntax-errors-debugging-guide Description: Debug and fix YAML syntax errors in Ansible playbooks. Common mistakes with indentation, colons, quotes, and booleans with practical examples. # Fix Ansible YAML Syntax Errors — The Complete Debugging Guide ## Quick Syntax Check Always validate before running: [code example] ## Error 1: Indentation Mistakes [code example] ## Error 2: Missing Colon Space [code example] ## Error 3: Unquoted Special Characters [code example] ## Error 4: Boolean Gotchas [code example] ## Error 5: Tabs Instead of Spaces [code example] ## Error 6: Multiline Strings [code example] ## Debugging Tools [code example] ## Conclusion 90% of Ansible YAML errors come from indentation, missing spaces after colons, unquoted special characters, and tabs. Use `--syntax-check` and `ansible-lint` to catch them before running. --- ## Fix Conda Activate — CommandNotFoundError URL: https://www.ansiblebyexample.com/articles/solving-the-conda-activation-error Description: Fix 'CommandNotFoundError: conda activate is not available' error. Initialize conda for bash/zsh, update .bashrc, and fix common activation issues. ## Introduction If you're working in data science, machine learning, or any field involving Python programming, you might be familiar with Conda – a powerful package and environment management system. However, a common hurdle that many users face is an error when trying to activate a Conda environment: "conda error: run 'conda init' before 'conda activate'". This message indicates that Conda hasn't been properly initialized in your shell environment, but don't worry – it's a fixable issue! ## Why Does This Error Occur Conda environments need to be activated to switch between different Python versions or sets of packages. The `conda activate` command is essential for this, but it requires Conda to be initialized in your shell. Without initialization, your shell can't recognize the `conda activate` command, leading to the error. ## How to Fix It 1. **Initialize Conda for Your Shell**: Run `conda init`. This command modifies your shell's startup file (like `.bashrc` for Bash, `.zshrc` for Zsh), integrating Conda into your shell environment. This is a one-time setup – once done, you won't need to repeat it for future sessions. 2. **Temporary Solution with `eval "$(conda shell.bash hook)"`**: If, for some reason, you prefer not to run `conda init`, there's a workaround. Use `eval "$(conda shell.bash hook)"`. It's a temporary measure that initializes Conda for the current shell session without altering the startup file. Remember, this is a session-specific solution and needs ... --- ## Fix Google Pixel Bootloop — Sideload OTA Update Guide URL: https://www.ansiblebyexample.com/articles/fix-google-pixel-bootloop-sideloading-ota-update Description: Fix a bootlooping Google Pixel with ADB sideload OTA update. Step-by-step recovery mode, fastboot, and factory image instructions for all models. ## Introduction Bootloop issues can be frustrating, especially when they occur on your Google Pixel device. If you find yourself stuck in a bootloop, don’t panic — there are steps you can take to resolve the problem. In this guide, we’ll walk you through the process of using ADB and Fastboot utilities to fix the bootloop issue on your Google Pixel. Experiencing technical issues with your Google Pixel can be a source of frustration, especially when faced with a bootloop. However, there’s hope in the form of Rescue OTA (Over-The-Air) updates, a solution that can revive your device without the need for extensive data wipes or bootloader unlocking. In this guide, we’ll walk you through the process of applying a Rescue OTA to your Pixel, providing detailed steps for Windows 10, while emphasizing that the basic concepts apply to MAC, Linux, and other Windows versions. ## Install Android SDK Platform Tools Android SDK Platform-Tools is a component of the Android SDK. It includes tools that interface with the Android platform, primarily `adb` and `fastboot`. ### Step 1: Downloading ADB and Fastboot Utilities The first step in resolving a bootloop issue is to download the latest version of ADB and Fastboot utilities from Google’s official website (https://developer.android.com/tools/releases/platform-tools). These tools are essential for interacting with your device at a low level and can help you diagnose and fix the problem. 1. Visit Google’s website and download the ADB and Fast... --- ## Fix ModuleNotFoundError: No module named 'ansible' URL: https://www.ansiblebyexample.com/articles/ansible-troubleshooting-modulenotfounderror-no-module-named-ansible-error Description: Fix the ModuleNotFoundError: No module named 'ansible' error. Diagnose Python environment mismatches, PATH issues, pip vs pipx installs, and virtual. ## Introduction The `ModuleNotFoundError: No module named 'ansible'` error occurs when Python cannot find the Ansible package in its module search path. This typically happens when Ansible is installed in a different Python environment than the one your script uses, or when using `ansible-core` (which doesn't provide the `ansible` top-level package the same way). This article covers every common cause and its fix. ## The Error ### Example Script [code example] ### Error Output [code example] ## Cause 1: Ansible Not Installed for This Python The most common cause — Ansible is installed with a different Python version or not installed at all. ### Diagnose [code example] ### Fix [code example] ## Cause 2: Multiple Python Versions Many systems have Python 3.9, 3.10, 3.11, and 3.12 installed simultaneously. Ansible might be under one version while your script runs another. ### Diagnose [code example] ### Fix [code example] ## Cause 3: Virtual Environment Not Activated Ansible is in a virtualenv, but your script runs outside it (or vice versa). ### Diagnose [code example] ### Fix [code example] ### Create a Dedicated Ansible Virtual Environment [code example] ## Cause 4: pipx Installation If you installed Ansible with `pipx`, it's isolated and not available to other Python scripts. ### Diagnose [code example] ### Fix [code example] ## Cause 5: ansible-core vs ansible Package `ansible-core` provides the core runtime (`ansible.builtin`), while the `a... --- ## Fix Ubuntu apt dpkg Lock Error — Quick Solutions URL: https://www.ansiblebyexample.com/articles/ubuntu-resolving-apt-dpkg-lock-errors Description: Fix 'Unable to acquire the dpkg frontend lock' error on Ubuntu. Remove stale locks, kill stuck processes, and prevent lock conflicts safely. ## Introduction One of the most common errors Ubuntu and Debian administrators encounter is the dpkg frontend lock error. This frustrating message prevents you from installing, updating, or removing packages — effectively blocking all package management operations until resolved. This guide covers the root causes, safe resolution methods, and how to prevent the error from recurring — including automating the fix with Ansible. ## Understanding the Error The full error typically looks like this: [code example] Or the related variant: [code example] ### What Causes This Error? The lock file (`/var/lib/dpkg/lock-frontend`) is a safety mechanism. It ensures only one process modifies the package database at a time, preventing corruption. Common causes include: | Cause | Description | |-------|-------------| | **Unattended upgrades** | The `unattended-upgrades` service is running background updates | | **Concurrent apt commands** | Two terminals both running `apt install` simultaneously | | **Crashed package manager** | A previous `apt` or `dpkg` process crashed without releasing the lock | | **Cloud-init** | On cloud instances, cloud-init may run package updates on first boot | | **Snapd auto-updates** | The snap daemon can hold dpkg locks during snap refreshes | ## Step-by-Step Resolution ### Step 1: Identify the Process Holding the Lock First, find out which process owns the lock: [code example] Or use the PID from the error message: [code example] To see all apt... --- ## Fixing Kubernetes PersistentVolume Configuration Error URL: https://www.ansiblebyexample.com/articles/fixing-kubernetes-persistentvolume-configuration-error Description: Fix the Kubernetes PersistentVolume strict decoding error for unknown field spec.PersistentVolumeReclaimPolicy. Step-by-step guide with correct YAML. ## Introduction When working with Kubernetes PersistentVolumes, YAML configuration errors are among the most common issues administrators face. One frequently encountered error involves the `PersistentVolumeReclaimPolicy` field, where incorrect casing or placement triggers a strict decoding error that prevents volume creation. This guide walks through the error, explains why it happens, shows the correct configuration, and covers PersistentVolume best practices. ## The Error When you apply a PersistentVolume YAML file with incorrect field casing, Kubernetes returns: [code example] ## Root Cause The error occurs because Kubernetes YAML fields are **case-sensitive**. The correct field name is `persistentVolumeReclaimPolicy` (camelCase starting with lowercase `p`), not `PersistentVolumeReclaimPolicy` (PascalCase starting with uppercase `P`). Common mistakes that trigger this error: | Incorrect | Correct | |-----------|---------| | `spec.PersistentVolumeReclaimPolicy` | `spec.persistentVolumeReclaimPolicy` | | `spec.AccessModes` | `spec.accessModes` | | `spec.Capacity` | `spec.capacity` | | `spec.StorageClassName` | `spec.storageClassName` | Kubernetes API uses **strict decoding** by default, meaning any unrecognized field (including incorrectly cased ones) will be rejected. ## Correct PersistentVolume Configuration ### NFS PersistentVolume [code example] ### hostPath PersistentVolume (Development) [code example] ### AWS EBS PersistentVolume [code example] ## Un... --- ## Four Methods to Configure PowerShell MaxMemoryPerShellMB URL: https://www.ansiblebyexample.com/articles/four-methods-to-configure-maximum-powershell-memory-in-windows-server Description: Configure PowerShell MaxMemoryPerShellMB on Windows Server via CLI, PowerCLI, batch, and Ansible. Fix WinRM memory errors in Ansible Windows automation. ## Introduction The `MaxMemoryPerShellMB` WinRM setting controls how much memory each PowerShell session can use. When Ansible connects to Windows hosts via WinRM, complex tasks — large file transfers, registry operations, or DSC configurations — can exceed the default 1024 MB limit, causing "not enough memory" errors. This article covers four methods to configure this setting and how to automate it with Ansible across your fleet. ## Why MaxMemoryPerShellMB Matters for Ansible Ansible's WinRM connection creates a PowerShell session on each Windows host. When tasks require significant memory (large variable sets, file content, or complex operations), the session can hit the memory limit: [code example] | Setting | Default | Recommended | Description | |---|---|---|---| | `MaxMemoryPerShellMB` | 1024 | 2048-4096 | Memory per PowerShell session | | `MaxConcurrentUsers` | 10 | 10-25 | Simultaneous WinRM users | | `IdleTimeout` | 7200000 (2h) | 7200000 | Idle session timeout (ms) | | `MaxProcessesPerShell` | 25 | 25 | Processes per shell | | `MaxShellsPerUser` | 30 | 30 | Concurrent shells per user | ## Method 1: PowerShell Command Line The most direct approach — navigate the WSMan provider: [code example] ### View All Shell Settings [code example] ## Method 2: PowerShell One-Liners Quick get/set without navigating: [code example] ### Remote Configuration via PowerShell [code example] ## Method 3: Batch Command (winrm.cmd) Use `winrm.cmd` from Command Prompt — use... --- ## Generate Clean YAML Output from Ansible Facts URL: https://www.ansiblebyexample.com/articles/generate-clean-yaml-output-from-ansible-facts Description: Discover how to generate clean YAML output from Ansible facts using Jinja2 templating, ensuring properly formatted data for easy reporting. Ansible is a powerful tool for automating tasks, but when working with dynamically generated data, such as Ansible facts, it can sometimes be tricky to produce clean, well-formatted output. This article demonstrates how to use Jinja2 templating within an Ansible playbook to transform facts into clean YAML, ensuring proper indentation and formatting. In this example, we'll look at a different scenario: transforming networking data (like interfaces, IP addresses, and MAC addresses) into a nicely formatted YAML structure. We'll cover how to loop through facts, control whitespace in Jinja2, and generate a neat YAML file. ## **Scenario: Formatting Network Interfaces** Imagine you are managing a fleet of servers and you need to produce a YAML report that lists each network interface's details, including its name, IP address, MAC address, and the status of the connection. Here's an Ansible task that gathers network facts and formats them into clean YAML output. ## Ansible Playbook Example [code example] ## Breaking Down the Example 1. **Gathering Facts**: We start by setting `gather_facts: yes`, which collects information about the target machine. In this case, we focus on the `ansible_interfaces` fact, which contains data about each network interface on the machine. 2. **Looping Through Interfaces**: Using Jinja2 templating, we iterate over the `ansible_interfaces` dictionary. For each interface, we access its name, MAC address, IP address, and status (whether it's... --- ## Get VMware vSphere Virtual Machine UUID — Ansible module vmware_guest_info URL: https://www.ansiblebyexample.com/articles/get-vmware-vsphere-virtual-machine-uuid-ansible-module-vmware-guest-info Description: How to automate the gathering of UUID of a specific “myvm” VMware vSphere Virtual Machine using Ansible Playbook and vmware_guest_info module. ## How to Get VMware vSphere Virtual Machine UUID with Ansible? ## Ansible Get VMware vSphere Virtual Machine UUID - `community.vmware.vmware_guest_info` - Gather info about a single VM Let's talk about the Ansible module `vmware_guest_info`. The full name is `community.vmware.vmware_guest_info`, which means that is part of the collection of modules to interact with VMware, community-supported. The module's purpose is to gather info about a single VM. ## Parameters - hostname string / port integer / username string / password string / datacenter string / validate_certs boolean - connection details - name string - Virtual machine name The following parameters are useful in order to Get VMware vSphere Virtual Machine UUID using the module `vmware_guest_info`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `port`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the virtual machine `name` to obtain all information about it. ## Links - `community.vmware.vmware_guest_info` ## Playbook How to Get VMware vSphere Virtual Machine UUID with Ansible. I'm going to show you how to Gather Information about a specific "myvm" VMware Virtual Machine and select the UUID using Ansible Playbook. ### code - vm_uuid.yml [code example] - vars.yml [code example] ### execution [code example] ### idempotency [c... --- ## Getting Started with Amazon EC2 Instances URL: https://www.ansiblebyexample.com/articles/automating-your-cloud-infrastructure-with-ansible-creating-aws-ec2-instances-made-easy Description: Learn how to automate EC2 instance creation on AWS with Ansible. This guide covers essential setup, configuration, and management for seamless cloud. ## Amazon Elastic Compute Cloud (EC2) Amazon Web Services (AWS) is a cloud computing platform that offers a wide range of services to customers, including computing, storage, and databases, among others. One of the most popular services provided by AWS is the Elastic Compute Cloud (EC2), which allows customers to rent virtual servers and run applications on them. EC2 instances are virtual servers in the cloud that can be created, launched, and managed easily. In this article, we'll discuss the basics of EC2 instances and how they work. ### What is an EC2 Instance? An EC2 instance is a virtual server in the AWS cloud that provides compute capacity. It is a scalable computing resource that can be easily launched, configured, and managed. Each instance is created from an Amazon Machine Image (AMI), which is a pre-configured virtual machine image that contains an operating system, applications, libraries, and other necessary components. EC2 instances can be created in various sizes and configurations, depending on the customer's requirements. They can run a variety of operating systems, including Linux, Windows, and macOS. ### How EC2 Instances Work EC2 instances are launched from an AMI and can be configured with various settings, including the instance type, storage, and security settings. Once launched, the instance runs on a virtual machine in the cloud, and customers can access it using various methods, including the AWS Management Console, the AWS Command Line Interf... --- ## Getting Started with Ansible URL: https://www.ansiblebyexample.com/articles/getting-started-with-ansible Description: A beginner-friendly guide to getting started with Ansible, a powerful IT automation tool. Learn what Ansible is, how it works, and how to write your first. ## What is Ansible? If you're new to automation and configuration management, **Ansible** is one of the best tools to start with. It’s **agentless**, uses **YAML**, and it's designed to be simple, powerful, and efficient. Whether you’re managing a few servers or deploying applications to hundreds, Ansible has got you covered. I'm Luca Berton, and welcome to today’s episode of **Ansible Pilot**. ## Why use Ansible? Here are some key reasons Ansible is loved by system administrators and DevOps engineers: * **No agents required** – everything works over SSH or WinRM. * **Simple YAML syntax** – great for beginners. * **Powerful modules** – support for system packages, services, files, cloud, and more. * **Idempotency** – run your playbook multiple times without side effects. * **Extensibility** – build roles, collections, and plugins as your infrastructure grows. ## Key Components of Ansible Let’s break down Ansible into its most important building blocks: * **Inventory**: A file (usually `hosts`) listing the machines you want to manage. * **Modules**: Pre-built units of work – think of them like commands (`ping`, `copy`, `yum`, etc.). * **Playbooks**: YAML files where you define your automation tasks. * **Tasks**: Individual units of work within a playbook. * **Roles**: Reusable collections of tasks, files, vars, and more. * **Collections**: Namespaced bundles of roles, modules, and plugins. ## Prerequisites * A control node (Linux/macOS with Python 3.x). * Managed nod... --- ## Git Checkout a Specific Commit — ansible.builtin.git URL: https://www.ansiblebyexample.com/articles/git-checkout-a-specific-commit-ansible-builtin-git Description: How to checkout a specific commit of a Git repository using Ansible's ansible.builtin.git module. Tested on real machines with clear, copy-paste examples. ## How to Checkout a Specific Commit Using Ansible? Managing code versions effectively is crucial in automation workflows. With Ansible’s `ansible.builtin.git` module, you can checkout a specific commit from a Git repository, ensuring your infrastructure or deployments use the exact version you need. I'm Luca Berton, and in this tutorial, I’ll guide you through checking out a specific commit of a Git repository using Ansible. ## ansible.builtin.git - Part of `ansible-core` - Manages Git checkouts - Supports branches, tags, and commit hashes The `ansible.builtin.git` module enables automated repository management in Ansible playbooks. You can use it to clone repositories, checkout branches, pull changes, and, importantly, checkout a specific commit by using its SHA-1 hash. ## Links - Ansible Git Module Documentation ## Playbook I’ll show you how to checkout a specific commit from a Git repository using an Ansible playbook. ### Execution [code example] ### Playbook Code [code example] ### Explanation: - **`repo`**: Defines the Git repository URL. - **`dest`**: Specifies where to clone the repository. - **`version`**: Points to the exact commit hash to checkout. ## Additional Options ### Force Checkout a Specific Commit If the repository is already cloned, but you want to force-checkout a commit: [code example] ### Checkout a Commit Not Part of a Branch If the commit isn't part of any branch or tag, you might need to specify `refspec`: [code example] ## Before... --- ## Git Large File Storage (LFS) — Handle Big Files in Git URL: https://www.ansiblebyexample.com/articles/git-large-files Description: Fix the 'pack exceeds maximum allowed size' Git error. Set up Git LFS for large files, configure .gitattributes, migrate existing repos, and manage binary. ## Introduction Git is optimized for text files — source code, configs, YAML playbooks. When you push large binary files (ISOs, VM images, datasets, compiled artifacts), you'll hit the `pack exceeds maximum allowed size` error. Git Large File Storage (LFS) solves this by storing large files on a separate server while keeping lightweight pointers in your repo. ## The Error [code example] This happens when: - A single file exceeds the platform's size limit (GitHub: 100MB, GitLab: varies) - The cumulative pack file is too large - Large binary files were committed to history ## Quick Fix: Git LFS ### Install Git LFS [code example] ### Initialize in Your Repo [code example] ### Track Large Files [code example] ### Verify Tracking [code example] ## Understanding .gitattributes [code example] ## File Types to Track with LFS | Category | Extensions | Typical Size | |----------|-----------|-------------| | VM images | `.vmdk`, `.qcow2`, `.vdi`, `.ova` | 1-50 GB | | Archives | `.iso`, `.tar.gz`, `.zip`, `.7z` | 100 MB - 10 GB | | Datasets | `.csv`, `.parquet`, `.h5` | 100 MB - 5 GB | | Media | `.mp4`, `.mov`, `.wav` | 50 MB - 5 GB | | Compiled | `.jar`, `.war`, `.whl` | 10 MB - 500 MB | | ML models | `.pt`, `.onnx`, `.pb`, `.safetensors` | 100 MB - 50 GB | ## Migrate Existing Repo to LFS If large files are already in your Git history: [code example] > **Warning:** `migrate import` rewrites Git history. Coordinate with your team before running this. ### Migrate a S... --- ## Google Gemini 1.5 Pro Surpasses GPT-4o in AI Leaderboards URL: https://www.ansiblebyexample.com/articles/google-gemini-1-5-pro-surpasses-gpt-4o-in-ai-leaderboards Description: Google's Gemini 1.5 Pro tops AI leaderboards, beating GPT-4o with advanced capabilities and a high ELO score. Explore its impact on the AI landscape. # Google Gemini 1.5 Pro Surpasses GPT-4o in AI Leaderboards ## Introduction Google Gemini 1.5 Pro Surpasses GPT-4o in AI Leaderboards. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Google Gemini 1.5 Pro Surpasses GPT-4o in AI Leaderboards requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6... --- ## google.cloud 1.14.0 - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/google-cloud-1-14-0-whats-new-and-how-to-test Description: google.cloud 1.14.0 refactors AlloyDB, Cloud Build, Colab and Vertex AI modules to use a shared gcp_v2.py module_utils base. # google.cloud 1.14.0 - Whats New and How to Test ## Introduction `google.cloud` is the Ansible collection that provides modules and plugins for managing Google Cloud Platform resources, including Compute Engine, Cloud Storage, IAM, AlloyDB, Cloud Build, Colab, and Vertex AI. Version 1.14.0 has just landed on Ansible Galaxy, and this post covers exactly what changed and how to install and verify it. ## Whats New This release is a minor version bump and, based on the collection's own changelog, contains a single change: several groups of modules have been migrated to a shared, updated module_utils base. ### Minor Changes - `gcp_alloydb_*`, `gcp_cloudbuild_*`, `gcp_colab_*`, `gcp_vertexai_*` modules now use `plugins/module_utils/gcp_v2.py` instead of their previous module_utils implementation (PR #763). This is an internal refactor rather than a behavioral or interface change for playbook authors. The affected module families are: | Module family | Resource area | | --- | --- | | `gcp_alloydb_*` | AlloyDB clusters and instances | | `gcp_cloudbuild_*` | Cloud Build triggers and workers | | `gcp_colab_*` | Vertex AI Colab Enterprise runtimes | | `gcp_vertexai_*` | Vertex AI endpoints, models, and datasets | Consolidating these modules onto `gcp_v2.py` brings them in line with the newer GCP module_utils pattern already used elsewhere in the collection, which should make future maintenance and bugfixes across these four resource families more consistent. No other minor ch... --- ## Google.Cloud Collection 1.15.0 - New Binary Authorization and Container Analysis Modules, Inventory Plugin Fixes URL: https://www.ansiblebyexample.com/articles/google-cloud-collection-1-15-0-new-binary-authorization-and-container-analysis-modules-inventory-plugin-fixes Description: Google.Cloud 1.15.0 adds binauthz and container analysis modules, fixes gcp_compute inventory folder resolution, and more. # Google.Cloud Collection 1.15.0 - New Binary Authorization and Container Analysis Modules, Inventory Plugin Fixes ## Introduction `google.cloud` is the Ansible Content Collection that provides modules, inventory plugins, and module utilities for managing Google Cloud Platform resources: Compute Engine, Cloud SQL, AlloyDB, Cloud Build, Vertex AI, IAM, and more, all driven from Ansible playbooks against the GCP APIs. Version 1.15.0 has just landed, replacing 1.14.0, and it brings two new module families plus a round of fixes to the `gcp_compute` dynamic inventory plugin, particularly around folder-based project resolution. ## Whats New ### Minor Changes - `gcp_alloydb_*` - updated to the most recent version generated from MMv1. - `gcp_binaryauthorization_*` - four new modules added for attestor/policy management plus accompanying info modules (PR #782). - `gcp_cloudbuild_trigger` - updated to the most recent version generated from MMv1. - `gcp_cloudbuildv2_*` - updated to the most recent version generated from MMv1. - `gcp_colab_*` - updated to the most recent version generated from MMv1. - `gcp_compute` inventory plugin - now prints an aggregate warning at the end of a sync when `folders:` is used and one or more resolved projects were skipped, summarizing how many out of the total were affected. - `gcp_containeranalysis_*` - two new modules added, a container analysis module and its matching info module (PR #782). - `gcp_vertexai_*` - updated to the most recent version ... --- ## Handle Yum/DNF Failures in Ansible — Troubleshooting and Best Practices URL: https://www.ansiblebyexample.com/articles/best-practices-for-handling-yum-command-failures-in-ansible Description: Troubleshoot and handle Yum/DNF package manager failures in Ansible playbooks. Covers lock files, repo errors, dependency conflicts, retry patterns. ## Introduction Yum and DNF package operations can fail for many reasons — lock files, repository errors, dependency conflicts, network timeouts, or disk space. This guide covers systematic troubleshooting patterns for Ansible playbooks that manage packages on RHEL, CentOS, Fedora, and other Red Hat family systems. ## Common Errors and Solutions ### 1. Yum Lock File (Another Process Running) [code example] [code example] Or kill stale processes: [code example] ### 2. Repository Errors [code example] [code example] ### 3. Dependency Conflicts [code example] [code example] ### 4. GPG Key Errors [code example] [code example] ### 5. Disk Space Issues [code example] [code example] ## Retry Pattern [code example] ## Error Handling Patterns ### Block/Rescue [code example] ### Conditional Error Handling [code example] ## Yum vs DNF Module | Feature | `ansible.builtin.yum` | `ansible.builtin.dnf` | |---------|----------------------|----------------------| | RHEL/CentOS 7 | ✓ | ✗ | | RHEL/CentOS 8+ | ✓ (wrapper) | ✓ (native) | | Fedora | ✓ (wrapper) | ✓ (native) | | Module groups | ✓ | ✓ | | `skip_broken` | ✓ | ✓ | | `allowerasing` | ✗ | ✓ | | Performance | Slower | Faster | ### Cross-Platform Pattern [code example] The `package` module auto-selects `yum` or `dnf` based on the OS. ## Check Mode (Dry Run) [code example] [code example] ## Conditional Reboots Only reboot after kernel updates, not regular package installs: [code example] ## Diagnostic ... --- ## Handling Primary Variable Changes Without Breaking Dependencies URL: https://www.ansiblebyexample.com/articles/handling-primary-variable-changes-without-breaking-dependencies Description: Learn how to address issues caused by changes to primary variables in your configuration or scripts. Discover strategies like validation, error handling,. ## Understanding the Issue: Breaking Dependencies with Variable Changes Changing a primary variable in a configuration or script can unintentionally break dependent variables or components. Let’s dive into the problem and explore strategies to mitigate these issues. ### Problem Analysis 1. **Variable Dependency:** If `foo` is the primary variable and `foo.bar` is derived or dependent on it, altering `foo` may invalidate `foo.bar` if it relies on a specific structure or value in `foo`. 2. **Dynamic Referencing:** Other variables or functions referencing `foo.bar` without a fallback mechanism or proper error handling may fail when `foo` is modified. 3. **Scope or Mutability:** In some languages or systems, changes to a primary variable may propagate unexpectedly, impacting dependent variables globally. --- ### Solutions #### 1. Default Values and Fallbacks Ensure dependent variables like `foo.bar` have a default value or fallback mechanism to handle changes in `foo`. [code example] #### 2. Validation Validate changes to `foo` before applying them. Ensure `foo` maintains the correct structure or format to prevent `foo.bar` from breaking. Example in Python: [code example] #### 3. Isolate Dependencies Refactor configurations so dependent variables don’t rely directly on mutable states in `foo`. [code example] #### 4. Immutable References If supported by your system, make `foo` immutable and create a new variable instead of altering `foo` directly. ###... --- ## Hands-on Ansible Automation Book Presentation URL: https://www.ansiblebyexample.com/articles/hands-on-ansible-automation-book-presentation Description: Explore Luca Berton new book, "Hands-On Ansible Automation," designed for beginners and experts alike, covering Ansible latest features, practical. Hi friends. This is Luca Berton, and I’m here to present to you my latest creation, this wonderful Hands-On Ansible automation book. I’m super proud of this book because it’s something that I really would like to create for a long time. As you can see, this is not a one-day read, and I was trying to distill everything that I know about Ansible inside this book. [](https://amzn.to/43HEMuL) {{}} Let me first of all clarify that this book was designed for people who would like to learn Ansible from the beginning or for some experts who would like to update their knowledge about Ansible. So the purpose is just there are wonderful books in the market about Ansible. However, they were created five or six years ago when Ansible was on the rise, and they’re lacking some information. Especially after the 2.9 transitions, we’re talking about the, since Ansible 2.10 onward, everything changed, especially with the introduction of the Ansible collection and then kind of like adding this part of the book, but not like designing everything around the collection. This book was created with this intent in mind. This is why the first section is just installing and is totally about Ansible. And then, we are going to explore more about Ansible architecture and how they build a collaboration. And let me also show you exactly that. There are a lot of code inside of this book. This is the best part of learning. I have always had this kind of stuff. You know me for the Ansible pilot project, a... --- ## Hands-on Ansible Automation by BPB Online book URL: https://www.ansiblebyexample.com/articles/hands-on-ansible-automation Description: Learn to set up and configure Ansible environments, automate tasks, manage configurations, deploy applications, and troubleshoot for enhanced. [](https://amzn.to/43HEMuL) {{}} ## WHAT YOU WILL LEARN - Gain a comprehensive knowledge of Ansible and its practical applications in Linux and Windows environments. - Set up and configure Ansible environments, execute automation tasks, and manage configurations. - Deploy applications and orchestrate complex workflows using Ansible. - Learn advanced techniques such as utilizing the Ansible Automation Platform for improved performance. - Acquire troubleshooting skills, implement best practices, and design efficient playbooks to streamline operations. - Revolutionize infrastructure management, automate routine tasks, and achieve unprecedented efficiency and scalability within organizations. ## KEY FEATURES - Comprehensive coverage of Ansible essentials and practical applications in Linux and Windows environments. - Step-by-step guidance for setting up and configuring Ansible environments. - In-depth exploration of playbook development for automating configuration management, deployment, and orchestration tasks. - Advanced techniques for leveraging Ansible Automation Platform and Morpheus for enhanced performance. - Troubleshooting strategies and best practices to overcome roadblocks in Ansible implementation. - Enhance Ansible workflows with troubleshooting, best practices, and integrations for optimal performance and expand capabilities in configuration management, GUI, RBAC, and third-party systems. ## Description Hands-on Ansible Automation is a comprehensive guide by... --- ## How to Change a User Password with Ansible URL: https://www.ansiblebyexample.com/articles/how-to-change-a-user-password-with-ansible Description: Change user passwords with Ansible — SHA-512 hashing, Vault encryption, bulk updates, and idempotent password management. ## Introduction Changing user passwords across multiple servers manually is tedious and error-prone. The `ansible.builtin.user` module provides a secure, idempotent way to set and change passwords on Linux, macOS, and FreeBSD systems. This article covers password hashing methods, Vault integration, bulk updates, idempotency pitfalls, and best practices for production environments. ## How Password Hashing Works Linux stores passwords as hashes in `/etc/shadow`. Ansible **does not accept plaintext passwords** — you must provide a pre-hashed value. The `password_hash` filter handles this: [code example] ### Supported Hash Algorithms | Algorithm | Filter Value | Strength | Use Case | |---|---|---|---| | SHA-512 | `sha512` | Strong (recommended) | Linux systems | | SHA-256 | `sha256` | Good | Older systems | | Blowfish | `blowfish` | Good | FreeBSD | | MD5 | `md5` | Weak (avoid) | Legacy only | ## Basic Password Change [code example] ### Execution Output [code example] ### Verify Login [code example] ## The Idempotency Problem Without a fixed salt, `password_hash` generates a **random salt on every run**, producing a different hash each time. This means Ansible reports `changed` on every execution — even when the password hasn't actually changed: [code example] ### Using inventory_hostname as Salt A common pattern that gives each host a unique but consistent salt: [code example] ### Using a Secret Salt from Vault [code example] ## Securing Passwords with Ansib... --- ## How to Create a New LVM Partition with Ansible URL: https://www.ansiblebyexample.com/articles/create-a-new-lvm-partition-ansible-module-parted Description: Discover how to automate the creation of LVM partitions on Linux systems using Ansible. This guide walks you through using the community.general.parted. ## How to Create a New LVM Partition with Ansible? ## Ansible Create a New LVM Partition - `community.general.parted` - Configure block device partitions Today we're talking about the Ansible module parted. The full name is `community.general.parted`, which means that is part of the collection of modules "community.general" maintained by the Ansible Community. The purpose of the module is to Configure block device partitions. ## Parameters - `device` string - The block device (disk) where to operate - `label` string - msdos/gpt/aix/amiga/bsd/dvh/loop/mac/pc98/sun - `number` integer - 1 - `state` string - info/present/absent - partition information / create / delete - `fs_type` string - If specified and the partition does not exist, will set filesystem type to the given partition. - `flags` list - A list of the flags that have to be set on the partition. The parameters of module `parted` for the creation of a New LVM Partition use case. The only required parameter is `device`, the block device (disk) where to operate. The system default partition table is `msdos` but you could specify a different one, such as `gpt`. The parameter `number` allows you to specify the partition number to work, required for almost any operations The parameter `state` specify the status of the specified partition. The default option `info` only gives you the partition information, the option `present` means to create the partition, and the option `absent` means that the partition must be delet... --- ## How to Create Ansible Inventory File URL: https://www.ansiblebyexample.com/articles/how-to-create-ansible-inventory-file Description: Write static and dynamic inventory files with groups, variables, and children. With clear, copy-paste, step-by-step examples. # How to Create Ansible Inventory File ## Introduction Write static and dynamic inventory files with groups, variables, and children. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Write static and dynamic inventory files with groups, variables, and children. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Create Custom Ansible Module URL: https://www.ansiblebyexample.com/articles/how-to-create-custom-ansible-module Description: Write custom modules in Python for operations not covered by existing modules. Tested on real machines with clear, copy-paste examples. # How to Create Custom Ansible Module ## Introduction Write custom modules in Python for operations not covered by existing modules. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Write custom modules in Python for operations not covered by existing modules. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Debug Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/how-to-debug-ansible-playbooks Description: Debug failing playbooks with verbosity levels, debug module, and strategy plugins. Tested, copy-paste examples included. # How to Debug Ansible Playbooks ## Introduction Debug failing playbooks with verbosity levels, debug module, and strategy plugins. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Debug failing playbooks with verbosity levels, debug module, and strategy plugins. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Fix Ansible Connection Failures: Complete Troubleshooting Guide URL: https://www.ansiblebyexample.com/articles/connection-failed-ansible-troubleshooting Description: Complete guide to troubleshooting Ansible connection failures. Fix SSH timeouts, authentication errors, WinRM issues, privilege escalation failures. Ansible connection failures are the most common errors when running playbooks. They occur when Ansible cannot establish a connection to the target host — usually via SSH for Linux or WinRM for Windows. This guide covers every major connection error, its root cause, and how to fix it. ## Understanding Ansible Connection Types Ansible supports multiple connection plugins: | Plugin | Protocol | Default Port | Used For | |--------|----------|-------------|----------| | `ssh` | SSH | 22 | Linux/Unix hosts (default) | | `paramiko` | SSH | 22 | Legacy SSH fallback | | `winrm` | WinRM | 5985/5986 | Windows hosts | | `local` | None | N/A | Running on the control node itself | | `docker` | Docker API | N/A | Docker containers | | `network_cli` | SSH | 22 | Network devices | ## Common SSH Connection Errors ### 1. Operation Timed Out **Error message:** [code example] **Root causes:** - Host is powered off or not booted - Network interface is disabled - Firewall blocking port 22 - Wrong IP address or hostname - Network routing issue **Troubleshooting steps:** [code example] ### 2. Permission Denied (Public Key) **Error message:** [code example] **Root causes:** - Wrong SSH key or key not loaded in ssh-agent - Wrong username - `authorized_keys` file missing or wrong permissions - SSH server configured to reject password authentication **Fix:** [code example] In your inventory, specify the key: [code example] ### 3. Host Key Verification Failed **Error message:** [code exa... --- ## How to Get IP Address of Remote Host in Ansible URL: https://www.ansiblebyexample.com/articles/how-to-get-ip-address-of-remote-host-in-ansible Description: Retrieve the IP address of managed nodes using Ansible facts and hostvars. Tested on real machines with clear, copy-paste examples. # How to Get IP Address of Remote Host in Ansible ## Introduction Retrieve the IP address of managed nodes using Ansible facts and hostvars. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Retrieve the IP address of managed nodes using Ansible facts and hostvars. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Handle Ansible Playbook Failures URL: https://www.ansiblebyexample.com/articles/how-to-handle-ansible-playbook-failures Description: Manage failures with ignore_errors, failed_when, block rescue, and retry logic. With clear, copy-paste, step-by-step examples. # How to Handle Ansible Playbook Failures ## Introduction Manage failures with ignore_errors, failed_when, block rescue, and retry logic. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Manage failures with ignore_errors, failed_when, block rescue, and retry logic. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Implement Idempotency in Ansible URL: https://www.ansiblebyexample.com/articles/how-to-implement-idempotency-in-ansible Description: Write idempotent tasks that safely run multiple times without side effects. Tested on real machines with clear, copy-paste examples. # How to Implement Idempotency in Ansible ## Introduction Write idempotent tasks that safely run multiple times without side effects. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Write idempotent tasks that safely run multiple times without side effects. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Install Ansible — pip, apt, dnf & Homebrew URL: https://www.ansiblebyexample.com/articles/ansible-install Description: Install Ansible on Ubuntu, RHEL, CentOS, macOS, and Windows step by step. Covers pip, APT, DNF, Homebrew, and WSL methods with version verification. ## Installing Ansible: A Step-by-Step Guide Ansible is a powerful open-source tool for IT automation, allowing you to manage configurations, deploy applications, and orchestrate complex workflows. This article provides a comprehensive guide to installing Ansible on various operating systems, ensuring you can get started with automating your IT infrastructure efficiently. ## Prerequisites Before installing Ansible, ensure you have the following prerequisites: - A supported operating system (Linux, macOS, or Windows with WSL) - Python 3.6 or later (for some distributions, Python 2.7 is still supported but not recommended) - Access to an internet connection to download Ansible packages ## Installing Ansible on Linux **Debian-based Systems (Ubuntu, Debian)** 1. **Update Your Package Index**: [code example] 2. **Install Ansible**: [code example] 3. **Verify the Installation**: [code example] **Red Hat-based Systems (RHEL, CentOS, Fedora)** 1. **Enable EPEL Repository** (for CentOS): [code example] 2. **Install Ansible** (for Fedora, RHEL): [code example] 3. **Verify the Installation**: [code example] **Arch-based Systems (Arch Linux, Manjaro)** 1. **Install Ansible**: [code example] 2. **Verify the Installation**: [code example] ## Installing Ansible on macOS For macOS, Ansible can be installed using Homebrew. 1. **Install Homebrew** (if not already installed): [code example] 2. **Install Ansible**: [code example] 3. **Verify the I... --- ## How to install Ansible in AlmaLinux 9 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-almalinux-9 Description: Learn how to easily install and maintain Ansible on AlmaLinux 9 using the ansible-core package from the AppStream repository with this simple guide. ## How to install Ansible in AlmaLinux version 9. Today we’re going to talk about the easier way to install and maintain Ansible inside AlmaLinux 9 using the appstream system repository. ## How to install Ansible in AlmaLinux 9 - `ansible-core` included in AppStream repository - `ansible` package not available Today we’re talking about How to install Ansible in AlmaLinux 9. The easier way to install and maintain up-to-date Ansible inside AlmaLinux version 9 is using the `ansible-core` package included in the AppStream distribution repository. Please notice that the package `ansible` isn’t available anymore. It’s not necessary to use the additional EPEL package repository. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - AlmaLinux website ## Playbook Let’s jump into a quick live Playbook of how to install the latest version of Ansible in AlmaLinux. I’m going to install the `ansible-core` package in an AlmaLinux 9 using the AppStream distribution repository. ### code - Install-Ansible-AlmaLinux9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in AlmaLinux using the AppStream repository. --- ## How to install Ansible in Amazon Linux 2 (AWS EC2) — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-amazon-linux-2 Description: How to install Ansible in Amazon Linux 2 using the Amazon Extras Library \"amazon-linux-extras\" and the EPEL (Extra Packages for Enterprise Linux). How to install Ansible in Amazon Linux version 2? Today we're going to talk about the easier way to install and maintain Ansible inside Amazon Linux 2 using the Amazon Extras Library and EPEL repositories. ## How to install Ansible in Amazon Linux 2 - "ansible2" topic in Extras Library repository - "ansible" in Extra Packages for Enterprise Linux (EPEL) additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), Rocky Linux and Scientific Linux (SL), Oracle Linux (OL), and Amazon Linux Today we're talking about How to install Ansible in Amazon Linux 2. The good news is that Ansible is included in the Extras Library included in Amazon Linux 2 repository using the "amazon-linux-extras" command. Another option is to install and maintain Ansible inside Amazon Linux 2 is using the Extra Packages for Enterprise Linux (EPEL) additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), Rocky Linux and Scientific Linux (SL), Oracle Linux (OL), and Amazon Linux. ## Links - Amazon Linux 2 - How do I enable the EPEL repository for my Amazon EC2 instance running CentOS, RHEL, or Amazon Linux? - Extras library (Amazon Linux 2) - Extra Packages for Enterprise Linux (EPEL) ## Playbook Install Ansible in Amazon Linux (EC2) 2 using the Amazon Extras Library and EPEL repositories. Here are the steps on how to install Ansible in Amazon... --- ## How to install Ansible in Arch Linux 2021.12.01 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-archlinux-2021-12-01 Description: The easier way to install the latest version of Ansible and maintain up-to-date in Arch Linux 2021.12.01 using Pacman and the Community repository. How to install Ansible in Arch Linux? Today we're going to talk about the easier way to install and maintain up-to-date Ansible in Arch Linux using the Community repository. ## How to install Ansible in Arch Linux - ansible package included in Community default repositories Today we're talking about How to install Ansible in Arch Linux. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager "pacman". You could expect the latest version of Ansible in the "Community" repository. At the moment is available the latest 5.0. ## Links - https://archlinux.org/packages/community/any/ansible/ ## Playbook Install Ansible in Arch Linux using "pacman" Package Manager using the Community repository. ### code - Install-Ansible-Arch Linux.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Arch Linux using the Community repository. --- ## How to install Ansible in CentOS 8 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-centos-8 Description: Discover the easiest way to install and maintain Ansible on CentOS 8 using the EPEL repository, managed by the Fedora Special Interest Group. How to install Ansible in CentOS version 8. Today we're going to talk about the easier way to install and maintain Ansible inside CentOS 8 using the EPEL repository. ## How to install Ansible in CentOS 8 - use Extra Packages for Enterprise Linux (EPEL) additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), CentOS and Scientific Linux (SL), Oracle Linux (OL) Today we're talking about How to install Ansible in CentOS 8. The easier way to install and maintain Ansible inside CentOS version 8 is using the Extra Packages for Enterprise Linux (EPEL) additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), CentOS and Scientific Linux (SL), Oracle Linux (OL). ## Playbook Let's jump in a quick live Playbook of how to install the latest and a specific version of Ansible in CentOS. ### code - install_ansible_EPEL.sh [code example] ### execution output [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in CentOS using the EPEL repository. --- ## How to install Ansible in CentOS 8 Stream — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-centos-8-stream Description: Learn the easiest way to install and maintain Ansible on CentOS Stream 8 using the EPEL Next repository, managed by the Fedora Special Interest Group. How to install Ansible in CentOS Stream version 8. Today we're going to talk about the easier way to install and maintain Ansible inside CentOS Stream 8 using the EPEL Next repository. ## How to install Ansible in CentOS Stream 8 - use Extra Packages for Enterprise Linux (EPEL) Next additional packages for CentOS Stream The easier way to install and maintain Ansible inside CentOS Stream version 8 is using the Extra Packages for Enterprise Linux (EPEL) Next additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for CentOS Stream. It's very similar to Extra Packages for Enterprise Linux (EPEL) additional packages target for Red Hat Enterprise Linux (RHEL), CentOS, Scientific Linux (SL), and Oracle Linux (OL). ## Playbook Let's jump in a quick live Playbook of how to install Ansible in CentOS Stream version 8. ### code - install-Ansible-CentOS-Stream8.sh [code example] ### execution output [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in CentOS Stream using the EPEL Next repository. --- ## How to install Ansible in CentOS 9 Stream — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-centos-9-stream Description: Learn how to install Ansible on CentOS Stream 9 using the AppStream repository for efficient automation and configuration management. How to install Ansible in CentOS Stream version 9. Today we're going to talk about the easier way to install and maintain Ansible inside CentO Stream version 9 using the system AppStream repository. ## How to install Ansible in CentOS Stream 9 - `ansible-core` in system AppStream repository - use Extra Packages for Enterprise Linux - EPEL Next additional packages for CentOS Stream The easier way to install and maintain Ansible inside CentOS Stream version 9 is using the system AppStream repository. Another way is to use the additional EPEL Next repository. This repository is maintained by the Fedora Special Interest Group and that manages a high-quality set of additional packages for CentOS Stream, similar to Extra Packages for Enterprise Linux (EPEL) additional packages target for Red Hat Enterprise Linux (RHEL), CentOS, and Scientific Linux (SL) and Oracle Linux (OL). See also: Ansible terminology - ansible vs ansible-core packages. ## Links - CentOS Stream Download - EPEL 9 is now available - Introducing CentOS Stream 9 - Extra Packages for Enterprise Linux (EPEL) ## Playbook Install Ansible in CentOS Stream version 9 via AppStream system repository. ### code - Install-Ansible-CentOS-Stream9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in CentOS Stream using the system AppStream reposit... --- ## How to install Ansible in Debian 11 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-debian-11 Description: The easier way to install the latest version of Ansible and maintain up-to-date in Debian 11 using APT and the \"main\" default repository. How to install Ansible in Debian version 11? Today we're going to talk about the easier way to install and maintain Ansible inside Debian using the default "main" repository. ## How to install Ansible in Debian - Included in the "main" default repository Today we're talking about How to install Ansible in Debian. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager "apt". You could expect the latest version of Ansible in the "main" repository. ## Playbook Install Ansible in Debian using the apt package manager and the "main" default repository. ### code - install-ansible-debian.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Debian using the "main" repository. --- ## How to install Ansible in Fedora 34 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-34 Description: How to install and maintain the latest version of Ansible inside Fedora 34 using the default repository with a practical Playbook. How to install Ansible in Fedora version 34. Today we're going to talk about the easier way to install and maintain Ansible inside Fedora 34 using the default repository. ## How to install Ansible in Fedora 34 Today we're talking about How to install Ansible in Fedora 34. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager. You could expect the latest version of Ansible in the updates repository. At the moment is available the latest 2.9. ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Fedora. ### code - install-Ansible-Fedora.sh [code example] ### execution output [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Fedora using the system repository and the DNF package manager. --- ## How to install Ansible in Fedora 35 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-35 Description: How to install and maintain the latest version of Ansible inside Fedora 35 using the default repository with a practical Playbook. How to install Ansible in Fedora version 35. Today we're going to talk about the easier way to install and maintain Ansible inside Fedora 35 using the default repository. ## How to install Ansible in Fedora 35 Today we're talking about How to install Ansible in Fedora 35. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager. You could expect the latest version of Ansible in the updates repository. At the moment is available the latest 2.9. ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Fedora. ### code - install-Ansible-Fedora.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Fedora using the system repository and the DNF package manager. --- ## How to install Ansible in Fedora 36 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-36 Description: How to install and maintain the latest version of Ansible inside Fedora 36 using the system repository with a practical Playbook. How to install Ansible in Fedora version 36. Today we're going to talk about the easier way to install and maintain Ansible inside Fedora 36 using the system repository. ## How to install Ansible in Fedora 36 Today we're talking about How to install Ansible in Fedora 36. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager. You could expect the latest version of Ansible in the updates repository. At the moment is available the latest 2.12 for `ansible-core` and 5.7 for `ansible`. See also: Ansible terminology - ansible vs ansible-core packages. ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Fedora. ### code - install-Ansible-Fedora.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Fedora using the system repository and the DNF package manager. --- ## How to install Ansible in Fedora 37 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-37 Description: How to install and maintain the latest version of Ansible inside Fedora 37 using the system repository with a practical Playbook. How to install Ansible in Fedora version 37. Today we're going to talk about the easier way to install and maintain Ansible inside Fedora 37 using the system repository. ## How to install Ansible in Fedora 37 Today we're talking about How to install Ansible in Fedora 37. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager. You could expect the latest version of Ansible in the updates repository. At the moment is available the latest 2.14 for `ansible-core` and 6.4 for `ansible`. See also: Ansible terminology - ansible vs ansible-core packages. ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Fedora. ### code - install-Ansible-Fedora.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Fedora using the system repository and the DNF package manager. --- ## How to install Ansible in Fedora 38 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-38 Description: How to install and maintain the latest version of Ansible inside Fedora 38 using the system repository with a practical Playbook. How to install Ansible in Fedora version 38. Today we're going to talk about the easier way to install and maintain Ansible inside Fedora 38 using the system repository. ## How to install Ansible in Fedora 38 Today we're talking about How to install Ansible in Fedora 38. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager. You could expect the latest version of Ansible in the updates repository. At the moment is available the latest 2.14.6 for `ansible-core` and 7.6.0 for `ansible`. See also: Ansible terminology - ansible vs ansible-core packages. ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Fedora. ### code - install-Ansible-Fedora.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Fedora using the system repository and the DNF package manager. --- ## How to install Ansible in Fedora 39 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-39 Description: Learn how to install Ansible on Fedora 39 efficiently using dnf, ensuring your system is ready for automation tasks with the latest versions of. ## Introduction Ansible is a powerful open-source automation tool that simplifies the configuration management, application deployment, and task automation processes. In this guide, we will walk through the steps to install Ansible on a Fedora 39 system. At the moment the following versions are available for `ansible-core` 2.16.0 and `ansible` 9.0.0. See also: Ansible terminology - ansible vs ansible-core packages. ## Prerequisites Before you begin, make sure you have: - Access to a Fedora 39 system. - `sudo` or `root` privileges on the system. ## Installation Steps ### 1. Update the System Ensure your system is up to date by running the following commands: [code example] ### 2. Check Ansible Availability Verify if Ansible is already installed by running: [code example] If Ansible is not installed, the command will return `bash: ansible: command not found.` [code example] ### 3. Install Ansible To install Ansible, run the following command: [code example] You may be prompted to confirm the installation. Type 'y' and press Enter. [code example] ### 4. Verify Ansible Installation After the installation is complete, run the following command to verify the installation: [code example] This command should now display information about the installed Ansible version. [code example] ## Additional Information ### Verify Installed To verify the installed Ansible package, you can use the following command: [code example] The output show the exact version i... --- ## How to install Ansible in Fedora 40 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-fedora-40-ansible-install Description: Enhance server management on Fedora 40 with Ansible. This guide covers installing Ansible, updating system packages, and verifying the installation to. ## Introduction With Fedora 40 serving as a robust platform for server management, incorporating automation tools like Ansible significantly enhances efficiency and system management capabilities. This guide walks you through the process of installing Ansible on Fedora 40, ensuring you are equipped to automate your system tasks effectively. ## Prerequisites Before you begin, ensure that you have: - Access to a Fedora 40 server with root privileges. - An active internet connection to download necessary packages. ## Step-by-Step Installation 1. Connect to Your Fedora Server Initiate an SSH connection from your terminal: [code example] Enter the password when prompted to access your server. 2. Switch to Root User For installing system-wide software and performing administrative tasks, switch to the root user: [code example] Enter your password to continue. 3. Update System Packages Before installing any new software, it's a good practice to update your system's package index: [code example] Confirm any prompts to ensure your system has the latest updates. 4. Check Available Ansible Packages To find out the available Ansible packages, you can list them using DNF: [code example] This is the output: [code example] This will show you the latest versions available for installation. 5. Install Ansible Using the DNF package manager, install Ansible: [code example] This command installs Ansible along with its dependencies. Confirm the installation when pro... --- ## How to install Ansible in Gentoo Linux — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-gentoo-linux Description: The easier way to install and maintain up-to-date Ansible inside Gentoo Linux using the \\"portage\\" package manager. With tested, real-world examples. How to install Ansible in Gentoo Linux? Today we're going to talk about the easier way to install and maintain Ansible inside Gentoo using the default "portage" package manager. ## How to install Ansible in Gentoo Linux - Included in "app-admin/ansible" of Portage Today we're talking about How to install Ansible in Gentoo. The good news is that Ansible is included in the "app-admin/ansible" repository so you could install it simply with your usual package manager "emerge" for Portage. You could expect the latest version of Ansible to maintain up-to-date with Portage. ## Links - https://packages.gentoo.org/packages/app-admin/ansible - https://wiki.gentoo.org/wiki/Ansible ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible using emerge for Portage. ### code - Install-Ansible-Gentoo.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Gentoo using the Portage package manager. --- ## How to install Ansible in macOS — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-macos-ansible-install Description: How to install the latest and specific versions of Ansible on macOS using the Homebrew Package Manager. Tested, copy-paste examples included. How to install Ansible in macOS. Today we’re going to talk about the easier way to install and maintain Ansible inside macOS. ## How to install Ansible in macOS Today we’re talking about How to install Ansible in macOS. The easier way to install and maintain Ansible inside macOS is to use the Homebrew Package Manager. It has already a build of Ansible with some versions available. The main advantage of using brew is that it takes care of all the necessary dependencies and it manage also the upgrade process. An alternative could be to use Python PIP but you’re going to download the source code and compile the software. It could be a solution for a developer that want always the latest up-to-date release. ## Demo install Ansible in macOS Let me Playbooknstrate to you how to install the latest and a specific version of Ansible in macOS with Homebrew Package Manager. ### code - install the latest release [code example] - install specific version [code example] ### Execution [code example] ### Verification After the successful installation you could verify in the command line: [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest and a specific version of Ansible in macOS using Homebrew Package Manager. --- ## How to install Ansible in OpenSUSE Leap 15 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-opensuse-leap-15 Description: How to install the latest version of Ansible in openSUSE using the official SUSE Leap \\"update\\" repository. With clear, copy-paste, step-by-step examples. ## How to install Ansible in openSUSE Leap? Today we're going to talk about the easier way to install and maintain Ansible inside openSUSE 15 using the distribution repository. ## How to install Ansible in openSUSE Leap 15 - use repository openSUSE Leap Update Today we're talking about How to install Ansible in openSUSE Leap 15. The easier way to install and maintain Ansible inside openSUSE Leap version 15 is using the Leap Update repository maintained by SUSE. ## Playbook Are you ready to make your hands dirty? Let's jump in a quick live Playbook of how to install the latest version of Ansible in openSUSE. ### code - Install-Ansible-openSUSE-Leap15.sh [code example] ### execution [code example] ### before the execution [code example] ### after the execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in openSUSE using the Leap Update repository. --- ## How to install Ansible in Oracle Linux 8 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-oracle-linux-8-ansible-install Description: Learn how to install the latest Ansible release on Oracle Linux 8 using the oracle-epel-release-el8 repository with a simple script. How to install Ansible in Oracle Linux version 8. Today we're going to talk about the easier way to install and maintain Ansible inside Oracle Linux 8 using the EPEL repository. ## How to install Ansible in Oracle Linux 8 - use Extra Packages for Enterprise Linux (EPEL) additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), CentOS and Scientific Linux (SL), Oracle Linux (OL) Today we're talking about how to install Ansible in AlmaLinux 8. The easier way to install and maintain Ansible inside AlmaLinux version 8 is using the Extra Packages for Enterprise Linux (EPEL) additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), Alma Linux, Rocky Linux and Scientific Linux (SL), Oracle Linux (OL). ## Links - Oracle Linux 8 ## Playbook Install latest Ansible release in Oracle Linux 8. ### code - Install-Ansible-OracleLinux8.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Oracle Linux using the EPEL repository. --- ## How to install Ansible in Oracle Linux 9 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-oracle-linux-9-ansible-install Description: Learn how to easily install and maintain Ansible on Oracle Linux 9 using the ansible-core package from the AppStream repository with this. ## How to install Ansible in OracleLinux version 9. Today we’re going to talk about the easier way to install and maintain Ansible inside OracleLinux 9 using the appstream system repository. ## How to install Ansible in OracleLinux 9 - `ansible-core` included in AppStream repository - `ansible` package not available Today we’re talking about How to install Ansible in OracleLinux 9. The easier way to install and maintain up-to-date Ansible inside OracleLinux version 9 is using the `ansible-core` package included in the AppStream distribution repository. Please notice that the package `ansible` isn’t available anymore. It’s not necessary to use the additional EPEL package repository. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - OracleLinux website ## Playbook Let’s jump into a quick live Playbook of how to install the latest version of Ansible in OracleLinux. I’m going to install the `ansible-core` package in an OracleLinux 9 using the AppStream distribution repository. ### code - Install-Ansible-OracleLinux9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Oracle Linux using the AppStream repository. --- ## How to Install Ansible in RHEL 8 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-rhel-8-ansible-install Description: How to install the latest and a specific version of Ansible in Red Hat Enterprise version 8 using Ansible Engine software collection. How to install Ansible in Red Hat Enterprise Linux version 8. Today we’re going to talk about the easier way to install and maintain Ansible inside RHEL 8 with the distribution tools. ## How to install Ansible in RHEL 8 Today we’re talking about How to install Ansible in RHEL 8. The easier way to install and maintain Ansible inside Red Hat Enterprise Linux version 8 with the distribution tools. The repository that contains Ansible is called the Ansible Engine software collection. The main advantage of using software collection is that you don’t require any external repository such as EPEL for this content. Software Collections are fully supported by Red Hat and included in your subscription plan. ## Demo Are you ready to make your hands dirty? Let’s jump in a quick live Playbook of how to install the latest and a specific version of Ansible in RHEL8. RedHat Enterprise Linux (RHEL) 8 supports `ansible-core` via the - AppStream repository since RHEL 8.6 - Extra Packages for Enterprise Linux (EPEL) repository ### code [code example] ### Execution [code example] ### Verification After the successful installation you could verify in the command line: [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest and a specific version of Ansible in RHEL8. --- ## How to Install Ansible in RHEL 9 — Step by Step URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-redhat-enterprise-linux-9 Description: How to install Ansible Core (ansible-core) in RedHat Enterprise Linux 9 included in the RHEL 9 AppStream repository. Tested, copy-paste examples included. ## How to install Ansible in Red Hat Enterprise Linux version 9? Today we're going to talk about the easier way to install and maintain Ansible inside RHEL 9 with the distribution tools. ## How to install Ansible in RHEL 9 - The Ansible Core package `ansible-core` included in the RHEL 9 AppStream repository Today we're talking about How to install Ansible in RHEL 9. The good news is that the Ansible Core package (ansible-core) is included out-of-the-box in the RHEL 9 AppStream repository. No more additional repository (Ansible Engine or EPEL) like previous versions for basic automation. However, for additional support for the underlying platform and Core-maintained modules is required the Ansible Automation Platform subscription. See also: Ansible terminology - ansible vs ansible-core packages. ## Link - Scope of support for the Ansible Core package included in the RHEL 9 AppStream - Using Ansible in RHEL 9 ## Playbook Install latest Ansible-Core in RHEL 9. ### code - Install-Ansible-RHEL9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible Core in RHEL9. --- ## How to Install Ansible in RHEL 9 Beta URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-redhat-enterprise-linux-9-beta Description: How to install Ansible Core (ansible-core) in RedHat Enterprise Linux 9 Beta included in the RHEL 9 AppStream repository. ## How to install Ansible in Red Hat Enterprise Linux version 9 Beta? Today we're going to talk about the easier way to install and maintain Ansible inside RHEL 9 with the distribution tools. ## How to install Ansible in RHEL 9 Beta - The Ansible Core package (ansible-core) included in the RHEL 9 AppStream repository Today we're talking about How to install Ansible in RHEL 9 Beta. The good news is that the Ansible Core package (ansible-core) is included out-of-the-box in the RHEL 9 AppStream repository. No more additional repository (Ansible Engine or EPEL) like previous versions for basic automation. However, for additional support for the underlying platform and Core-maintained modules is required the Ansible Automation Platform subscription. ## Link - Scope of support for the Ansible Core package included in the RHEL 9 AppStream - Using Ansible in RHEL 9 ## Playbook Install latest Ansible-Core in RHEL 9. ### code - Install-Ansible-RHEL9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible Core in RHEL9. --- ## How to Install Ansible in RHEL 9.1 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-redhat-enterprise-linux-9-1 Description: How to install Ansible Core (ansible-core) in RedHat Enterprise Linux 9.1 included in the RHEL 9.1 AppStream repository. ## How to install Ansible in Red Hat Enterprise Linux version 9.1? Today we're going to talk about the easier way to install and maintain up-to-date Ansible inside RHEL 9.1 with the distribution tools. ## How to install Ansible in RHEL 9.1 - The Ansible Core package `ansible-core` included in the RHEL 9.1 AppStream repository Today we're talking about How to install Ansible in RHEL 9.1. The good news is that the Ansible Core package (ansible-core) is included out-of-the-box in the RHEL 9.1 AppStream repository. No more additional repository (Ansible Engine or EPEL) like previous versions for basic automation. However, for additional support for the underlying platform and Core-maintained modules is required the Ansible Automation Platform subscription. See also: Ansible terminology - ansible vs ansible-core packages. ## Link - Scope of support for the Ansible Core package included in the RHEL 9.1 AppStream - Using Ansible in RHEL 9.1 ## Playbook Install latest Ansible-Core in RHEL 9.1. ### code - Install-Ansible-RHEL9.1.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible Core in RHEL9.1. --- ## How to Install Ansible in RHEL 9.2 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-redhat-enterprise-linux-9-2 Description: How to install Ansible Core (ansible-core) in RedHat Enterprise Linux 9.2 included in the RHEL 9.2 AppStream repository. ## How to install Ansible in Red Hat Enterprise Linux version 9.2? Today we're going to talk about the easier way to install and maintain up-to-date Ansible inside RHEL 9.2 with the distribution tools. ## How to install Ansible in RHEL 9.2 - The Ansible Core package `ansible-core` included in the RHEL 9.2 AppStream repository Today we're talking about How to install Ansible in RHEL 9.2. The good news is that the Ansible Core package (ansible-core) is included out-of-the-box in the RHEL 9.2 AppStream repository. No more additional repository (Ansible Engine or EPEL) like previous versions for basic automation. However, for additional support for the underlying platform and Core-maintained modules is required the Ansible Automation Platform subscription. See also: Ansible terminology - ansible vs ansible-core packages. ## Link - Scope of support for the Ansible Core package included in the RHEL 9.2 AppStream - Using Ansible in RHEL 9.2 ## Playbook Install latest Ansible-Core in RHEL 9.2. ### code - Install-Ansible-RHEL9.2.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] ## Conclusion Now you know how to install the latest version of Ansible Core in RHEL9.2. --- ## How to Install Ansible in RHEL 9.3 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-redhat-enterprise-linux-9-3 Description: A concise guide on installing and maintaining Ansible in RHEL 9.3 using the distribution tools without additional repositories. ## How to install Ansible in Red Hat Enterprise Linux version 9.3? Today we're going to talk about the easier way to install and maintain up-to-date Ansible inside RHEL 9.3 with the distribution tools. ## How to install Ansible in RHEL 9.3 - The Ansible Core package `ansible-core` included in the RHEL 9.3 AppStream repository Today we're talking about How to install Ansible in RHEL 9.3. The good news is that the Ansible Core package (ansible-core) is included out-of-the-box in the RHEL 9.3 AppStream repository. No more additional repository (Ansible Engine or EPEL) like previous versions for basic automation. However, for additional support for the underlying platform and Core-maintained modules is required the Ansible Automation Platform subscription. See also: Ansible terminology - ansible vs ansible-core packages. ## Link - Scope of support for the Ansible Core package included in the RHEL 9.3 AppStream - Using Ansible in RHEL 9.3 ## Playbook Install latest Ansible-Core in RHEL 9.3. ### code - Install-Ansible-RHEL9.3.sh [code example] ### execution [code example] ### Before execution [code example] ### After execution [code example] ## Conclusion Now you know how to install the latest version of Ansible Core in RHEL9.3. --- ## How to install Ansible in Rocky Linux 8 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-rocky-linux-8 Description: How to install and maintain up-to-date Ansible inside Rocky Linux 8 using the EPEL repository. With tested, real-world examples. How to install Ansible in Rocky Linux version 8. Today we're going to talk about the easier way to install and maintain Ansible inside Rocky Linux 8 using the EPEL repository. ## How to install Ansible in Rocky Linux 8 - use Extra Packages for Enterprise Linux (EPEL) additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), Rocky Linux and Scientific Linux (SL), Oracle Linux (OL) Today we're talking about How to install Ansible in Rocky Linux 8. The easier way to install and maintain Ansible inside Rocky Linux version 8 is using the Extra Packages for Enterprise Linux (EPEL) additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), Rocky Linux and Scientific Linux (SL), Oracle Linux (OL). ## Playbook Let's jump in a quick live Playbook of how to install the latest version of Ansible in Rocky Linux. ### code - Install-Ansible-RockyLinux8.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Rocky Linux using the EPEL repository. --- ## How to install Ansible in SUSE Linux Enterprise Server (SLES) 15 SP3 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-suse-linux-enterprise-server-sles-15-sp3 Description: How to install and maintain up-to-date Ansible inside SUSE Linux Enterprise Server (SLES) 15 SP3 using the SUSE Package Hub repository. How to install Ansible in SUSE Linux Enterprise SLES Server 15 SP3? Today we're going to talk about the easier way to install and maintain Ansible inside SUSE Linux Enterprise (aka SLES) Server 15 SP3 using the Package Hub repository. ## How to install Ansible in SLES 15 SP3 - use SUSE Package Hub repository Today we're talking about How to install Ansible in SUSE Linux Enterprise 15 SP 3. The easier way to install and maintain Ansible inside SUSE Linux Enterprise version 15 SP 3 is using the SUSE Package Hub repository maintained by the SUSE community. ## Links - SUSE Package Hub - Community Packages for SUSE Linux Enterprise Server / Desktop - How to register SLES using the SUSEConnect command line tool - Adding SUSE Package Hub repositories to SUSE Linux Enterprise Server ## Playbook Install the latest version of ansible in SUSE Linux Enterprise Server 15 SP3. ### code - Install-Ansible-SLES-15-SP3.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in SUSE Linux Enterprise Server 15 SP3 using the Package Hub repository. --- ## How to install Ansible in Ubuntu 21.10 — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-21-10-ansible-install Description: How to install Ansible in Ubuntu 21.10 Impish Indri using the universe and PPA repositories. Tested, copy-paste examples included. How to install Ansible in the latest Ubuntu 21.10. Today we're going to talk about the easier way to install and maintain Ansible inside Ubuntu 21.10 with the distribution tools. ## How to install Ansible in Ubuntu 21.10 - universe - PPA Today we're talking about How to install Ansible in Ubuntu 21.10? We're going to see the easy way to install and maintain Ansible inside Ubuntu with the distribution tools. We are going to see how to install Ansible in two different ways. The first method to install Ansible is using the universe repository, the default that you get after installation. The main advantage of using the universe repository is that you don't require any external repository. And the second method to install Ansible is using the PPA repository. Please bear in mind that adding an additional repository has a different quality assurance of software. ## Playbook Install Ansible in Ubuntu 21.10 with universe and PPA ### universe code [code example] ### universe execution [code example] ### PPA code - install-Ansible-PPA.sh [code example] ### PPA execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install ansible using universe and PPA repositories in Ubuntu 21.10. --- ## How to install Ansible in Ubuntu 22.04 LTS Jammy Jellyfish — Ansible Install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-22-04-ansible-install Description: How to install ansible using the universe repository in Ubuntu 22.04 LTS Jammy Jellyfish. Tested on real machines with clear, copy-paste examples. ## How to install Ansible in the latest Ubuntu 22.04. Today we're going to talk about the easier way to install and maintain Ansible inside Ubuntu 22.04 with the distribution tools. ## How to install Ansible in Ubuntu 22.04 - universe - PPA Today we're talking about how to install Ansible in Ubuntu 22.04 LTS Jammy Jellyfish. We're going to see the easy way to install and maintain Ansible inside Ubuntu with the distribution tools. We are going to see how to install Ansible in two different ways. The first method to install Ansible is using the universe repository, the default that you get after installation. The main advantage of using the universe repository is that you don't require any external repository. And the second method to install Ansible is using the PPA repository. Please bear in mind that adding an additional repository has a different quality assurance of software. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - ansible packages for Ubuntu - ansible PPA for Ubuntu ## Playbook How to install Ansible in Ubuntu 22.04 LTS Jammy Jellyfish with universe and PPA repositories. ### universe - code [code example] - execution [code example] ### PPA - code [code example] - execution [code example] ## Conclusion Now you know how to install ansible using universe and PPA repositories in Ubuntu 22.04 LTS Jammy Jellyfish. --- ## How to install Ansible in Ubuntu 22.10 Kinetic Kudu — Ansible Install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-22-10-ansible-install Description: Learn how to install Ansible on Ubuntu 22.10 Kinetic Kudu using the universe repository with a simple and straightforward method. ## How to install Ansible in the latest Ubuntu 22.10. Today we're going to talk about the easier way to install and maintain Ansible inside Ubuntu 22.10 with the distribution tools. ## How to install Ansible in Ubuntu 22.10 - universe - PPA Today we're talking about how to install Ansible in Ubuntu 22.10 Kinetic Kudu. We're going to see the easy way to install and maintain Ansible inside Ubuntu with the distribution tools. We are going to see how to install Ansible using the **universe** repository, the default that you get after installation. The main advantage of using the universe repository is that you don’t require any external repository. At the moment the installation of Ansible using the PPA repository is not available. Please bear in mind that adding an additional repository has a different quality assurance of software. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - ansible packages for Ubuntu - ansible PPA for Ubuntu ## Playbook How to install Ansible in Ubuntu 22.10 Kinetic Kudu with universe repository. ### universe - code [code example] - execution [code example] ### PPA - code [code example] - execution Not available at the moment (30th November 2022) ## Conclusion Now you know how to install ansible using universe repository in Ubuntu 22.10 Kinetic Kudu. --- ## How to install Ansible in Ubuntu 23.04 Lunar Lobster — Ansible Install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-23-04-ansible-install Description: Learn the easiest ways to install and maintain Ansible on Ubuntu 23.04 Lunar Lobster using the universe and PPA repositories for efficient automation. ## How to install Ansible in the latest Ubuntu 23.04. Today we're going to talk about the easier way to install and maintain Ansible inside Ubuntu 23.04 with the distribution tools. ## How to install Ansible in Ubuntu 23.04 - universe - PPA Today we're talking about how to install Ansible in Ubuntu 23.04 Lunar Lobster. We're going to see the easy way to install and maintain Ansible inside Ubuntu with the distribution tools. We are going to see how to install Ansible in two different ways. The first method to install Ansible is using the universe repository, the default that you get after installation. The main advantage of using the universe repository is that you don't require any external repository. And the second method to install Ansible is using the PPA repository. Please bear in mind that adding an additional repository has a different quality assurance of software. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - ansible packages for Ubuntu - ansible PPA for Ubuntu ## Playbook How to install Ansible in Ubuntu 23.04 Lunar Lobster with universe and PPA repositories. ### universe - code [code example] - execution [code example] ### PPA - code [code example] - execution [code example] ## Conclusion Now you know how to install ansible using universe and PPA repositories in Ubuntu 23.04 Lunar Lobster. --- ## How to Install Ansible on Ubuntu 20.04, 22.04, and 24.04 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-20-04-ansible-install Description: Step-by-step guide to installing Ansible on Ubuntu using apt, PPA, and pip. Covers Ubuntu 20.04, 22.04, and 24.04 with version comparison. This guide covers three methods to install Ansible on Ubuntu — the system package manager (`apt`), the Ansible PPA for newer versions, and `pip` for the latest release. Each method has trade-offs between simplicity, version freshness, and control. ## Which Installation Method Should You Use? | Method | Best For | Ansible Version | Updates | |--------|----------|----------------|---------| | **apt (Universe)** | Quick setup, no external repos | Older (distro version) | With system updates | | **PPA** | Newer version via apt | Recent stable | PPA updates | | **pip** | Latest version, virtual envs | Latest | `pip install --upgrade` | **Recommendation:** Use `pip` in a virtual environment for production control nodes. Use `apt` or PPA for quick testing. ## Method 1: Install via apt (Universe Repository) The simplest method — uses Ubuntu's built-in universe repository: [code example] ### Verify Installation [code example] ### Version by Ubuntu Release | Ubuntu Version | Ansible Package Version | |---------------|------------------------| | 20.04 LTS | 2.9.x | | 22.04 LTS | 2.10.x | | 24.04 LTS | 2.16.x | **Note:** Ubuntu 20.04 ships Ansible 2.9, which is significantly outdated and missing many modern features (collections, FQCN support). Consider PPA or pip for 20.04. ## Method 2: Install via Ansible PPA The official Ansible PPA provides newer versions: [code example] ### Verify [code example] ### Why Use the PPA? - Gets Ansible updates faster than Ubuntu's relea... --- ## How to Install Ansible on Ubuntu 23.10 Mantic Minotaur URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-23-10-ansible-install Description: Learn how to install Ansible on Ubuntu 23.10 through a remote SSH session with easy-to-follow steps and commands for seamless automation setup. ## Introduction Ansible is a powerful tool for automating IT tasks, and installing it on Ubuntu 23.10 is a straightforward process. This article will guide you through the steps to install Ansible on a Ubuntu system, based on a real-world example from a remote SSH session. ## Prerequisites Before you begin, ensure that you have: - Access to a terminal. - Sudo privileges on your Ubuntu system. In this guide, we'll connect remotely to an Ubuntu server using SSH. The Ubuntu version we are working with is Ubuntu 23.10. ## Step 1: Connecting to the Ubuntu Server First, establish an SSH connection to your Ubuntu server: [code example] Once connected, you'll be greeted with the Ubuntu welcome message, confirming that you are running Ubuntu 23.10. [code example] ## Step 2: Checking for Ansible Before installing Ansible, it's a good practice to check if it's already installed: [code example] If Ansible is not installed, Ubuntu's package manager will suggest installing it through `apt install ansible-core`. [code example] ## Step 3: Installing Ansible Now, proceed with the installation: 1. Update the package list to ensure you get the latest version available: [code example] 2. Install Ansible using apt: [code example] During the installation, you'll see a list of additional packages that will be installed along with Ansible. These dependencies are necessary for Ansible's optimal performance. 3. Confirm the installation by pressing Y when prompted. The installation... --- ## How to Install Ansible on Ubuntu, RHEL, macOS, and Windows URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-on-ubuntu-rhel-macos-and-windows Description: Step-by-step guide to install Ansible on Ubuntu 24.04, RHEL 9, CentOS, Fedora, macOS, and Windows WSL. Covers pip, apt, dnf, and brew installation methods. ## How to Install Ansible **The fastest way to install Ansible** is with pip: `pip install ansible`. Ansible requires Python 3.10+ and runs on Linux, macOS, and Windows (via WSL). It connects to remote hosts via SSH — no agent is needed on target machines. ## Quick Install (pip — All Platforms) The fastest way to install Ansible on any system: [code example] ## Ubuntu / Debian ### Method 1: apt (System Package) [code example] ### Method 2: PPA (Latest Version) [code example] ### Method 3: pip (Recommended) [code example] ### Ubuntu 24.04 Specific [code example] ## RHEL / CentOS / Fedora ### RHEL 9 / CentOS Stream 9 [code example] For the full Ansible package with community collections: [code example] ### Fedora [code example] ## macOS ### Homebrew [code example] ### pip [code example] ## Windows (via WSL) Ansible doesn't run natively on Windows. Use Windows Subsystem for Linux: [code example] ## Verify Installation [code example] ## First Steps After Installation ### Create an Inventory File [code example] ### Run Your First Ad-Hoc Command [code example] ### Run Your First Playbook [code example] [code example] ## Upgrade Ansible [code example] ## Common Installation Issues ### "externally-managed-environment" Error (Ubuntu 24.04+) [code example] ### Python Version Too Old Ansible requires Python 3.10+. Check your version: [code example] ### pip Not Found [code example] ## Try Ansible Without Installing Use our free Ansible Pl... --- ## How to Install Ansible on Windows URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-on-windows Description: Install Ansible on Windows using WSL2, Cygwin, or Docker containers. Hands-on, tested examples and best practices for How to Install Ansible on Windows. # How to Install Ansible on Windows ## Introduction Install Ansible on Windows using WSL2, Cygwin, or Docker containers. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Install Ansible on Windows using WSL2, Cygwin, or Docker containers. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to install Ansible with PIP — Ansible install URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-with-pip-ansible-install Description: How to install Ansible with PIP - the Python package manager. Step-by-step Ansible tutorial with practical examples and best practices. ## How to install Ansible with PIP, the Python package manager? Today we're going to talk about how to use the up-to-date version of Ansible in Linux and macOS using PIP. ## How to install Ansible with PIP Today we're talking about How to install Ansible with PIP. PIP is the Python package manager and is going to take care of all the processes and manage the necessary dependency. It takes care of the download and installs process of packages directly from PyPI. PIP is designed to be OS-independent. It could be a solution for developers that always want the latest up-to-date release. The alternative approach is to use the Operating System specific Package Manager. For example for Linux yum, DNF, and apt and for macOS Homebrew. This second approach put more emphasis on stability so the latest release could be not available. So if you really need the latest release of Ansible I'd suggest you use PIP. ## Demo install Ansible with PIP Demo time! Let me Playbooknstrate to you how to install the latest of Ansible with PIP, the Python package manager. ### code PIP user - install-pip-user.sh [code example] ### code PIP global - install-pip-global.sh [code example] - Execution [code example] - Verification After the successful installation you could verify in the command line: [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install Ansible with PIP, the Python package manager. --- ## How to install ansible-lint in macOS URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-lint-in-macos Description: How to install the ansible-lint command line utility and use it to improve our Ansible Playbooks in macOS Intel and Silicon. ## What is the ansible-lint tool? > ansible-lint checks playbooks for practices and behavior that could potentially be improved. Ansible-Lint is a command-line tool for linting playbooks, roles, and collections aimed toward any Ansible users. Its main goal is to promote proven practices, patterns, and behaviors while avoiding common pitfalls that can easily lead to bugs or make code harder to maintain. ## Links - ansible-lint https://ansible-lint.readthedocs.io/ - Homebrew https://brew.sh/ ## Installation in macOS Let's install the `ansible-lint` tool in macOS using the Homebrew package manager. I suppose the Homebrew is already installed using the Homebrew https://brew.sh/ website. The brew tool works on macOS Intel and Silicon (M1, M2, M1Pro, M2Pro, M1Max, M2Max, M1Ultra, M2Ultra). ### before [code example] ### installation command The installation command downloads the required files and dependencies (sqlite, ansible, black, pygments and yamllint) and install them in our system. [code example] ### execution [code example] ### verification [code example] ## Conclusion Now you know how to install the `ansible-lint` command line utility in macOS. --- ## How to Loop Over a Dictionary in Ansible URL: https://www.ansiblebyexample.com/articles/how-to-loop-over-a-dictionary-in-ansible Description: Iterate over dictionaries using dict2items, with_dict, and loop filters in Ansible. Tested on real machines with clear, copy-paste examples. # How to Loop Over a Dictionary in Ansible ## Introduction Iterate over dictionaries using dict2items, with_dict, and loop filters in Ansible. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Iterate over dictionaries using dict2items, with_dict, and loop filters in Ansible. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Manage Ansible in a Team URL: https://www.ansiblebyexample.com/articles/how-to-manage-ansible-in-a-team Description: Best practices for team collaboration with shared repos, roles, and workflows. Tested on real machines with clear, copy-paste examples. # How to Manage Ansible in a Team ## Introduction Best practices for team collaboration with shared repos, roles, and workflows. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Best practices for team collaboration with shared repos, roles, and workflows. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Manage Multiple Servers with Ansible URL: https://www.ansiblebyexample.com/articles/how-to-manage-multiple-servers-with-ansible Description: Scale Ansible to hundreds of servers with inventory groups and dynamic inventories. Tested on real machines with clear, copy-paste examples. # How to Manage Multiple Servers with Ansible ## Introduction Scale Ansible to hundreds of servers with inventory groups and dynamic inventories. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Scale Ansible to hundreds of servers with inventory groups and dynamic inventories. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Pass Variables to Ansible Playbook via Command Line? URL: https://www.ansiblebyexample.com/articles/pass-variables-to-ansible-playbook-in-command-line-ansible-extra-variables Description: How to pass or override an Ansible Playbook variable from the command line in plaintext, JSON, or YAML. It is very useful to combine some script. ## Passing Variables to Ansible Playbook: A Quick Guide In today's episode of Ansible Pilot, we'll delve into the practical aspect of passing variables to Ansible Playbooks via the command line. This can be a powerful and flexible way to customize your playbook execution based on dynamic inputs. I'm Luca Berton, and let's jump right into the world of Ansible extra variables. ## Understanding Ansible Extra Variables Ansible extra variables provide a means to pass values to your playbook from the command line. This flexibility is particularly valuable when you need to integrate Ansible into existing automation scripts or workflows. Extra variables can be specified in various formats, and today, we'll explore a few options. ### Command Line Syntax The command line parameter for passing extra variables is `--extra-vars`, followed by the variable-value pair. Here are some examples: - `--extra-vars "fruit=apple"` - `--extra-vars '{"fruit":"apple"}'` - `--extra-vars "@file.json"` - `--extra-vars "@file.yml"` ### Real-Life Example Let's illustrate this concept with a real-life example. Consider the following Ansible Playbook: - example.yml [code example] In this playbook, we have a variable named `fruit` with a default value of "banana." The playbook then prints a message using the value of this variable. ### Executing Without Extra Variables If we run the playbook without any extra variables, it uses the default value: [code example] ### Executing With a Plain Extra V... --- ## How to Run Ansible as Non-Root User URL: https://www.ansiblebyexample.com/articles/how-to-run-ansible-as-non-root-user Description: Execute Ansible without root access using become, sudo, and privilege escalation. With clear, copy-paste, step-by-step examples. # How to Run Ansible as Non-Root User ## Introduction Execute Ansible without root access using become, sudo, and privilege escalation. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Execute Ansible without root access using become, sudo, and privilege escalation. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Run Ansible Behind a Proxy URL: https://www.ansiblebyexample.com/articles/how-to-run-ansible-behind-a-proxy Description: Configure Ansible to work through HTTP and SOCKS proxies for restricted networks. With clear, copy-paste, step-by-step examples. # How to Run Ansible Behind a Proxy ## Introduction Configure Ansible to work through HTTP and SOCKS proxies for restricted networks. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Configure Ansible to work through HTTP and SOCKS proxies for restricted networks. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Run Ansible Playbook Against Single Host URL: https://www.ansiblebyexample.com/articles/how-to-run-ansible-playbook-against-single-host Description: Run an Ansible playbook on one specific host using --limit flag, patterns, and inventory targeting. Tested on real machines with clear, copy-paste examples. # How to Run Ansible Playbook Against Single Host ## Introduction Run an Ansible playbook on one specific host using --limit flag, patterns, and inventory targeting. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Run an Ansible playbook on one specific host using --limit flag, patterns, and inventory targeting. Follow the step-by-step guide above, test in check mode, and implement error handling for production... --- ## How to Run Ansible Playbook in Background URL: https://www.ansiblebyexample.com/articles/how-to-run-ansible-playbook-in-background Description: Execute long-running tasks asynchronously with async and poll in Ansible. Tested on real machines with clear, copy-paste examples. # How to Run Ansible Playbook in Background ## Introduction Execute long-running tasks asynchronously with async and poll in Ansible. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Execute long-running tasks asynchronously with async and poll in Ansible. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Run Linux Fedora Workstation 39 on an Apple Mac URL: https://www.ansiblebyexample.com/articles/how-to-run-linux-fedora-workstation-39-on-an-apple-mac Description: Twenty Years of Fedora: Celebrating Innovation in Open Source Step-by-step Ansible tutorial with practical examples and best practices. ## Introduction On November 6, 2003, the Fedora Project released Fedora Core 1, marking the inception of a community-driven journey into the world of open-source operating systems. Fast forward twenty years, and Fedora Linux 39 is here, a testament to two decades of innovation, collaboration, and unwavering dedication. ## Desktop Delights Fedora Workstation, the desktop variant of Fedora, now boasts GNOME 45. This update brings not only better performance but also a slew of usability enhancements. Users will find a new workspace switcher and a significantly improved image viewer, enhancing the overall desktop experience. But that’s not all; Fedora offers a diverse array of desktop flavors, including Fedora Onyx, a Budgie-based “Atomic” desktop for those seeking something different. ## In the Cloud For cloud enthusiasts, Fedora Cloud images are now officially available on Microsoft Azure, expanding its presence to complement Google Cloud and AWS. What’s more, cloud images are configured to allow cloud-init to install updates and reboot upon provisioning, ensuring you start with the latest security updates. ## Under the Hood As always, Fedora Linux 39 incorporates numerous updates to keep the open-source software world at your fingertips. Expect to find key software updates, including GCC 13.2, Binutils 2.40, Glibc 2.38, GDB 13.2, and RPM 4.19. The release also includes updates to popular programming languages, such as Python 3.12 and Rust 1.73. Inkscape, the celebrated vect... --- ## How to Run Only One Task in Ansible Playbook? — Ansible tags statement URL: https://www.ansiblebyexample.com/articles/how-to-run-only-one-task-in-ansible-playbook-ansible-tags-statement Description: How to select single or multiple tasks, include, import, play, block, and role in an Ansible Playbook using tags parameter of ansible-playbook command. ## How to run only one task in an Ansible Playbook? ## How use tags statement in Ansible Playbook? - `--tags all` - `--tags tag1` - `--tags [tag1, tag2]` - `--skip-tags [tag3, tag4]` - `--tags tagged` - `--tags untagged` Today we're talking about Ansible tags statement. When your Ansible Playbook starts to grow up it's useful to define tags to allow a more granular execution. You could define one or multiple tags at the individual task, include, import, play, block, role level. Tags also could have tag inheritance properties. The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the "ansible-playbook" command. The default behavior is to execute all the tags in your Playbook with `--tags all`. You could specify to execute a single tag with `--tags tag1` or a list of tags `--tags [tag1, tag2]` You could specify also and use the negate logic to exclude some tags`--skip-tags [tag3, tag4]`. Another convenient way is to execute only the code with tag `--tags tagged` or without `--tags untagged`. ## Links - Tags ## Playbook How to run only one task in Ansible Playbook? I'm going to show you one simple Ansible Playbook with two tasks and two tags and how to select one or another via the command line. ### code [code example] ### execution default [code example] ### execution tags tag1 [code example] ### execution tags tag2 [code example] ### execution tags tagged [code example] code with ❤️ in GitHub ## Conclusion Now you k... --- ## How to Skip a Task in Ansible URL: https://www.ansiblebyexample.com/articles/how-to-skip-a-task-in-ansible Description: Skip tasks conditionally with when clause, tags, and skip_tags in Ansible playbooks. With clear, copy-paste, step-by-step examples. # How to Skip a Task in Ansible ## Introduction Skip tasks conditionally with when clause, tags, and skip_tags in Ansible playbooks. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Skip tasks conditionally with when clause, tags, and skip_tags in Ansible playbooks. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Speed Up Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/how-to-speed-up-ansible-playbooks Description: Optimize Ansible performance with pipelining, mitogen, caching, and parallelism. With clear, copy-paste, step-by-step examples. # How to Speed Up Ansible Playbooks ## Introduction Optimize Ansible performance with pipelining, mitogen, caching, and parallelism. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Optimize Ansible performance with pipelining, mitogen, caching, and parallelism. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Test Ansible Playbooks with Molecule URL: https://www.ansiblebyexample.com/articles/how-to-test-ansible-playbooks-with-molecule Description: Test roles and playbooks with Molecule using Docker and Vagrant providers. With clear, copy-paste, step-by-step examples. # How to Test Ansible Playbooks with Molecule ## Introduction Test roles and playbooks with Molecule using Docker and Vagrant providers. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Test roles and playbooks with Molecule using Docker and Vagrant providers. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Upgrade Ansible Version URL: https://www.ansiblebyexample.com/articles/how-to-upgrade-ansible-version Description: Upgrade Ansible safely across major versions with compatibility checks. Tested on real machines with clear, copy-paste examples. # How to Upgrade Ansible Version ## Introduction Upgrade Ansible safely across major versions with compatibility checks. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Upgrade Ansible safely across major versions with compatibility checks. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Upgrade Kubelet in Kubernetes: A Complete Guide URL: https://www.ansiblebyexample.com/articles/keeping-kubernetes-clusters-up-to-date Description: Upgrade Kubelet in Kubernetes clusters safely. Step-by-step guide covering version skew policy, drain/uncordon workflow, kubeadm upgrades, and automation. ## Introduction The Kubelet is the primary node agent in Kubernetes — it runs on every node and ensures containers match their PodSpecs. Keeping Kubelet up-to-date is critical for security patches, bug fixes, and compatibility with the control plane. This guide covers the complete upgrade workflow. ## Prerequisites | Requirement | Notes | |-------------|-------| | kubectl access | Cluster admin permissions | | kubeadm | For managed upgrades | | SSH access to nodes | For manual kubelet restart | | Maintenance window | Pods will be evicted during drain | ## Version Skew Policy Kubernetes enforces strict version compatibility: | Component | Allowed Skew from API Server | |-----------|------| | kubelet | Up to **2 minor versions** behind | | kube-proxy | Same minor version as kubelet | | kubectl | ±1 minor version | | kubeadm | Same minor version as target | Example: If API server is v1.29, kubelet can be v1.27, v1.28, or v1.29. [code example] ## Upgrade Workflow ### Step 1: Upgrade kubeadm [code example] ### Step 2: Drain the Node [code example] ### Step 3: Upgrade Kubelet Configuration [code example] For control plane nodes (first one): [code example] ### Step 4: Upgrade Kubelet and kubectl [code example] ### Step 5: Restart Kubelet [code example] ### Step 6: Uncordon the Node [code example] ## Upgrade All Nodes (Rolling) [code example] ## Automate with Ansible [code example] ## Troubleshooting ### Kubelet Won't Start After Upgrade [code example] ... --- ## How to Use Ansible Callbacks for Logging URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-callbacks-for-logging Description: Configure callback plugins for custom output, logging, and notifications. Tested on real machines with clear, copy-paste examples. # How to Use Ansible Callbacks for Logging ## Introduction Configure callback plugins for custom output, logging, and notifications. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Configure callback plugins for custom output, logging, and notifications. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible Collections URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-collections Description: Install, create, and manage Ansible Collections for modular automation. Tested on real machines with clear, copy-paste examples. # How to Use Ansible Collections ## Introduction Install, create, and manage Ansible Collections for modular automation. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Install, create, and manage Ansible Collections for modular automation. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible Galaxy Roles URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-galaxy-roles Description: Find, install, and use community roles from Ansible Galaxy in your playbooks. Hands-on, tested examples and best practices for How to Use Ansible Galaxy Roles. # How to Use Ansible Galaxy Roles ## Introduction Find, install, and use community roles from Ansible Galaxy in your playbooks. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Find, install, and use community roles from Ansible Galaxy in your playbooks. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible Tags Effectively URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-tags-effectively Description: Organize playbooks with tags for selective execution and faster iteration. With clear, copy-paste, step-by-step examples. # How to Use Ansible Tags Effectively ## Introduction Organize playbooks with tags for selective execution and faster iteration. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Organize playbooks with tags for selective execution and faster iteration. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible Vault for Secrets URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-vault-for-secrets Description: Encrypt and decrypt sensitive data with Ansible Vault in production workflows. Tested on real machines with clear, copy-paste examples. # How to Use Ansible Vault for Secrets ## Introduction Encrypt and decrypt sensitive data with Ansible Vault in production workflows. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Encrypt and decrypt sensitive data with Ansible Vault in production workflows. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible with AWS URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-with-aws Description: Automate AWS infrastructure with Ansible using amazon.aws collection modules. Hands-on, tested examples and best practices for How to Use Ansible with AWS. # How to Use Ansible with AWS ## Introduction Automate AWS infrastructure with Ansible using amazon.aws collection modules. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Automate AWS infrastructure with Ansible using amazon.aws collection modules. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible with Docker URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-with-docker Description: Build images, run containers, and manage Docker infrastructure with Ansible. With clear, copy-paste, step-by-step examples. # How to Use Ansible with Docker ## Introduction Build images, run containers, and manage Docker infrastructure with Ansible. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Build images, run containers, and manage Docker infrastructure with Ansible. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible with Git URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-with-git Description: Automate git operations including clone, pull, checkout, and deploy from repos. Hands-on, tested examples and best practices for How to Use Ansible with Git. # How to Use Ansible with Git ## Introduction Automate git operations including clone, pull, checkout, and deploy from repos. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Automate git operations including clone, pull, checkout, and deploy from repos. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Ansible with Terraform URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-with-terraform Description: Combine Terraform for provisioning and Ansible for configuration management. Tested on real machines with clear, copy-paste examples. # How to Use Ansible with Terraform ## Introduction Combine Terraform for provisioning and Ansible for configuration management. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Combine Terraform for provisioning and Ansible for configuration management. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. ## Related guide Related reading: Terraform ... --- ## How to Use Ansible with VMware vSphere URL: https://www.ansiblebyexample.com/articles/how-to-use-ansible-with-vmware-vsphere Description: Automate VMware virtual machines, networks, and storage with Ansible. Tested on real machines with clear, copy-paste examples. # How to Use Ansible with VMware vSphere ## Introduction Automate VMware virtual machines, networks, and storage with Ansible. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Automate VMware virtual machines, networks, and storage with Ansible. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Jinja2 Filters in Ansible URL: https://www.ansiblebyexample.com/articles/how-to-use-jinja2-filters-in-ansible Description: Transform data with Jinja2 filters for string manipulation, math, and formatting. Tested on real machines with clear, copy-paste examples. # How to Use Jinja2 Filters in Ansible ## Introduction Transform data with Jinja2 filters for string manipulation, math, and formatting. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Transform data with Jinja2 filters for string manipulation, math, and formatting. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## How to Use Variables in Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/how-to-use-variables-in-ansible-playbooks Description: Define and use variables from inventories, vars files, facts, and command line. Tested on real machines with clear, copy-paste examples. # How to Use Variables in Ansible Playbooks ## Introduction Define and use variables from inventories, vars files, facts, and command line. This comprehensive guide walks you through every method with practical examples. ## Quick Answer [code example] ## Step-by-Step Guide ### Step 1: Prerequisites [code example] ### Step 2: Implementation [code example] ### Step 3: Verification [code example] ## Complete Playbook [code example] ## Common Mistakes | Mistake | Why It Fails | Correct Approach | |---------|-------------|-----------------| | Missing `become` | Permission denied | Add `become: true` | | Wrong variable scope | Undefined variable | Use `set_fact` or `vars` | | Not idempotent | Changes on every run | Check state before acting | | No error handling | Playbook aborts | Use `block/rescue` | ## Best Practices 1. **Always test first** — use `--check --diff` before applying 2. **Use FQCN** — fully qualified collection names prevent conflicts 3. **Handle errors** — never let playbooks fail silently 4. **Document your code** — future you will thank present you 5. **Version control** — commit playbooks to git ## Related Articles - Ansible Best Practices - Ansible Troubleshooting Guide - Ansible Performance Optimization ## Conclusion Define and use variables from inventories, vars files, facts, and command line. Follow the step-by-step guide above, test in check mode, and implement error handling for production reliability. --- ## Improve Playbook Debugging Using Ansible Lint URL: https://www.ansiblebyexample.com/articles/improve-playbook-debugging-using-ansible-lint Description: Explore how Ansible lint, a crucial command-line tool, improves Ansible automation by checking code quality, reducing errors, and enhancing playbook. ## Introduction Ansible lint is a command-line tool that is crucial in Ansible automation. It acts as a code quality checker, helping users identify errors and providing suggestions for playbook improvements. This tool is indispensable for maintaining the integrity and reliability of Ansible playbooks, reducing debugging time, and ensuring smooth automation processes. In this article, we’ll delve into the world of Ansible lint. We’ll explore how to install it, showcase some practical use cases, and Playbooknstrate how it can prevent errors during playbook execution. ## Installing Ansible Lint Before we dive into the benefits of Ansible lint, let’s first install it. There are multiple ways to do this: 1. Using pip: The simplest way to install Ansible lint is via Python Package Manager (pip). Run the following command: [code example] 2. On Red Hat Enterprise Linux (RHEL): If you’re on RHEL systems with a Red Hat Ansible Automation Platform subscription, you can use dnf to install Ansible lint: [code example] 3. From the GitHub source repository: You can also install Ansible lint directly from the source repository on GitHub, but this method requires `pip>=22.3.1`: [code example] With Ansible lint successfully installed, let’s explore its benefits through two practical examples. ## Ansible Lint Configuration File One of the powerful features of Ansible lint is its configuration ability. You can tailor its behavior to your specific needs using a configuration file (.an... --- ## Inserting Text in Files Using ANSI-C Quoting in OSX with sed URL: https://www.ansiblebyexample.com/articles/inserting-text-in-files-using-ansi-c-quoting-in-osx-with-sed Description: Learn how to use sed with ANSI-C quoting on OSX to insert text into specific lines of files, simplifying automated text editing tasks. ## Inserting Text in Files Using ANSI-C Quoting in OSX with `sed` When working with text files on OSX, the `sed` (stream editor) command proves to be a powerful tool for making automated edits. One common task involves inserting lines into specific positions within files. This article explores how to use `sed` with ANSI-C quoting to achieve this. ## Introduction to `sed` `sed` is a Unix utility that parses and transforms text, using a simple and compact programming language. It is commonly used for text substitution, deletion, and insertion tasks. ## ANSI-C Quoting ANSI-C quoting allows the use of escape sequences in string literals, facilitating the insertion of complex strings and multi-line texts. This is particularly useful when working with `sed` for inserting text into files. ## Inserting Text Using `sed` and ANSI-C Quoting Let's break down the process of inserting text at a specific line in a file using `sed` on OSX. The general syntax for inserting text at a specific line is: [code example] Where: - `-i ''` enables in-place editing of the file. - `'N i\text to insert'` specifies the line number `N` and the text to insert. ### Example 1: Inserting a Line at a Specific Position To insert a line at the 3rd position in a file, the following command is used: [code example] - `3i\` tells `sed` to insert the text at line 3. - `$'\n''text to insert'` uses ANSI-C quoting to ensure the newline character is interpreted correctly. ### Example 2: Inserting a Timestam... --- ## Install and Configure Molecule for Efficient Ansible Role and Collection Testing URL: https://www.ansiblebyexample.com/articles/install-and-configure-molecule-for-efficient-ansible-role-and-collection-testing Description: Step-by-Step Guide to Installing Molecule on Your Local Machine and Setting Up Testing Platforms for Accurate Automation Workflows As an Ansible automation expert, I often rely on the Molecule testing framework to test my Ansible roles and playbooks. Molecule makes it easy to validate your Ansible content across different operating systems and configurations, ensuring that your automation workflows are reliable and consistent. In this article, I will guide you through the steps to install Molecule on your local machine. ## Step 1: Install Python Molecule requires Python 3.6 or later to run. Check your current Python version by running the command `python --version`. If your version is lower than 3.6, you will need to install Python 3.6 or later. You can download and install Python from the official website. ## Step 2: Install pip Pip is the package installer for Python, and it is used to install Molecule and its dependencies. To install pip, run the following command: [code example] ## Step 3: Install Molecule Once you have pip installed, you can use it to install Molecule by running the command: [code example] This will install Molecule and its dependencies on your local machine. The full `requiremets.txt`: [code example] You can verify that Molecule is installed correctly by running the command `molecule --version`. [code example] ## Step 4: Install Docker (Optional) If you plan to use Docker as the testing platform for Molecule, you will need to install Docker on your local machine. You can download and install Docker from the official website. Once Docker is installed, you can test the ... --- ## Install Ansible — pip apt dnf Homebrew URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-all-platforms Description: Install Ansible on Ubuntu, RHEL, macOS, Fedora, Debian, and Windows WSL. Step-by-step instructions using pip, package managers, and virtual environments. ## Introduction Ansible is an agentless automation tool — you only install it on the **control node** (the machine that runs playbooks). Target machines need only SSH (Linux/macOS) or WinRM (Windows). This guide covers every major platform: Ubuntu/Debian, RHEL/CentOS/Rocky, Fedora, macOS, and Windows (via WSL). Choose the method that fits your environment. ## Quick Install (All Platforms) [code example] ## Prerequisites [code example] > **Note**: Ansible runs on the control node only. Managed hosts just need Python 3.9+ and SSH. ## Ubuntu / Debian ### Method 1: pip (Recommended — Latest Version) [code example] ### Method 2: APT Package Manager [code example] ### Method 3: pipx (Isolated Install) [code example] ### Ubuntu 24.04 Specific Notes [code example] ## RHEL / CentOS / Rocky / AlmaLinux ### Method 1: pip (Recommended) [code example] ### Method 2: DNF Package Manager [code example] ## Fedora [code example] ## macOS ### Method 1: Homebrew (Recommended) [code example] ### Method 2: pip [code example] ## Windows (via WSL) Ansible doesn't run natively on Windows — use Windows Subsystem for Linux (WSL). [code example] [code example] ### Windows Host (Managed Node) Setup [code example] ## Verify Installation [code example] ## Install Specific Versions [code example] ## Install Additional Collections [code example] ## Common Mistakes [code example] ## Troubleshooting [code example] ## Related Articles - Ansible Beginners Guide - Ansi... --- ## Install Ansible AWX Operator for Kubernetes (K8s) and OpenShift (OCP) — Ansible AWX URL: https://www.ansiblebyexample.com/articles/install-ansible-awx-operator-for-kubernetes-k8s-and-openshift-ocp-ansible-awx Description: How to deploy the latest Ansible AWX Operator in your local Red Hat OpenShift Local (formerly Red Hat CodeReady Containers), fully compatible with. ## How to Install Ansible AWX Operator for Kubernetes (K8s) and OpenShift (OCP)? Ansible AWX Operator is the preferred way to deploy an AWX instance in your network. The alternative way is to build and run Docker containers only for experienced users and developers. ## Install Ansible AWX - Ansible AWX Operator for Kubernetes built with Operator SDK and Ansible - Ansible AWX for Docker (experienced users) Ansible AWX is the upstream project of Ansible Automation Controller (formerly Ansible Tower), providing a modern web-UI and API interface to manage Ansible Playbooks, inventories, Credentials, and Vaults between your team in your organization. Running AWX using the AWX Operator is the preferred way for you to test the AWX web-UI and API to manage Ansible Playbook execution easily. Ansible AWX operator for Kubernetes built with Operator SDK and Ansible. AWX can also be installed and run in Docker, but this install path is only recommended for development/test-oriented deployments and has no official release. ## Links - AWX Operator - kustomize installation ## Playbook - Install Ansible AWX Operator for Kubernetes (K8s) or OpenShift (OCP) How to Install Ansible AWX Operator for Kubernetes (K8s). I will show you how to install the latest Ansible AWX Operator in your local Red Hat OpenShift Local (formerly Red Hat CodeReady Containers). If available, you can also use a Kubernetes (K8s) cluster or Red Hat OpenShift (OCP)cluster. ### code - kustomization.yaml [code exa... --- ## Install Ansible Controller Single Host URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-single-node Description: Complete guide to installing Red Hat Ansible Automation Platform on a single host with an internal database. Inventory file, prerequisites. ## Introduction The Red Hat Ansible Automation Platform (AAP) provides enterprise-grade automation with a web UI, REST API, role-based access control, and centralized job scheduling. While production deployments typically use a multi-node architecture, a single-host installation with an internal PostgreSQL database is ideal for development, testing, proof-of-concept, and small team environments. This guide walks through the complete installation process on a single RHEL host. ## Prerequisites ### System Requirements | Resource | Minimum | Recommended | |----------|---------|-------------| | CPU | 2 cores | 4+ cores | | RAM | 4 GB | 8+ GB | | Disk | 20 GB | 40+ GB | | OS | RHEL 8.4+ or RHEL 9 | RHEL 9.x | ### Software Requirements - **Red Hat subscription** with Ansible Automation Platform entitlement - **RHEL 8.4+** or **RHEL 9.x** (x86_64) - **Python 3.8+** (included with RHEL 8/9) - **Root or sudo access** - **DNS resolution** configured for the host ### Prepare the System [code example] ## Download the Installer Download the installer bundle from the Red Hat Customer Portal: 1. Navigate to access.redhat.com 2. Download the **Ansible Automation Platform Setup Bundle** for your RHEL version 3. Transfer to your host and extract: [code example] ## Configure the Inventory File The inventory file defines the installation topology. For a single-host deployment with internal database: [code example] ### Inventory Parameters Explained | Parameter | Description | |... --- ## Install Ansible on AlmaLinux 8 Easily with EPEL URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-almalinux-8 Description: Learn how to install and maintain Ansible on AlmaLinux 8 using the EPEL repository. Follow this simple guide to set up Ansible efficiently on your system. ## How to install Ansible in AlmaLinux version 8. Today we're going to talk about the easier way to install and maintain Ansible inside AlmaLinux 8 using the EPEL repository. ## How to install Ansible in AlmaLinux 8 - use Extra Packages for Enterprise Linux (EPEL) additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), AlmaLinux and Scientific Linux (SL), Oracle Linux (OL) Today we're talking about how to install Ansible in AlmaLinux 8. The easier way to install and maintain Ansible inside AlmaLinux version 8 is using the Extra Packages for Enterprise Linux (EPEL) additional repository. This repository is maintained by the Fedora Special Interest Group and manages a high-quality set of additional packages for Enterprise Linux: Red Hat Enterprise Linux (RHEL), AlmaLinux and Scientific Linux (SL), Oracle Linux (OL). ## Links - AlmaLinux website - AlmaLinux wiki EPEL ## Playbook Install latest Ansible release in AlmaLinux 8. ### code - Install-Ansible-AlmaLinux8.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in AlmaLinux using the EPEL repository. --- ## Install Ansible on Debian 12 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-debian-12-bookworm Description: The easier way to install the latest version of Ansible and maintain up-to-date in Debian 12 using APT and the \"main\" default repository. ## How to install Ansible in Debian version 12? Today we're going to talk about the easier way to install and maintain Ansible inside Debian using the default "main" repository. ## How to install Ansible in Debian - Included in the "main" default repository Today we're talking about How to install Ansible in Debian. The good news is that Ansible is included in the default repository so you could install it simply with your usual package manager "apt". You could expect the latest version of Ansible in the "main" repository. ## Step-by-step Install Ansible in Debian using the apt package manager and the "main" default repository. ### code - install-ansible-debian.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] ## Conclusion Now you know how to install the latest version of Ansible in Debian using the "main" repository. --- ## Install Ansible on macOS — Homebrew URL: https://www.ansiblebyexample.com/articles/install-ansible-for-mac-universal-intel-chip-and-apple-silicon-using-homebrew-in-macos-monterey Description: Install Ansible on macOS (Intel and Apple Silicon M1/M2/M3) using Homebrew. Complete guide with installation, verification, virtual environments. ## Introduction Homebrew is the easiest way to install Ansible on macOS — it handles all dependencies automatically and works on both Intel and Apple Silicon (M1/M2/M3/M4) Macs. ## Method 1: Homebrew (Recommended) ### Install Homebrew If you don't have Homebrew yet: [code example] ### Install Ansible [code example] Sample output (Apple Silicon): [code example] ### Verify Installation [code example] [code example] ### Update Ansible [code example] ## Method 2: pip (Python Package Manager) ### Using a Virtual Environment (Best Practice) [code example] ### Install Specific Version [code example] ### Install ansible-core Only If you only need the core engine without extra collections: [code example] | Package | Includes | Size | |---------|----------|------| | `ansible` | ansible-core + 85+ collections | ~350 MB | | `ansible-core` | Core engine only | ~15 MB | ## Method 3: pipx (Isolated Install) [code example] `pipx` keeps Ansible in its own isolated Python environment, avoiding dependency conflicts. ## Post-Installation Setup ### Create Configuration File [code example] ### Create Inventory File [code example] ### Test Ansible [code example] ### Install Additional Collections [code example] ## Troubleshooting ### "command not found: ansible" **Homebrew on Apple Silicon** installs to `/opt/homebrew/bin/`. Ensure it's in your PATH: [code example] ### Python Version Conflicts macOS ships with a system Python. Ansible needs Python 3.9+: [co... --- ## Install Ansible on Rocky Linux 9 URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-rocky-linux-9-ansible-install Description: How to install and maintain up-to-date Ansible inside Rocky Linux 9 using DNF and the ”appstream” system repository. Tested, copy-paste examples included. ## How to install Ansible in Rocky Linux version 9. Today we’re going to talk about the easier way to install and maintain Ansible inside Rocky Linux 9 using the appstream system repository. ## How to install Ansible in Rocky Linux 9 - `ansible-core` included in AppStream repository - `ansible` package not available Today we’re talking about How to install Ansible in Rocky Linux 9. The easier way to install and maintain up-to-date Ansible inside Rocky Linux version 9 is using the `ansible-core` package included in the AppStream distribution repository. Please notice that the package `ansible` isn’t available anymore. It’s not necessary to use the additional EPEL package repository. See also: Ansible terminology - ansible vs ansible-core packages. ## Links - Rocky Linux 9.0 Available Now ## Playbook Let’s jump into a quick live Playbook of how to install the latest version of Ansible in Rocky Linux. I’m going to install the `ansible-core` package in an Rocky Linux 9 using the AppStream distribution repository. ### code - Install-Ansible-RockyLinux9.sh [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to install the latest version of Ansible in Rocky Linux using the AppStream repository. --- ## Install Ansible on Ubuntu 24.04 LTS — pip & APT Guide URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-ubuntu-24-04-ansible-install Description: Install Ansible on Ubuntu 24.04 Noble Numbat step by step. Covers pip, APT PPA, pipx methods with version pinning and virtual environments. ## Introduction In the rapidly evolving landscape of IT infrastructure management, Ansible emerges as a beacon of efficiency and simplicity. This open-source tool, championed by Red Hat, automates complex IT tasks and provides a user-friendly interface that simplifies the process of managing large-scale systems. This article delves into the practical application of Ansible in managing Ubuntu systems, using a real-world session log to illustrate its integration and efficacy. The integration of Ansible into Ubuntu systems provides significant security benefits. By automating the patch management process, Ansible ensures that all systems are up-to-date with the latest security patches, reducing the risk of vulnerabilities. Additionally, Ansible's agentless architecture minimizes the system's attack surface, as it does not require additional software installed on the client machines. ## Instructions Here is a step-by-step guide to securely connect to an Ubuntu 24.04 server and install Ansible for automation tasks: ### Step 1: Establishing SSH Connection 1. Open Terminal: Start by opening your terminal on your local machine. 2. Connect via SSH: Use the SSH command to initiate a secure connection: [code example] 1. Replace `devops` with your actual username and `ubuntu.example.com` with your server's hostname or IP address. 2. Verify Host Authenticity: Upon first connection, you'll be asked to verify the host's fingerprint: The authenticity of host 'ubuntu.example.com ... --- ## Install Ansible on Windows 10 WSL URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-windows-10-wsl-windows-subsystem-for-linux Description: Learn how to install Ansible on Windows 10 using the Windows Subsystem for Linux (WSL), leveraging its compatibility for seamless automation tasks. ## How to install Ansible in Windows 10 Today we're going to talk about the easier way to install and maintain Ansible inside Windows 10 using the Windows Subsystem for Linux. ## How to install Ansible in Windows 10 Today we're talking about How to install Ansible in Windows 10. Officially Windows is not a supported operating system for the control node even if RedHat is working really hard to eliminate barriers to native Windows controllers. The reason behind this is that there are a lot of UNIX-isms deeply baked into most of Ansible that prevents it from working on native Windows, basically, Windows doesn't have the fork() syscall implementation. Ansible controller worker model as of 2.10 makes heavy use of the POSIX fork() syscall. - Cygwin Some people used Cygwin POSIX-compatibility projects but sometimes it just breaks so it's not a reliable solution. - Windows Subsystem for Linux The best alternative is to use Windows Subsystem for Linux, also known as WSL. Run WSL version 2 if Windows 10 later than build 2004 or Windows 11. Ansible works great on WSL and WSL2. ## Links More technical information: - https://docs.microsoft.com/en-us/windows/wsl/compare-versions - https://docs.ansible.com/ansible/latest/user_guide/windows_faq.html ## Playbook Let's jump in a quick live Playbook of how to install the latest and a specific version of Ansible in Windows using Windows Subsystem for Linux. You must be running Windows 10 version 2004 and higher (Build 19041 and higher)... --- ## Install Ansible on Windows WSL URL: https://www.ansiblebyexample.com/articles/how-to-install-ansible-in-windows-11-wsl-windows-subsystem-for-linux Description: Learn the easiest way to install and maintain Ansible on Windows 11 using the Windows Subsystem for Linux (WSL), enhancing compatibility and performance. How to install Ansible in Windows 11. Today we're going to talk about the easier way to install and maintain Ansible inside Windows 11 using the Windows Subsystem for Linux. ## How to install Ansible in Windows 11 Today we're talking about How to install Ansible in Windows 11. Officially Windows is not a supported operating system for the control node even if RedHat is working really hard to eliminate barriers to native Windows controllers. The reason behind this is that there are a lot of UNIX-isms deeply baked into most of Ansible that prevents it from working on native Windows, basically, Windows doesn't have the fork() syscall implementation. Ansible controller worker model as of 2.11 makes heavy use of the POSIX fork() syscall. - Cygwin Some people used Cygwin POSIX-compatibility projects but sometimes it just breaks so it's not a reliable solution. - Windows Subsystem for Linux The best alternative is to use Windows Subsystem for Linux, also known as WSL. Run WSL version 2 if Windows 10 later than build 2004 or Windows 11. Ansible works great on WSL and WSL2. ## Links More technical information: - https://docs.microsoft.com/en-us/windows/wsl/compare-versions - https://docs.ansible.com/ansible/latest/user_guide/windows_faq.html - https://arstechnica.com/gadgets/2021/10/the-best-part-of-windows-11-is-a-revamped-windows-subsystem-for-linux/ ## Playbook Let's jump in a quick live Playbook of how to install the latest and a specific version of Ansible in Windows us... --- ## Install AWX on Kubernetes — Open Source Ansible Tower URL: https://www.ansiblebyexample.com/articles/install-awx-on-kubernetes-open-source-ansible-tower Description: Install AWX on Kubernetes using the AWX Operator. Step-by-step guide covering prerequisites, operator deployment, AWX instance creation, ingress. ## Introduction AWX is the open-source upstream project for Red Hat Ansible Automation Controller (formerly Ansible Tower). It provides a web UI, REST API, RBAC, job scheduling, and workflow orchestration for Ansible automation. Since AWX 18+, the only supported installation method is Kubernetes via the **AWX Operator**. This guide covers the complete installation on Kubernetes, Minikube, and K3s. ## Prerequisites | Requirement | Minimum | |---|---| | Kubernetes cluster | 1.24+ | | kubectl | Matching cluster version | | RAM | 4 GB available | | CPU | 2 cores available | | Storage | 20 GB persistent volume | | DNS/Ingress | For external access | ## Option 1: Install on Minikube (Development) ### Start Minikube [code example] ### Deploy AWX Operator [code example] ### Create AWX Instance [code example] [code example] ### Get Admin Password [code example] ### Access AWX [code example] ## Option 2: Install on K3s (Production-Lite) [code example] ## Option 3: Install on Production Kubernetes ### With Helm (Alternative Method) [code example] ### AWX Custom Resource (Full Configuration) [code example] ## Post-Installation Setup ### Create Organization [code example] ### Add Credentials [code example] ### Add Project [code example] ### Add Inventory and Job Template [code example] ## Upgrade AWX [code example] ## Backup and Restore [code example] ## Troubleshooting ### Pods Stuck in Pending [code example] ### Database Migration Fails [code exam... --- ## Install Docker — Ansible apt Module URL: https://www.ansiblebyexample.com/articles/install-docker-in-debian-like-systems-ansible-module-apt-key-apt-repository-and-apt Description: How to automate the installation of the docker-ce engine in Ubuntu 20.04 LTS x86_64 (or amd64) using Ansible Playbook. The procedure is going to take care. ## How to Install Docker in Debian-like systems with Ansible? ## Ansible install Docker in Debian-like systems - Add Docker key => `ansible.builtin.apt_key` - Add Docker repository => `ansible.builtin.apt_repository` - Update apt cache and install Docker => `ansible.builtin.apt` In order to install Docker on a Debian-like system we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.apt_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Docker releases. The second step is to add the add Docker repository to the distribution. It's an extra website were `apt`, your distribution package manager looks like for software. You are going to use the `ansible.builtin.apt_repository` Ansible module. The third step is to update the apt cache for the available packages and install Docker (`docker-ce`) using the `ansible.builtin.apt` Ansible module. ## Parameters - `apt-key` `url` string - URL - `apt-key` `state` string - present/absent - `apt_repository` `repo` string - repository - `apt_repository` `state` string - present/absent - `apt` `name` string - name or package specific - `apt` `state` string - latest/present/absent - `apt` `update_cache` boolean - no/yes For the `ansible.builtin.apt_key` Ansible module I'm going to use two parameters: "`url`" and "`state`". The "url" parameter spe... --- ## Install Docker in Windows-like systems — Ansible module win_chocolatey URL: https://www.ansiblebyexample.com/articles/install-docker-in-windows-like-systems-ansible-module-win-chocolatey Description: How to automate the installation of the latest version of Docker Desktop in your Windows-like system with Ansible Playbook and Chocolatey. ## How to Install Docker in Windows-like systems with Ansible? Today I'm going to reveal how to install the software in a Windows-managed host using Chocolatey Package Manager. ## Ansible module win_chocolatey - `chocolatey.chocolatey.win_chocolatey` - Manage packages using chocolatey Chocolatey is the package manager for windows, it has the largest online registry of Windows packages. At the moment it contains nearly 9000 Community Maintained Packages. Today we're talking about Ansible module `win_chocolatey` to automate the software installation process. The full name is `chocolatey.chocolatey.win_chocolatey`, which means that is part of the collection distributed by "chocolatey". It manages packages in Windows using chocolatey. It's the windows correspondent of the ansible package module. ## Parameters - name list-string - the name of the package - state string - present/latest/absent/downgrade/reinstalled - version string - specific version The parameter list is pretty wide but this four are the most important options. In the "name" parameter you are going to specify the name of the package or a list of packages. If you would like to install a specific version you could specify it in the "version" parameter. The state specifies the action that we would like to perform. In our case installation is "present or latest". ## Links - Docker Desktop via Chocolatey ## Playbook Install Docker in Windows-like systems with Ansible Playbook. ### code [code example] ### ... --- ## Install Google Chrome in Debian like systems — Ansible module apt_key, apt_repository and apt URL: https://www.ansiblebyexample.com/articles/install-google-chrome-in-debian-like-systems-ansible-module-apt-key-apt-repository-and-apt Description: How to install the latest Google Chrome Stable on a Debian-like workstation (Debian, Ubuntu, Linux Mint, MX Linux, Deepin, AntiX, PureOS, Kali Linux,. ## How to Install Google Chrome in Debian-like systems with Ansible? ## Ansible install Google Chrome in Debian-like systems - Add Google Chrome key => `ansible.builtin.apt_key` - Add Google Chrome repository => `ansible.builtin.apt_repository` - Update apt cache and install Google Chrome => `ansible.builtin.apt` In order to install Google Chrome on a Debian-like system, we need to perform three different steps. The first step is to download the gpg signature key for the repository. You are going to use the `ansible.builtin.apt_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Google releases. The second step is to add the add Google Chrome repository to the distribution. It's an extra website were `apt`, your distribution Package Manager looks like for software. You are going to use the `ansible.builtin.apt_repository` Ansible module. The third step is to update the apt cache for the available packages and install Google Chrome using the `ansible.builtin.apt` Ansible module. ## Parameters - apt-key url string - URL - apt-key state string - present/absent - apt_repository repo string - repository - apt_repository state string - present/absent - apt name string - name or package-specific - apt state string - latest/present/absent - apt update_cache boolean - no/yes For the `ansible.builtin.apt_key` Ansible module I'm going to use two parameters: "url" and "state". The "url" pa... --- ## Install Google Chrome on Suse with Ansible URL: https://www.ansiblebyexample.com/articles/install-google-chrome-in-suse-like-systems-ansible-module-rpm-key-zypper-repository-and-zypper Description: Learn how to install the latest Google Chrome Stable on SUSE Linux Enterprise Server and openSUSE using Ansible. Follow our step-by-step guide. How to Install Google Chrome in Suse-like systems with Ansible? ## Ansible install Google Chrome in Suse-like systems - Add Google Chrome key => ansible.builtin.rpm_key - Add Google Chrome repository => community.general.zypper_repository - Update yum cache and install Google Chrome => community.general.zypper In order to install Google Chrome on a Suse-like system, we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.rpm_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Google releases. The second step is to add the add Google Chrome repository to the distribution. It's an extra website where `zypper`, your distribution package manager, looks like for software. You are going to use the `community.general.zypper_repository` Ansible module. The third step is to refresh the zypper cache for the available packages and install Google Chrome using the `community.general.zypper` Ansible module. ## Parameters - `rpm_key` key string - URL - `rpm_key` state string - present/absent For the `ansible.builtin.rpm_key` Ansible module I'm going to use two parameters: "key" and "state". The "key" parameter specifies the URL or the key ID of the repository GPG signature key and the "state" verify that is present in our system after the execution. - zypper_repository name string - zypper_rep... --- ## Install Microsoft Edge in RedHat-like systems — Ansible module rpm_key, yum_repository and yum URL: https://www.ansiblebyexample.com/articles/install-microsoft-edge-in-redhat-like-systems-ansible-module-rpm-key-yum-repository-and-yum Description: How to install the latest Microsoft Edge Stable on a RedHat-like workstation verify software using the public GPG key and set up the Microsoft repository.. ## How to Install Microsoft Edge in RedHat-like systems with Ansible? ## Microsoft Edge on Linux Microsoft Edge is available in the following channels: - Stable Channel - Beta Channel - Major update every 4 weeks - Dev Channel - Updated weekly - Canary Channel - Updated daily More information https://www.microsoftedgeinsider.com/en-us/download/ ## Ansible install Microsoft Edge in RedHat-like systems - Add Microsoft Edge key => ansible.builtin.rpm_key - Add Microsoft Edge repository => ansible.builtin.yum_repository - Update yum cache and install Microsoft Edge => ansible.builtin.yum In order to install Microsoft Edge on a RedHat-like system, we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.rpm_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Microsoft releases. The second step is to add the add Microsoft Edge repository to the distribution. It's an extra website where `yum/dnf`, your distribution package manager looks like for software. You are going to use the `ansible.builtin.yum_repository` Ansible module. The third step is to update the yum cache for the available packages and install Microsoft Edge using the `ansible.builtin.yum` Ansible module. ## Parameters - rpm_key key string - URL - rpm_key state string - present/absent - yum_repository name string - reposi... --- ## Install Microsoft Edge on Debian with Ansible URL: https://www.ansiblebyexample.com/articles/install-microsoft-edge-in-debian-like-systems-ansible-module-apt-key-apt-repository-and-apt Description: Learn how to install Microsoft Edge on Debian using Ansible. Follow our guide for a smooth setup process, including repository and key additions. ## How to Install Microsoft Edge in Debian-like systems with Ansible? ## Microsoft Edge on Linux Microsoft Edge is available in the following channels: - Stable Channel - Beta Channel - Major update every 4 weeks - Dev Channel - Updated weekly - Canary Channel - Updated daily More information https://www.microsoftedgeinsider.com/en-us/download/ ## Ansible install Microsoft Edge in Debian-like systems - Add Microsoft Edge key => ansible.builtin.apt_key - Add Microsoft Edge repository => ansible.builtin.apt_repository - Update apt cache and install Microsoft Edge => ansible.builtin.apt In order to install Microsoft Edge on a Debian-like system, we need to perform three different steps. The first step is to download the GPG signature key for the repository. You are going to use the `ansible.builtin.apt_key` Ansible module. This encrypted key verifies the genuinity of the packages and the repository and guarantees that the software is the same as Microsoft releases. The second step is to add the add Microsoft Edge repository to the distribution. It's an extra website were `apt`, your distribution package manager looks like for software. You are going to use the `ansible.builtin.apt_repository` Ansible module. The third step is to update the apt cache for the available packages and install Microsoft Edge using the `ansible.builtin.apt` Ansible module. ## Parameters - `apt-key` `url` string - URL - `apt-key` `state` string - present/absent - `apt_repository` `repo` string -... --- ## Install Minikube with Ansible — Local Kubernetes Setup Guide URL: https://www.ansiblebyexample.com/articles/streamlining-kubernetes-development-with-ansible-and-minikube Description: Install and configure Minikube with Ansible for local Kubernetes development. Complete guide with Galaxy role, manual installation, cluster management,. ## Introduction Minikube runs a single-node Kubernetes cluster locally — perfect for development, testing, and learning. Automating Minikube installation with Ansible ensures consistent setup across developer machines, CI/CD runners, and lab environments. ## Method 1: Ansible Galaxy Role The quickest approach — use the community `gantsign.minikube` role: [code example] ### Playbook [code example] ### Customize for ARM (Apple Silicon) [code example] ## Method 2: Manual Installation Playbook Full control over the installation: [code example] ### Install with Docker Driver [code example] ## Cluster Management Playbook [code example] ### Stop and Delete Cluster [code example] ## Minikube Addons Management [code example] ## Deploy Application to Minikube [code example] ## CI/CD Testing with Minikube [code example] ## Minikube vs Other Local K8s | Tool | Multi-node | Resource Usage | Best For | |------|-----------|----------------|----------| | Minikube | ✅ (experimental) | Medium | General dev/testing | | kind | ✅ | Low | CI/CD pipelines | | k3s | ✅ | Low | Edge/IoT | | Docker Desktop | ❌ | High | Simple local dev | | MicroK8s | ✅ | Low | Ubuntu/snap users | ## Related Articles - Ansible for Containers: Docker, Podman, Kubernetes - Create Kubernetes Namespace - Create Kubernetes Pod - Install AWX Operator for Kubernetes - Ansible Roles Explained - Ansible Best Practices Guide ## Conclusion Minikube with Ansible gives you reproducible local Kubernetes e... --- ## Install PostgreSQL — Ansible RHEL yum URL: https://www.ansiblebyexample.com/articles/install-postgresql-in-redhat-like-systems-ansible-modules-yum-stat-shell-service Description: How to automate the installation of PostgreSQL on RedHat-like systems: installing the necessary packages and dependency, initializing the. ## How to Install PostgreSQL with Ansible in RedHat-like systems? ## Ansible Install PostgreSQL in RedHat-like systems - Install server, client, utils => `ansible.builtin.yum` - Initialize db => `ansible.builtin.stat`, `ansible.builtin.shell` - Start and Enable at boot => `ansible.builtin.service` In order to install PostgreSQL on a RedHat-like system, you need to perform three steps. The first step is to install the packages to perform server, client, and utils. You are going to use the `ansible.builtin.yum` Ansible module. These include the distribution-related binaries, libraries, and documentation for your RedHat-like system. The second step is to initialize the PostgreSQL database. There is a command-line utility that you could execute using the Ansible `ansible.builtin.shell` module. The effective command executed is `postgresql-setup initdb`. This code is executed only if needed, the conditional check was performed by the `ansible.builtin.stat` module. The third step is to Start and Enable the PostgreSQL service at boot using the `ansible.builtin.service` Ansible module. ## Links - `ansible.builtin.yum` - `ansible.builtin.stat` - `ansible.builtin.shell` - `ansible.builtin.service` ## Playbook Let's jump into a real-life playbook to install PostgreSQL in RedHat-like systems with Ansible. I'm going to show you how to install the PostgreSQL server, client utilities, and the Python libraries to manage the DBMS. The second step is to perform the initial PostgreSQL da... --- ## Install PostgreSQL in Debian-like systems — Ansible modules apt, stat, shell, service URL: https://www.ansiblebyexample.com/articles/install-postgresql-in-debian-like-systems-ansible-modules-apt-stat-shell-service Description: How to automate the installation of PostgreSQL on Debian-like systems: installing the necessary packages and dependency, initializing the. ## How to Install PostgreSQL with Ansible in RedHat-like systems? I’m going to show you a live Playbook and some simple Ansible code. ## Ansible Install PostgreSQL in Debian-like systems - Install server, client, utils => `ansible.builtin.apt` - Initialize db => `ansible.builtin.stat`, `ansible.builtin.shell` - Start and Enable at boot => `ansible.builtin.service` In order to install PostgreSQL on a Debian-like system, you need to perform three steps. The first step is to install the packages to perform server, client, and utils. You are going to use the `ansible.builtin.apt` Ansible module. These include the distribution-related binaries, libraries, and documentation for your Debian-like system, Ubuntu as well. The second step is to initialize the PostgreSQL database. There is a command-line utility that you could execute using the Ansible `ansible.builtin.shell` module. The effective command executed is `/usr/lib/postgresql/14/bin/initdb -D /var/lib/postgresql/14/main` (suppose you are using version 14). This code is executed only if needed, the conditional check was performed by the `ansible.builtin.stat` module. The third step is to Start and Enable the PostgreSQL service at boot using the `ansible.builtin.service` Ansible module. ## Links - `ansible.builtin.apt` - `ansible.builtin.stat` - `ansible.builtin.shell` - `ansible.builtin.service` ## Playbook Let’s jump into a real-life playbook to install PostgreSQL in Debian-like systems with Ansible. I’m going t... --- ## Install Red Hat CodeReady Containers to run OpenShift 4 in macOS URL: https://www.ansiblebyexample.com/articles/install-red-hat-codeready-containers-to-run-openshift-4-in-macos Description: How to install Red Hat CodeReady Containers to run a full OpenShift 4 cluster in your Mac running macOS Big Sur and use the command line and the web. ## What is Red Hat CodeReady Containers - an OpenShift 4 cluster for local development - minimum 4 vCPU, 8 GB RAM, 35 GB storage CodeReady Containers is designed for local development and testing on an OpenShift 4 cluster. The CodeReady Containers requires at least: - 4 virtual CPUs (vCPUs) - 8 GB of RAM memory - 35 GB of storage space ## Playbook How to Install Red Hat CodeReady Containers in MacOS and simple usage. - Red Hat OpenShift 4 on your laptop: Introducing Red Hat CodeReady Containers ### cluster setup [code example] ### cluster start [code example] ### cluster status [code example] ### cluster webui The server is accessible via web console at: https://console-openshift-console.apps-crc.testing ### cluster stop [code example] ### cluster restart [code example] ## Conclusion Now you know how to install Red Hat CodeReady Containers in MacOS and how to manage the OpenShifft 4 cluster, start, stop, restart, status. ## Related For a production-focused walkthrough, see Luca Berton's guide on Ansible Kubernetes day-2 operations. --- ## Install Red Hat OpenShift Local Kubernetes in macOS on MacBook Pro Intel x86_64 and M1 arm64 URL: https://www.ansiblebyexample.com/articles/install-red-hat-openshift-local-kubernetes-in-macos-on-macbook-pro-intel-x86-64-and-m1-arm64 Description: How to install Red Hat OpenShift Local Kubernetes (formerly CodeReady Containers) to run a complete OpenShift 4 cluster in your Mac (Intel Chip x86_64 or. ## What is Red Hat OpenShift Local - an OpenShift 4 cluster for local development - minimum 4 vCPU, 8 GB RAM, 35 GB storage - formerly CodeReady Containers OpenShift Local is designed for local development and testing on an OpenShift 4 cluster. The OpenShift Local requires at least: - 4 virtual CPUs (vCPUs) - 8 GB of RAM memory - 35 GB of storage space ## Playbook How to Install Red Hat OpenShift Local in MacOS and simple usage. - Red Hat OpenShift 4 on your laptop: Introducing Red Hat CodeReady Containers ### cluster setup [code example] ### cluster start [code example] ### cluster status [code example] ### cluster WebUI The server is accessible via web console at: https://console-openshift-console.apps-crc.testing ### cluster stop [code example] ### cluster restart [code example] ## Conclusion Now you know how to install Red Hat OpenShift Local (formerly CodeReady Containers) in macOS and how to manage the OpenShifft 4 cluster, start, stop, restart, and status. ## Further reading To go deeper, managing Kubernetes with Ansible playbooks expands on these patterns in production. --- ## Install SELinux with Ansible — RHEL 8 URL: https://www.ansiblebyexample.com/articles/installing-and-enabling-selinux-with-ansible-on-rhel-8 Description: Learn how to use Ansible to install, configure, and enable SELinux on RHEL 8. Ensure security and compliance through automation. SELinux (Security-Enhanced Linux) is a vital security feature in RHEL 8 that enforces mandatory access control (MAC). This guide demonstrates how to automate the installation and configuration of SELinux using Ansible. ## Why Enable SELinux? SELinux provides enhanced security by restricting access based on policies. It prevents unauthorized access and mitigates security risks. ### Key Benefits of SELinux: - **Mandatory Access Control (MAC)**: Restricts access based on predefined security policies. - **Process Isolation**: Prevents unauthorized processes from accessing sensitive resources. - **Enhanced Security**: Reduces the attack surface in enterprise environments. ## Prerequisites Before running the Ansible playbook, ensure: 1. You have a **control node** with Ansible installed. 2. The **target system** (RHEL 8) is accessible via SSH. 3. You have **sudo/root privileges** on the target machine. ## Writing an Ansible Playbook to Install SELinux ### 1. **Installing SELinux Packages** We need to ensure that the necessary SELinux packages are installed on the target system. [code example] ### 2. **Configuring SELinux Mode** The SELinux configuration file (`/etc/selinux/config`) needs to be modified to set the mode to `enforcing`. [code example] ### 3. **Checking Current SELinux Status** Before enabling SELinux, check its current mode. [code example] ### 4. **Enabling SELinux if Not Already Enforcing** If SELinux is not in enforcing mode, we enable it dynamicall... --- ## Install Software on Windows with Ansible — win_chocolatey Module Guide URL: https://www.ansiblebyexample.com/articles/install-google-chrome-in-windows-like-systems-ansible-module-win-chocolatey Description: Install, update, and manage Windows software with Ansible's win_chocolatey module. Deploy Chrome, Firefox, VS Code, and any Chocolatey package across. ## Introduction Chocolatey is the package manager for Windows — like `apt` or `yum` for Linux. Ansible's `win_chocolatey` module lets you install, update, and remove any of the 9,000+ Chocolatey packages across your Windows fleet. This guide covers single packages, bulk installs, version pinning, and common deployment patterns. ## Prerequisites | Requirement | Details | |-------------|---------| | Ansible collection | `chocolatey.chocolatey` | | Windows target | WinRM configured (setup guide) | | Chocolatey | Auto-installed by the module if missing | [code example] ## Module Parameters | Parameter | Type | Description | |-----------|------|-------------| | `name` | string/list | Package name(s) from Chocolatey repository | | `state` | string | `present`, `latest`, `absent`, `downgrade`, `reinstalled` | | `version` | string | Specific version to install | | `source` | string | Custom Chocolatey source/feed URL | | `install_args` | string | Arguments passed to the native installer | | `package_params` | string | Parameters passed to the Chocolatey package | | `allow_prerelease` | bool | Allow pre-release versions | | `force` | bool | Force reinstall even if already installed | | `ignore_checksums` | bool | Skip package checksum validation | | `timeout` | int | Timeout in seconds for the install | ## Basic Examples ### Install a Single Package [code example] ### Install Multiple Packages [code example] ### Install Specific Version [code example] ### Update to Lates... --- ## Install Spotify snap in Debian-like systems — Ansible module snap URL: https://www.ansiblebyexample.com/articles/install-spotify-snap-in-debian-like-systems-ansible-module-snap Description: How to automate the installation of Spotify snap system-wide in Debian-like systems using Ansible module snap. Tested, copy-paste examples included. ## How to Install Spotify snap on Debian-like systems with Ansible? ## Ansible installs Spotify snap on Debian-like systems - `community.general.snap` - Manages snaps Today we are going to talk about the Ansible module `snap`. The full name is `community.general.snap`, it's part of `community.general` modules maintained by the Ansible Community. The purpose of the `snap` module is to Manage snaps in the target system. ## Parameters - name _string_ - snap name - state _string_ - present/absent - channel _string_ - "stable" - classic _boolean_ - no/yes Let me summarize the parameters of `snap` module. The only required is "name", where you specify the snap name to install or remove. The parameter "state" specifies if you would like to perform the install action ("present" option) or the remove action ("absent" option). The parameter "channel" specifies which channel to use, default the "stable" channel. The parameter "classic" allows the confinement allows a snap to have the same level of access to the system as "classic" packages. ## Links - community.general.snap - spotify snap ## Playbook ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Install Spotify snap in Debian-like systems with Ansible. --- ## Install Spotify snap in RedHat-like systems — Ansible module snap URL: https://www.ansiblebyexample.com/articles/install-spotify-snap-in-redhat-like-systems-ansible-module-snap Description: How to automate the installation of Spotify snap system-wide in RedHat-like systems using Ansible module snap. With clear, copy-paste, step-by-step examples. ## How to Install Spotify snap on RedHat-like systems with Ansible? ## Ansible installs Spotify snap on RedHat-like systems - `community.general.snap` - Manages snaps Today we are going to talk about the Ansible module `snap`. The full name is `community.general.snap`, it's part of `community.general` modules maintained by the Ansible Community. The purpose of the `snap` module is to Manage snaps in the target system. ## Parameters - name _string_ - snap name - state _string_ - present/absent - channel _string_ - "stable" - classic _boolean_ - no/yes Let me summarize the parameters of `snap` module. The only required is "name", where you specify the snap name to install or remove. The parameter "state" specifies if you would like to perform the install action ("present" option) or the remove action ("absent" option). The parameter "channel" specifies which channel to use, default the "stable" channel. The parameter "classic" allows the confinement allows a snap to have the same level of access to the system as "classic" packages. ## Links - community.general.snap - spotify snap - Installing snap on Fedora ## Playbook ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Install Spotify snap in RedHat-like systems with Ansible. --- ## Install Visual Studio Code: Manual, Homebrew, Ansible Methods URL: https://www.ansiblebyexample.com/articles/install-visual-studio-code-for-mac-universal-intel-chip-and-apple-silicon-manual-homebrew-and-ansible Description: Learn how to install Visual Studio Code on macOS using manual download, Homebrew, or Ansible. Explore the pros and cons of each installation method. ## Visual Studio Code Visual Studio Code is an excellent Free and Built Open Source IDE that speeds up any software development nowadays. It runs everywhere. The main four feature are: - IntelliSense - Run and Debug - Built-in Git - Extensions ## Manual way Manually download and install from the official website https://code.visualstudio.com/. - Pro: easy for new users - Cons: time-consuming to upgrade, time-consuming for multiple machines to install and upgrade ## Homebrew way Using the Homebrew package manager, you can easily search and install the visual-studio-code package. - Pro: fast install and upgrade - Cons: require Terminal skill, time-consuming for multiple machines installation and upgrade ## Ansible way Using Ansible, you can quickly deploy an Ansible Playbook to install the visual-studio-code package via Homebrew. - Pro: fast install and upgrade, unlock parallel multiple machine installation - Cons: require Terminal skill ### code - install-visualstudiocode.yml [code example] - inventory [code example] ### execution There is currently a bug in the module report, but it successfully installs Visual Studio Code. [code example] ### idempotency [code example] ## Conclusion Now you know three ways to install and maintain up-to-date Visual Studio Code for Mac Universal (Intel Chip and Apple Silicon): Manual, Homebrew and Ansible. --- ## Install Zoom flatpak in Debian-like systems — Ansible module flatpak URL: https://www.ansiblebyexample.com/articles/install-zoom-flatpak-in-debian-like-systems-ansible-module-flatpak Description: How to automate the installation of Zoom flatpak system-wide in Debian-like systems using Ansible module flatpak. Tested, copy-paste examples included. ## How to install Zoom flatpak in Debian-like systems with Ansible? ## Ansible install Zoom flatpak in Debian-like systems - `community.general.flatpak` - Manage flatpaks Today we are going to talk about the Ansible module `flatpak`. The full name is `community.general.flatpak`, it's part of `community.general` modules maintained by the Ansible Community. The purpose of the `flatpak` module is to Manage flatpaks in the target system. ## Parameters - name _string_ - flatpak name - state _string_ - present/absent - method _string_ - system/user - remote _string_ - flathub - no_dependencies _string_ - no/yes - executable _string_ - flatpak Let me summarize the parameters of `flatpak` module. The only required is "name", where you specify the flatpak name to install or remove. The parameter "state" specifies if you would like to perform the install action ("present" option) or the remove action ("absent" option). The parameter "method" specifies if you would like to install the flatpak system-wide (default) or only for the current user. The following parameters are more for advanced users. For example specify a different source with `remote` parameter other than the default "flathub"; not install the dependency "no_dependencies" parameter or if the `executable` is different than the usual `flatpak`. ## Links - Flatpak technology - Zoom flatpak ## Playbook How to install Zoom flatpak in Debian-like systems with Ansible Playbook. ### code [code example] ### execution ... --- ## Install Zoom flatpak in RedHat-like systems — Ansible module flatpak URL: https://www.ansiblebyexample.com/articles/install-zoom-flatpak-in-redhat-like-systems-ansible-module-flatpak Description: How to automate the installation of Zoom flatpak system-wide in RedHat-like systems using Ansible module flatpak. Tested, copy-paste examples included. ## How to install Zoom flatpak in RedHat-like systems with Ansible? ## Ansible install Zoom flatpak in RedHat-like systems - `community.general.flatpak` - Manage flatpaks Today we are going to talk about the Ansible module `flatpak`. The full name is `community.general.flatpak`, it's part of `community.general` modules maintained by the Ansible Community. The purpose of the `flatpak` module is to Manage flatpaks in the target system. ## Parameters - name _string_ - flatpak name - state _string_ - present/absent - method _string_ - system/user - remote _string_ - flathub - no_dependencies _string_ - no/yes - executable _string_ - flatpak Let me summarize the parameters of `flatpak` module. The only required is "name", where you specify the flatpak name to install or remove. The parameter "state" specifies if you would like to perform the install action ("present" option) or the remove action ("absent" option). The parameter "method" specifies if you would like to install the flatpak system-wide (default) or only for the current user. The following parameters are more for advanced users. For example specify a different source with `remote` parameter other than the default "flathub"; not install the dependency "no_dependencies" parameter or if the `executable` is different than the usual `flatpak`. ## Links - Flatpak technology - Zoom flatpak ## Playbook How to install Zoom flatpak in RedHat-like systems with Ansible Playbook. ### code [code example] ### execution ... --- ## Installing and Configuring the Ansible Code Bot URL: https://www.ansiblebyexample.com/articles/installing-and-configuring-the-ansible-code-bot Description: Set up Ansible Code Bot to automatically scan GitHub repos for Ansible best practices, generate fix PRs, and maintain code quality across your. ## Introduction The Ansible Code Bot is a GitHub App that automatically scans your repositories for Ansible playbooks, roles, and collections — then opens pull requests with suggested improvements based on current best practices. Think of it as an automated code reviewer that never sleeps, catching deprecated modules, outdated syntax, and missed optimization opportunities. ## What Ansible Code Bot Does The bot analyzes your Ansible code and generates PRs for: | Category | Examples | |----------|---------| | **Deprecated modules** | Replace `command` with `ansible.builtin.command` (FQCN) | | **Outdated syntax** | Update `with_items` to `loop` | | **Best practices** | Add `no_log: true` to password tasks | | **Module updates** | Use newer module parameters | | **Security** | Flag hardcoded credentials | | **Performance** | Suggest `ansible.builtin.package` over `yum`/`apt` for cross-platform | ### Example PR from Code Bot [code example] ## Prerequisites - GitHub account (personal or organization) - Repositories containing Ansible code - Red Hat account (for subscription authentication) ## Installation ### Step 1: Install the GitHub App 1. Go to the Ansible Code Bot GitHub App page 2. Click **Install** 3. Choose your organization or personal account ### Step 2: Select Repositories Choose which repositories the bot can access: - **All repositories** — scan everything (recommended for organizations) - **Select repositories** — pick specific repos ### Step 3: Grant P... --- ## Installing Containerized Ansible Automation Platform URL: https://www.ansiblebyexample.com/articles/installing-containerized-ansible-automation-platform Description: Learn how to install the containerized Ansible Automation Platform on Red Hat Enterprise Linux 9, simplifying management and enhancing security with a. ## Introduction The world of IT automation is rapidly evolving, and Red Hat is at the forefront with its containerized Ansible Automation Platform. In this guide, we will walk you through the containerized Ansible Automation Platform installation process on Red Hat Enterprise Linux 9 (RHEL 9). This innovation opens doors to a more streamlined and efficient management experience. ## Why Containerized Ansible Automation Platform? As the Ansible Automation Platform has grown in complexity with the addition of new services and components, managing it has become more challenging. The containerized Ansible Automation Platform represents a significant step towards improving this management experience. It simplifies installation, enhances security, and provides a launchpad for new features, all while reducing the platform’s footprint. The containerized Ansible Automation Platform offers several advantages: 1. Slimmed Down Installation: The installation process is simplified, making it more accessible to users. 2. Layered Installation: This approach provides flexibility and customization options. 3. Enhanced Security: The use of rootless Podman containers ensures security from the outset. 4. Platform for Future Features: The containerized platform sets the stage for future enhancements. 5. Lighter Footprint: It caters to various markets and solutions, ensuring optimal performance. With this technical preview release, you gain access to exciting features such as: - Applying Your L... --- ## Installing JetPorch via Packages on macOS URL: https://www.ansiblebyexample.com/articles/installing-jetporch-via-packages-on-macos Description: A Step-by-Step Guide to Installing JetPorch via Packages on macOS. Tested on real machines with clear, copy-paste examples. ## Introduction JetPorch, or Jet Enterprise Professional Orchestrator or simply Jet, is a versatile and community-driven IT automation platform designed for configuration management, deployment, orchestration, patch management, and executing arbitrary workflows. Jet stands out for its simplicity, consistency, and speed, making it a powerful choice for managing IT infrastructure. This article will guide you through installing JetPorch on macOS using packages. ### Jet Features Before diving into the installation process, let's briefly explore some of the key features that make JetPorch a compelling choice for IT professionals: - **Language Simplicity**: JetPorch places a strong emphasis on simplicity, consistency, and stability in its design and user interface, ensuring a minimal and clean aesthetic. - **Rust-Powered Parallel SSH**: JetPorch leverages the speed and efficiency of Rust to offer extremely fast multithreaded parallel SSH capabilities, ensuring rapid execution of tasks. - **Multi-Worker Distributed SSH**: Expected to be available in Q4 2023, JetPorch will introduce a multi-worker distributed SSH fanout, allowing for efficient task execution across multiple hosts. Additionally, true planetary-scale automation is planned for December 2023/January 2024. - **Enterprise Security and Audit Focus**: Security is a top priority for JetPorch, ensuring that your automation processes are carried out with the highest level of safety and compliance. - **Friendly Documentation**... --- ## Integrate Ansible with Backstage for Streamlined Automation URL: https://www.ansiblebyexample.com/articles/integrate-ansible-with-backstage-for-streamlined-automation Description: Discover how to integrate Ansible with Backstage for enhanced infrastructure automation, self-service tools, and improved developer workflows. Modern software development often revolves around managing complex infrastructure and ensuring a seamless developer experience. Tools like Ansible and Backstage address these challenges by offering powerful capabilities for infrastructure automation and software cataloging, respectively. When combined, they create a robust solution that bridges the gap between operations and development, streamlining workflows and improving visibility. This article explores how Ansible and Backstage complement each other and how their integration can benefit organizations. --- ## What Is Ansible? **Ansible** is an open-source automation platform that simplifies tasks such as configuration management, application deployment, and IT orchestration. With its agentless architecture, Ansible uses YAML-based playbooks to define tasks and execute them across systems, making it highly accessible for teams looking to automate repetitive processes. Key features of Ansible include: - **Agentless Architecture**: Requires no additional software on managed nodes. - **Declarative Language**: YAML syntax makes it easy to write and understand playbooks. - **Idempotence**: Ensures that tasks are executed only when changes are required. - **Extensibility**: Can integrate with CI/CD pipelines, monitoring systems, and more. --- ## What Is Backstage? Backstage, developed by Spotify, is an open-source developer portal designed to centralize and organize software development workflows. It features a **Softwar... --- ## Integrate Ansible with VMware vRealize Automation Efficiently URL: https://www.ansiblebyexample.com/articles/integrate-ansible-with-vmware-vrealize-automation-efficiently Description: Learn how to efficiently integrate Ansible with VMware vRealize Automation to automate IT operations, enhance scalability, and ensure consistency. ## Introduction As IT environments become increasingly complex, the need for robust automation tools to manage infrastructure across various platforms is more critical than ever. VMware vRealize Automation (vRA) is a powerful tool that helps IT teams manage, automate, and deliver IT services at scale. Integrating Ansible, a widely used automation tool, with vRA enhances its capabilities, enabling seamless configuration management, application deployment, and infrastructure orchestration. This article explores how to integrate Ansible with VMware vRealize Automation, the benefits of this integration, and best practices for leveraging these tools to streamline IT operations. ## Why Integrate Ansible with VMware vRealize Automation? Integrating Ansible with vRA offers several advantages: 1. **Enhanced Automation:** Ansible's agentless architecture and extensive module library make it an ideal companion to vRA, allowing for the automation of complex tasks across a variety of environments. 2. **Consistency and Compliance:** Ansible ensures consistent configuration across environments, reducing configuration drift and ensuring compliance with internal policies and external regulations. 3. **Scalability:** Ansible can automate tasks across large-scale environments, including cloud, on-premises, and hybrid infrastructures, making it a perfect match for the scalable nature of vRA. 4. **Simplified Management:** With Ansible's simple, human-readable playbooks, IT teams can manag... --- ## Integrate Splunk Logging with Ansible Automation Controller URL: https://www.ansiblebyexample.com/articles/integrate-splunk-with-ansible-automation-controller-enhancing-monitoring-and-insights-with-logging-aggregation Description: Learn to integrate Splunk logging with Ansible Automation Controller. Follow this guide for setting up Splunk HTTP Event Collector and configuring log. ## Introduction In today’s rapidly evolving IT landscape, robust logging and centralized log aggregation are critical components for ensuring your infrastructure's stability, security, and performance. Automation Controller, a powerful tool in the realm of IT operations, offers seamless integration with external log aggregation services like Splunk, enabling you to gain valuable insights into your system’s behavior and troubleshoot issues effectively. We explore how to set up Splunk logging integration with Automation Controller using the Splunk HTTP Collector. Logging plays a pivotal role in providing comprehensive insights into the performance and usage of systems. Ansible Automation Controller offers a powerful logging and aggregation feature, enabling detailed logs to be sent to third-party external log aggregation services. These services serve as valuable tools for understanding controller behavior, technical trends, and system health. ### Key Highlights: - Aggregated Data: By sending logs to external aggregation services, administrators gain the ability to analyze events within the infrastructure comprehensively. This helps in monitoring for anomalies, correlating events between different services, and gaining deeper insights into system operations. - Data Types: The types of data most beneficial to the controller include job fact data, job events/job runs, activity stream data, and log messages. These data types provide a well-rounded view of the controller’s activ... --- ## Introducing “Ansible Collab” — A New Era for Ansible Community Events URL: https://www.ansiblebyexample.com/articles/introducing-ansible-collab Description: Empowering Community and Innovation: Unveiling the Future of Automation with Ansible Collab. With clear, copy-paste, step-by-step examples. ## Introduction Ansible has been at the forefront of automation and orchestration, revolutionizing how we manage systems and deploy software. Since its inception, the Ansible community has played a pivotal role in shaping its growth and evolution. Our journey through various events and summits has been nothing short of remarkable. Today, we are thrilled to announce the next step in this journey: the introduction of "Ansible Collab." ### The Evolution of Community Gatherings The Ansible community's voice has been echoing through the halls of Ansible Contributor Summits since 2016. These summits, an essential part of AnsibleFest, have fostered innovation and collaboration among our community members. With the onset of the pandemic, we seamlessly transitioned to virtual formats, ensuring our community's spirit remained unbroken. However, as times change and the community expands, so must our approach to gatherings. Notably, AnsibleFest has evolved and is now a segment of the broader Red Hat Summit. This shift calls for a new, more inclusive, and engaging format for our community events. ## Introducing Ansible Collab In 2023, we ventured into a new format with the Ansible Community Day, focusing more on user engagement alongside the Ansible Contributor Summit. Despite our best efforts, we noticed a certain overlap and confusion about the target audience for these events. We realized the need for a more unified and clear approach. Therefore, in 2024, we are excited to roll ... --- ## Introducing the zabbix_add_host Ansible Role Simplifying Certificate Validation with Zabbix URL: https://www.ansiblebyexample.com/articles/introducing-the-zabbix-add-host-ansible-role-simplifying-certificate-validation-with-zabbix Description: Simplifying Zabbix Server Management with the ‘zabbix_add_host’ Ansible Role by Steffen Scheib, Senior Technical Account Manager at Red Hat ## Introduction In the ever-evolving world of IT automation and monitoring, the use of Ansible and Zabbix has become a popular choice for many professionals. One of the critical aspects of managing Zabbix servers is ensuring secure communication and certificate validation. To simplify the process, Steffen Scheib, a Senior Technical Account Manager at Red Hat, has released a new Ansible role — ‘zabbix_add_host.’ In this article, we will explore this role and its purpose in enhancing Zabbix server management. ### Automating Monitoring with Ansible Ansible is a powerful open-source automation tool that allows you to automate tasks, configuration management, and application deployment. It simplifies complex processes and makes them easily repeatable. When it comes to Zabbix, an open-source monitoring solution, Ansible can be a valuable tool for managing and configuring your monitoring infrastructure. Steffen Scheib, an experienced professional in the field, has recognized the need for simplifying the process of certificate validation in Zabbix, and as a result, he created the ‘zabbix_add_host’ Ansible role. ## Introducing the ‘zabbix_add_host’ Role The ‘zabbix_add_host’ role is designed to streamline the process of adding hosts to Zabbix server instances with certificate validation enabled. This role leverages the certified ‘zabbix.zabbix.zabbix_host’ module, which makes the task of authenticating with Zabbix easier for both newcomers and experienced users. ### When to Consid... --- ## Introduction to Chip Design with Open-Source EDA Tools URL: https://www.ansiblebyexample.com/articles/introduction-to-chip-design-with-open-source-eda-tools Description: Excited to announce my latest Coursera course, 'Introduction to Chip Design with Open-Source EDA Tools' in collaboration with the Starweaver Instructor. # 🚀 Exciting Announcement – My New Course on Coursera! 🎓 I'm thrilled to introduce my latest course, **"Introduction to Chip Design with Open-Source EDA Tools"**, created in collaboration with the **Starweaver Instructor Team** and now available on **Coursera**! {{}} ## Why Chip Design? Chips are at the heart of modern technology, powering everything from smartphones to AI systems. But did you know that **open-source EDA tools** have made chip design more **accessible** and **affordable** than ever? This course is designed for **beginners** and aspiring engineers looking to get hands-on experience in semiconductor design. ## 🔍 What You'll Learn: ✅ Develop **basic chip layouts** using **open-source EDA tools** ✅ Analyze and apply **chip design workflows** ✅ Design, simulate, and validate a **functional logic circuit** ✅ Use industry-leading **tools like Magic, OpenROAD, KiCAD, SkyWater PDK, and NGSPICE** {{}} ## 📌 Course Details: 🎯 **Beginner-friendly** – No prior chip design experience needed 🕒 **2 hours to complete** – Learn at your own pace 📜 **Earn a shareable certificate** – Add it to your LinkedIn profile 🔥 **Recently updated – February 2025!** ## Who Should Take This Course? 💡 **Aspiring engineers & hardware designers** 💡 **Electrical engineering students** 💡 **Open-source developers** 💡 **Tech enthusiasts curious about semiconductor design** {{}} ## 🎓 Start Learning Today! 🔗 **Enroll Now:** https://imp... --- ## JetPorch — Rust-Based Automation Tool by Michael DeHaan URL: https://www.ansiblebyexample.com/articles/jetporch-rust-automation-like-ansible-led-by-michael-dehaan Description: JetPorch is a Rust-based IT automation tool created by Ansible founder Michael DeHaan. Compare features, syntax, and performance with Ansible. # JetPorch — Rust-Based Automation Tool by Michael DeHaan ## Introduction Rust-Based Automation Tool by Michael DeHaan. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of JetPorch requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use ta... --- ## JetPorch Automation Tech Preview One Release URL: https://www.ansiblebyexample.com/articles/jetporch-automation-tech-preview-one-release Description: Save the Date and Join the Celebration on Friday, Sept 29th at 11:30 EST. With clear, copy-paste, step-by-step examples. ## Introduction Jet is a versatile and community-driven IT automation platform designed for various tasks such as configuration, deployment, orchestration, patch management, and executing diverse workflows. Led by Michael DeHaan, the original creator of widely-used IT automation tools like Cobbler and Ansible, Jet combines simplicity, consistency, and stability in its design. Tech Preview Release: Jet is gearing up for its first Tech Preview release, scheduled for September 29th, 2023. To celebrate this milestone, a virtual text-only release party will be held on Discord starting at 11:30 AM EST and continuing throughout the day and night. Key Features of Jet: - Language Simplicity: Jet emphasizes straightforward and consistent language usage for an easy-to-understand syntax. - Multithreaded Performance: Powered by Rust, Jet delivers blazing-fast multithreaded performance. - Security and Audit Focus: Jet prioritizes enterprise-grade security for efficient and secure IT operations. - Documentation: Jet offers user-friendly documentation to help users maximize its capabilities. - Extensibility: While Jet’s core modules are in Rust, users can create modules in languages supporting JSON. - Core Language and Compatibility: Jet’s core language and compatibility are designed to cater to IT professionals familiar with Ansible. It utilizes a YAML dialect similar to Ansible’s playbook language, ensuring a smooth transition for Ansible users. Additionally, Jet employs Handlebars as i... --- ## Join Ansible Community Day Berlin 2023: Engage and Connect URL: https://www.ansiblebyexample.com/articles/ansible-community-day-berlin-2023 Description: Attend Ansible Community Day in Berlin on September 20, 2023. Connect with Ansible users, contributors, and developers, and learn from expert-led sessions. ## Introduction The Ansible Community Day in Berlin 2023 is an event organized by The Ansible Community Team at Red Hat. It is designed to connect with people who use, contribute to, and develop the Ansible project globally. This event serves as a platform to engage with the diverse Ansible community, including users, contributors, and developers, and to highlight their experiences and contributions. ## Links - https://www.ansible.com/blog/ansible-community-day-berlin-2023 - https://forum.ansible.com/pub/acd2023-berlin-agenda ## Key Points Key points about the Ansible Community Day in Berlin 2023: 1. **Purpose**: The primary aim of the Ansible Community Day is to bring together individuals who are involved with Ansible in various capacities. It complements the Ansible Contributor Summit, emphasizing the importance of Ansible users from all backgrounds and roles. 2. **Other Events**: This event follows the success of previous Ansible Community Day events in Pune, India, and Boston, USA, earlier in the year. These events provided valuable opportunities for the community to meet in person, share knowledge, and learn more about Ansible. 3. **Location and Date**: The Ansible Community Day Berlin 2023 will take place in Berlin, Germany, on **September 20, 2023**. The venue for the event is **c-base**, located at **Rungestraße 20, Berlin**. 4. **Agenda**: The event promises a variety of activities and sessions, including: A Conclusion of Ansible community announcements and upd... --- ## JSON Data Search with Ansible URL: https://www.ansiblebyexample.com/articles/json-data-search-with-ansible Description: Discover how to automate data filtering using Ansible with a practical example of finding band members in a list. Perfect for beginners. ## Introduction Ansible is a powerful tool used for automation and configuration management. While it is commonly associated with tasks like server provisioning and application deployment, its flexibility allows it to be used for a wide variety of tasks, even something as simple as searching for a specific band member in a list of bands. In this article, we'll create an Ansible playbook that searches for bands formed with a member named "Starr" and outputs the result. ## Disclaimer Full example: https://www.redhat.com/sysadmin/ansible-jinja-lists-dictionaries ### The Playbook Below is the Ansible playbook designed for this task. It includes a list of bands, each with its members, formation year, and the decade they were most active. The playbook filters through this list to find any band that has a member named "Starr." [code example] ### Explanation of the Code - **Playbook Structure**: - The playbook targets the `localhost` and does not gather facts, as this is a simple data-processing task. - **Variables Section**: - The `bands` variable is defined as a list containing information about several bands, including their names, members, formation year, and the decade they were active. - **Task**: - A single task is defined that uses the `ansible.builtin.debug` module to filter through the `bands` list and find any band with a member named "Starr." - The filtering is done using Jinja2 templating with the `selectattr` filter, which searches for "Starr" within... --- ## Knee: The Ansible-Powered CLI for Seamless Infrastructure Automation URL: https://www.ansiblebyexample.com/articles/knee-the-ansible-powered-cli-for-seamless-infrastructure-automation Description: Unlocking Efficiency in IT Infrastructure: Automate with Knee and Ansible. With clear, copy-paste, step-by-step examples. ## Introduction In today's fast-paced tech environment, repetitive tasks like software installations and system configurations are not just time-consuming but also prone to errors, leading to inefficiencies and operational delays. Enter **Knee**, a cutting-edge CLI tool that leverages the robust capabilities of Ansible to automate these mundane tasks, thereby enhancing efficiency and reducing human error. ### Overview of Knee Knee is an innovative open-source command-line interface (CLI) built atop Ansible, designed to streamline and simplify infrastructure setup. By automating the repetitive tasks involved in setting up systems, Knee allows IT professionals to focus on more strategic tasks that add value to the business. **GitHub Repository:** Visit Repo **Documentation:** Read the Docs ### How Knee Works Knee transforms infrastructure setup through a four-step process, integrating user inputs with powerful Ansible playbooks. Here’s a closer look at how it functions: 1. **Component Selection:** Users begin by selecting the required components like web servers, databases, and caching tools. Knee offers a curated list to choose from, simplifying the selection process. 2. **Provide Configurations:** Post selection, Knee prompts users to input detailed configuration settings such as software versions and database configurations. These inputs form the blueprint for the installation process. 3. **Ansible Integration:** Utilizing Ansible’s Infrastructure as Code (IaC) c... --- ## KubeCon 2025 Early Bird Tickets URL: https://www.ansiblebyexample.com/articles/kubecon-2025-early-bird-tickets Description: Today is your last chance to grab Early Bird tickets for KubeCon + CloudNativeCon Europe London 2025! With clear, copy-paste, step-by-step examples. 🌟 **Attention Kubernetes Enthusiasts! Save up to $500 Today!** 🌟 The countdown is on! Today marks your **final chance** to snag **Early Bird tickets** for the **KubeCon + CloudNativeCon Europe 2025** event in London! This must-attend conference will bring together thousands of Kubernetes and cloud-native professionals to shape the future of technology. Don't miss your opportunity to attend at the best rates available. ### 📅 **Early Bird Deadline** **December 17, 2024, 23:59 GMT** ### 💰 **Ticket Savings Breakdown** Secure your pass today and lock in these **huge savings** compared to the **Standard rates** that start tomorrow: - **Corporate Pass:** $999 (Save $500 off Standard at $1,499!) - **Individual Pass:** $399 (Save $280 off Standard at $679!) - **Academic Pass:** $200 (Flat rate, always affordable!) ### **Why Attend KubeCon + CloudNativeCon Europe?** This conference is the **premier event for cloud-native practitioners**, and here’s why it’s unmissable: ✅ **Cutting-Edge Insights:** Learn from top experts and innovators in Kubernetes, DevOps, and cloud-native technologies. ✅ **Unparalleled Networking Opportunities:** Meet leaders in cloud-native development, operations, and security. ✅ **Exclusive Co-Located Events:** Access CNCF-hosted sessions (with an All-Access Pass) like EnvoyCon, Istio Day, and more. ✅ **Training Discounts & Workshops:** Take advantage of exclusive attendee offers on training and certifications to further your ex... --- ## KubeCon and CloudNativeCon Europe 2024 Call For Proposals URL: https://www.ansiblebyexample.com/articles/kubecon-and-cloudnativecon-europe-2024-call-for-proposals Description: Hurry up for Call For Proposals (CFP) until November 26, 2023, Navigating the Cloud-Native Future: KubeCon + CloudNativeCon Europe 2024 in Paris 19-24. ## Introduction The Cloud Native Computing Foundation (CNCF) is set to host its flagship conference, KubeCon + CloudNativeCon, in the picturesque city of Paris, France, from March 19 to 22, 2024. This event serves as a melting pot for adopters and technologists from leading open source and cloud-native communities. The gathering is expected to attract professionals eager to delve into the latest trends, developments, and innovations in cloud-native computing. ## Conclusionping KubeCon + CloudNativeCon Europe 2023 To understand the significance of the upcoming event, it's worthwhile to revisit the success of KubeCon + CloudNativeCon Europe 2023 held in Amsterdam. The conference brought together a diverse array of participants, fostering collaboration and knowledge exchange. The event showcased a broad spectrum of topics, including keynotes, breakouts, and a vibrant Solutions Showcase. Attendees had the chance to explore the Amsterdam experience through the eyes of industry experts and practitioners, gaining valuable insights into the rapidly evolving cloud-native landscape. ## What to Expect in Paris 2024 The upcoming conference promises an even more enriching experience. The schedule at a glance reveals an impressive lineup of activities, including pre-event programming, keynotes, breakouts, and the ever-popular KubeCrawl + CloudNativeFest. With a focus on education and advancement, the event aims to cater to the needs of both seasoned professionals and those new to the clo... --- ## Kubernetes CoreDNS and ExternalDNS URL: https://www.ansiblebyexample.com/articles/coredns-vs-externaldns Description: Explore the roles of CoreDNS and ExternalDNS in Kubernetes, their functions, and how they work together to manage internal and external DNS. ## Introduction CoreDNS and ExternalDNS are two essential components commonly used in Kubernetes clusters for DNS management. They serve different purposes but can work together to provide a seamless DNS experience in a Kubernetes environment. Here's an overview of each and how they can be used together: ## CoreDNS **CoreDNS** is the default DNS server for Kubernetes. It is responsible for service discovery within the cluster. CoreDNS translates Kubernetes Service names into IP addresses, allowing pods to communicate with each other using service names. ### Key Functions of CoreDNS: - **Service Discovery:** Resolves internal Kubernetes service names to their corresponding ClusterIP. - **Pod DNS:** Resolves pod names to their IP addresses within the cluster. - **Custom DNS Configuration:** Can be configured to forward DNS queries to external DNS servers or provide custom DNS zones. **CoreDNS Configuration Example:** The CoreDNS configuration is typically found in the `ConfigMap` associated with the `kube-system` namespace. Here's an example of a CoreDNS `Corefile`: [code example] ## ExternalDNS **ExternalDNS** is a Kubernetes add-on that synchronizes Kubernetes service and ingress resources with external DNS providers. While CoreDNS handles internal DNS resolution, ExternalDNS manages DNS entries with external DNS providers like AWS Route 53, Google Cloud DNS, or Azure DNS. ### Key Functions of ExternalDNS: - **Automatic DNS Record Management:** Creates, updates, or ... --- ## kubernetes.core 6.5.0 - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/kubernetes-core-6-5-0-whats-new-and-how-to-test Description: kubernetes.core 6.5.0 adds Helm v4 compatibility, a kubeconfig remove behavior, and fixes helm, helm_repository, k8s_drain, and EE build bugs. # kubernetes.core 6.5.0 - Whats New and How to Test ## Introduction `kubernetes.core` is the Ansible collection that provides the modules and plugins used to manage Kubernetes and OpenShift resources from playbooks, including `k8s`, `helm`, `k8s_drain`, and kubeconfig management modules. Version 6.5.0 has just been published on Ansible Galaxy and brings Helm v4 compatibility across the Helm-related modules along with a set of targeted bug fixes. ## Whats New ### Release Summary According to the collection's own changelog, this release "implements minor changes and bug fixes such as a new `remove` value to the `behavior` option of the `kubeconfig` module, allowing entries to be deleted from the kubeconfig file by name, as well as Helm v4 compatibility across the Helm modules." ### Minor Changes - `helm` - adds the `server_side` and `force_conflicts` options to control Helm v4 server-side apply when installing or upgrading a release (PR #1164). - `helm_plugin` - adds a `--keyring` argument to allow changing the keyring default location. The option is only accepted with `state=present` (the `helm plugin install` subcommand), since that is the only implemented subcommand supporting `--keyring` (PR #1150). - `helm_registry_auth` - documents that, as of Helm 4.2.1, registry success messages such as `Login Succeeded` are printed to stdout instead of stderr (PR #1147). - `kubeconfig` - adds the `remove` value to the `behavior` option, allowing entries to be deleted from the ku... --- ## kubernetes.core 6.6.0 Released - Whats New and How to Test URL: https://www.ansiblebyexample.com/articles/kubernetes-core-6-6-0-released-whats-new-and-how-to-test Description: kubernetes.core 6.6.0 adds helm wait_for_jobs and cleanup_on_fail options, k8s_cp streaming copy, k8s_info metadata-only fetches, and more. # kubernetes.core 6.6.0 Released - Whats New and How to Test ## Introduction The `kubernetes.core` collection is the official Ansible collection for interacting with Kubernetes clusters, providing modules such as `k8s`, `k8s_info`, `k8s_cp`, `helm`, `helm_info`, and related lookup and inventory plugins. It is maintained by the Ansible Cloud team and is one of the dependencies pulled in by the `ansible` community package. Version 6.6.0 has just been published on Ansible Galaxy, replacing 6.5.0. This release is not a pure bugfix drop: it ships a number of minor feature additions across the `helm`, `k8s_cp`, `k8s_info`, and `k8s` lookup/waiter code paths, plus several deprecation notices that collection users should be aware of ahead of future major releases. ## Whats New ### Helm module improvements - `helm` gains a new `wait_for_jobs` option, which waits for all Jobs to complete before marking a Helm release as successful. This requires Helm >= 3.5.0 (PR #1140). - `helm` gains a new `cleanup_on_fail` option, mapping to the `--cleanup-on-fail` Helm flag, allowing deletion of new resources created during a failed upgrade. It complements `atomic` and can be combined with it, but not with `replace`, since `replace` deploys via `helm install`, which does not accept that flag (PR #1206). - `helm` now warns when `reuse_values` or `reset_then_reuse_values` is requested in a combination that Helm silently ignores. This happens by default because `reset_values` defaults to `true`,... --- ## Latest Ansible Job Opportunities: Remote & Global Roles URL: https://www.ansiblebyexample.com/articles/ansible-job-board Description: Discover the latest Ansible-specific job opportunities worldwide. Find remote and on-site roles for automation consultants, developers, and more. ## Some Ansible-Specific Job Opportunities This job board lists the latest Ansible-specific job opportunities worldwide. In the post-pandemic world, many organizations have realized the cornerstone importance of successful automation in their business. Feel free to follow up with the contacts directly to request more information. Job descriptions are provided by third parties, and the Ansible Pilot Community doesn't have any responsibility for inaccurate or non-specific details. ### Available Positions - **Ady Gamre** - **Role:** Ansible Automation Consultant (Permanent) - **Location:** Europe (Remote) - **Contact:** gamre@silverlinktechnologies.com - **Srikanth V.** - **Role:** Ansible Automation (Permanent) - **Location:** Prague, Czech Republic - **Contact:** +44 203 887 1710 Ext:7020, srikanth.sv@avanceservices.uk - **Pooja B.** - **Role:** Ansible Automation Consultant (Full Time Permanent) - **Location:** HCL Technologies, 100% Remote in Czech Republic - **Contact:** barik@silverlinktechnologies.com - **Mahesh (Maya) Yanagunde** - **Role:** Ansible Tower Consultant (Permanent Role) - **Location:** HCL for Prague, Czech Republic (Remote Work) - **Contact:** mahesh@silverlinktechnologies.com - **Iryna Hlushko** - **Role:** Ansible Automation Specialist - **Location:** IT Industry, Digital Services Consulting - **Details:** Job Description - **Michal Titl** - **Role:** DevOps Opportunity at Systek - **Location:** Public Transport I... --- ## Latest Articles URL: https://www.ansiblebyexample.com/articles/-index --- ## Learn Ansible book technical review by Luca Berton URL: https://www.ansiblebyexample.com/articles/learn-ansible Description: Second Edition: Automate your cloud infrastructure, security configuration, and application deployment. Tested, copy-paste examples included. ## Introduction Learn how to write and run Ansible Playbooks, from the basics to launching complex multi-tier applications across public cloud platforms such as Amazon Web Services (AWS) and Microsoft Azure. [](https://amzn.to/4bH35xz) {{}} ## Key Features - Write roles to automate everything, from basic apps to the entire cloud infrastructure - Leverage Ansible's module ecosystem to streamline tasks across cloud platforms, operating systems, and apps - Adopt DevOps practices and integrate Ansible with CI/CD platforms to streamline automation workflows ## Book Description Are you tired of manually deploying and managing your infrastructure and looking for ways to streamline your deployments, introduce consistency and collaboration, and save time? If so, then Learn Ansible is for you. Written by a DevOps practitioner and system administrator with 30] years of experience, this book will teach you how to automate repetitive tasks and effortlessly manage several resources from a single code base. From installing Ansible and writing your first playbook to deploying multi-tier applications across different cloud platforms, this book will take you on an exciting learning journey. By learning the art of defining highly available cloud infrastructure using code, you'll find it easy to distribute configurations alongside your application. You'll explore Ansible Galaxy, learn about community-contributed Ansible roles, and discover how to create and share your own roles. Later, th... --- ## Leveraging Ansible Callback Plugins for Enhanced Performance URL: https://www.ansiblebyexample.com/articles/leveraging-ansible-callback-plugins-for-enhanced-performance Description: Profiling, Troubleshooting, and Optimizing Resources in Ansible Automation with timer, profile_tasks, and profile_roles Callback Plugins ## Introduction Ansible is a powerful open-source automation tool used for configuration management, application deployment, and task automation. To harness the full potential of Ansible, it’s essential to fine-tune its configuration according to your specific needs. In this article, we’ll delve into the `ansible.cfg` file and explore how to optimize Ansible’s performance by utilizing callback plugins. Specifically, we will focus on the `[defaults]` section of the `ansible.cfg` file and the configuration options `callback_whitelist` and `callbacks_enabled`. ## Understanding Callback Plugins Callback plugins in Ansible are used to customize the output of playbooks and provide additional functionality during playbook execution. They can be configured globally in the `ansible.cfg` file or per-playbook using the `ansible.cfg` setting in a playbook. Callback plugins offer a wide range of capabilities, from generating custom reports to monitoring playbook execution time. ### The ansible.cfg File The Ansible.cfg file is a central configuration file that governs Ansible’s behavior. It is typically located in the `/etc/ansible/` directory for system-wide configurations or in the project directory for playbook-specific configurations. To modify Ansible’s behavior, you can edit this file to include various settings related to callback plugins. ### Configuring Callback Plugins in ansible.cfg Within the `ansible.cfg` file, configuration settings for callback plugins are placed in the `... --- ## Leveraging Ansible for Time Savings and Reduced Human Error in Multi-Cloud Environments URL: https://www.ansiblebyexample.com/articles/leveraging-ansible-for-time-savings-and-reduced-human-error-in-multi-cloud-environments Description: Streamlining Multi-Cloud Automation with Ansible: Time Savings and Error Reduction. Tested, copy-paste examples included. ## Introduction In today’s fast-paced and complex IT landscape, organizations face the challenge of managing diverse cloud environments efficiently while minimizing human errors. This is where Ansible, a powerful automation tool, comes into play. By connecting private and public cloud providers, Ansible simplifies infrastructure management, saves time, and reduces the risk of human error. This article will explore the domains where Ansible excels, its benefits, and its role in orchestrating, operationalizing, and governing cloud resources. ## Domains: Public Cloud, Cloud-Native, and Private Cloud Ansible acts as the glue that seamlessly connects private and cloud providers across domains like public cloud (e.g., AWS, Azure, Google Cloud), cloud-native platforms such as Openshift and Kubernetes, and private cloud solutions like OpenStack, VMware, and Nutanix. ### Time Savings and Reduced Human Error Ansible’s value proposition lies in its ability to automate repetitive tasks, freeing up IT staff for more strategic endeavors. By automating tasks such as infrastructure deployment and retirement, patch management, cloud operations, and troubleshooting, Ansible significantly reduces human error and accelerates time-to-value. ### Orchestrate, Operationalize, and Govern Ansible serves as a comprehensive solution for orchestrating, operationalizing, and governing cloud resources, ensuring seamless management across various aspects. 1. Orchestrate: - Deployment and retirement: Ans... --- ## Leveraging Poetry for Efficient Virtual Environment Management URL: https://www.ansiblebyexample.com/articles/leveraging-poetry-for-efficient-virtual-environment-management Description: Unveiling the Verses: Navigating Virtual Environments with Poetry and Ansible. Tested on real machines with clear, copy-paste examples. ## Leveraging Poetry for Efficient Virtual Environment Management In the ever-evolving landscape of software development, managing dependencies and creating a controlled environment for project execution is crucial. Python developers often find themselves juggling with virtual environments to isolate project dependencies, ensuring consistency and reproducibility across different setups. While there are several tools available for this task, one standout option that combines simplicity with power is Poetry. ## Understanding Poetry Poetry is not just a literary form; it's also a Python packaging and dependency management tool. It streamlines the process of defining and installing project dependencies, making the management of virtual environments a seamless experience. To embark on this journey, let's explore how Poetry can be employed for managing a virtual environment, taking Ansible as a case study. ### Setting the Stage Firstly, create a directory for your project and navigate into it: [code example] Next, initiate a Poetry project within the directory: [code example] This command will prompt you to provide details about your project, such as its name, version, and dependencies. [code example] ### Adding Dependencies With the project initialized, add Ansible to the list of dependencies using the `poetry add` command: [code example] Poetry will handle the installation of Ansible and any additional dependencies required. [code example] ### Verifying the Instal... --- ## Linting Ansible Playbooks: A Guide to Ensuring Consistency and Quality URL: https://www.ansiblebyexample.com/articles/linting-ansible-playbooks-a-guide-to-ensuring-consistency-and-quality Description: Ensure Ansible playbook quality and consistency with linting. Learn to avoid issues like using the Ansible best practices for reliable deployments. ## Introduction If you’re involved in managing infrastructure, you probably already know the power and flexibility of Ansible, an open-source configuration management tool. Ansible allows you to automate the configuration of one or many machines, ensuring that tasks are performed consistently, whether you’re provisioning virtual machines, installing applications, or applying updates. But how can you be sure your Ansible playbooks are free from errors and follow best practices? That’s where linting comes into play. ### What is Ansible? Ansible is a widely-used configuration management software that simplifies automation tasks for IT professionals and system administrators. With Ansible, you can define tasks in YAML files called playbooks. These tasks can include setting up servers, installing software, creating users, and much more. The real power of Ansible lies in its ability to perform these tasks consistently across multiple machines, making it a crucial tool in the world of infrastructure management. ### Why Lint Ansible? Ansible playbooks are written in YAML, a human-readable data serialization format. While YAML is user-friendly, it is strict about syntax, indentation, and formatting. Linting helps you ensure that your Ansible playbooks adhere to these YAML standards, making your code more readable and less prone to errors. Linting also checks for issues beyond just syntax. It enforces best practices, catches deprecated features, and identifies potential security vu... --- ## List VMware Datastore Tags with Ansible URL: https://www.ansiblebyexample.com/articles/list-tags-in-vmware-datastore-using-ansible Description: Retrieve and manage VMware datastore tags using Ansible's community.vmware collection. Complete guide with vmware_datastore_info, tag filtering,. ## Introduction VMware tags organize vSphere resources — datastores, VMs, hosts, networks — into categories for management, policy enforcement, and reporting. Using Ansible's `community.vmware` collection, you can programmatically retrieve datastore information including tags, capacity, and usage across your entire vSphere environment. ## Prerequisites ### Install the VMware Collection [code example] ### Python Dependencies [code example] ### vCenter Credentials Store credentials securely with Ansible Vault: [code example] [code example] ## Basic: List Datastore Tags [code example] ## Filter by Datacenter or Cluster [code example] ## Filter Datastores by Tag [code example] ## Capacity Report [code example] ## Manage Tags with Ansible ### List All Tag Categories [code example] ### Create and Assign Tags [code example] ## VMware Module Reference | Module | Purpose | |--------|---------| | `vmware_datastore_info` | Get datastore details + tags | | `vmware_tag` | Create/delete tags | | `vmware_tag_manager` | Assign/remove tags from objects | | `vmware_category` | Manage tag categories | | `vmware_category_info` | List tag categories | | `vmware_datastore_cluster` | Manage datastore clusters | | `vmware_host_datastore` | Mount/unmount datastores on hosts | ## Related Articles - Ansible Best Practices Guide - Ansible Vault: Encrypt Sensitive Data - Ansible Roles Explained ## Conclusion The `vmware_datastore_info` module retrieves comprehensive datastore... --- ## Luca Berton & Erez Kirson: AI, Mentorship, and Innovation Insights URL: https://www.ansiblebyexample.com/articles/luca-berton-erez-kirson-on-ai-mentorship-and-the-future-of-innovation Description: Discover insights on AI, mentorship, and the future of technology with Luca Berton and Erez Kirson. Tune in for inspiring discussions on innovation. Join Luca Berton and Erez Kirson for an engaging exploration into the world of technology, AI, and the power of community in our latest video podcast. Dive deep into their personal journeys from early curiosity to influential tech careers, and discover their unique insights on the future of innovation. In this episode, Luca and Erez discuss their passion for technology and open source, the importance of continuous learning, and the rising influence of AI in our lives. They share stories of mentorship, the significance of community support, and their vision for a future where technology and personal robotics seamlessly integrate into our daily lives. Whether you’re a seasoned tech enthusiast or just starting out, there’s something in this podcast for everyone. From discussions on the miniaturization of technology to the role of humans in AI decision-making, Luca and Erez provide a comprehensive outlook on what’s next in tech. Timestamps: 00:00 Introduction and Connection 01:08 Passion for Technology and Open Source 03:01 Early Start and Curiosity 05:34 From Commodore to Technology Career 07:14 The Importance of Continuous Learning 09:24 The Fascination with Technology 10:47 Envision the Future of Technology 14:10 The Value of Community and Mentorship 15:35 The Power of Sharing and Mentoring 19:06 Acquiring New Knowledge and Asking Questions 21:47 The Rise of AI and Generative AI 23:24 The Future of AI and Technology 25:39 The Importance of Data and AI Use Cases... --- ## Manage Ansible Collection Changelogs with Antsibull-Changelog URL: https://www.ansiblebyexample.com/articles/ansible-collection-changelog-with-antsibull-changelog Description: Learn how to use Antsibull-Changelog to efficiently manage and document updates in your Ansible collections. Follow this guide to keep your changelogs. ## Introduction Keeping track of changes in your Ansible collection is essential for maintaining transparency and informing users about updates, enhancements, and bug fixes. `antsibull-changelog` is a powerful tool that streamlines the process of managing changelogs. In this article, we’ll guide you through the steps of setting up and utilizing `antsibull-changelog` for your Ansible collection. ## Installation The first step is to install `antsibull-changelog`. Open your terminal and execute the following command: [code example] ## Initialization After installing `antsibull-changelog`, navigate to the root directory of your Ansible collection and initialize it: [code example] This command sets up the necessary directory structure and configuration files to manage changelogs effectively. Linting Ensure your changelog adheres to the required format by running the linting command: [code example] The linting process helps identify and rectify any issues in your changelog. ## Adding Changelog Fragment Create a new file in the `changelogs/fragments` directory, such as `1.0.0.yaml`. Populate this file with details about the changes made in your collection. Use the following template: [code example] Replace the content within the backticks with your collection name, release date, and a brief summary of the changes. ## Releasing a New Version After adding the changelog fragment, it’s time to release the new version of your Ansible collection: [code example] This comm... --- ## Manage Disk Space by Cleaning /var/log/journal on Fedora URL: https://www.ansiblebyexample.com/articles/managing-journal-logs-in-fedora Description: Free disk space by managing systemd journal logs on Fedora and RHEL. Configure journald.conf size limits, vacuum old logs, automate cleanup with Ansible,. ## Introduction The `/var/log/journal` directory stores persistent systemd journal logs. On long-running Fedora, RHEL, or CentOS systems, these logs can grow to several gigabytes. This guide covers how to check journal size, clean up old entries, configure permanent size limits, and automate the process with Ansible. ## Check Current Journal Size [code example] ### Detailed Breakdown [code example] ## Method 1: Vacuum by Size Remove old logs until total size is under the threshold: [code example] ## Method 2: Vacuum by Time Remove logs older than a specified period: [code example] ## Method 3: Vacuum by Number of Files [code example] ## Configure Permanent Size Limits Edit `/etc/systemd/journald.conf`: [code example] Apply changes: [code example] ### Key Parameters | Parameter | Description | Example | |-----------|-------------|---------| | `SystemMaxUse` | Max total journal size | `500M`, `1G` | | `SystemMaxFileSize` | Max individual file size | `50M` | | `SystemKeepFree` | Min free space to maintain | `1G` | | `MaxRetentionSec` | Max age of entries | `30day`, `1week` | | `RuntimeMaxUse` | Max size for volatile (`/run`) journals | `100M` | | `SystemMaxFiles` | Max number of journal files | `10` | ## Force Log Rotation Trigger immediate rotation without waiting: [code example] Verify: [code example] ## Automate with Ansible ### One-Time Cleanup [code example] ### Configure Permanent Limits [code example] ### Scheduled Cleanup with Cron [code e... --- ## Managing ABRT Debug Files: Fedora Disk Space Guide URL: https://www.ansiblebyexample.com/articles/managing-abrt-debug-files Description: Fine-Tuning Fedora: A Guide to Efficiently Managing ABRT Debug Files. Tested on real machines with clear, copy-paste examples. ## Introduction Fedora, like many Linux distributions, employs the Automatic Bug Reporting Tool (ABRT) to capture and analyze application crashes on the system. Over time, the /var/cache/abrt-di/usr directory can accumulate a substantial number of files, causing the system to run low on disk space. In this article, we'll explore whether it's safe to remove files in this directory and how to manage the space efficiently. ## Understanding /var/cache/abrt-di/usr The `/var/cache/abrt-di/usr` directory contains debug information and associated files collected by ABRT. While these files are crucial for diagnosing and fixing application crashes, they can become a burden on your system's storage, especially if left unchecked. Fortunately, it is generally safe to clean up these files, but certain precautions should be taken. ## Cleaning Up /var/cache/abrt-di/usr To free up space on your Fedora system, you can safely remove files in the `/var/cache/abrt-di/usr` directory. However, it's essential to ensure that you're not deleting critical information needed for debugging. Before proceeding with the cleanup, consider the following steps: 1\. Check Max Size Configurations: Review the maximum crash report size specified in `/etc/abrt/abrt.conf`: [code example] This setting controls the overall size of crash reports and helps prevent the directory from growing uncontrollably. 2\. Adjust DebugInfoCacheMB: Examine the DebugInfoCacheMB configuration in `/etc/abrt/plugins/CCpp.conf`:... --- ## Managing Ansible Automation Platform Credentials at Scale with HashiCorp Vault URL: https://www.ansiblebyexample.com/articles/managing-ansible-automation-platform-credentials-hashicorp-vault Description: Integrate HashiCorp Vault with Ansible Automation Platform for credentials at scale. Configure dynamic secret lookups, token renewal, and custom EE support. ## Introduction Managing credentials across hundreds of playbooks and thousands of hosts is one of the hardest problems in enterprise automation. Hardcoded passwords, shared service accounts, and static API keys create security risks that grow with every new automation workflow. HashiCorp Vault solves this by providing centralized, audited, and dynamic secret management — and Ansible Automation Platform (AAP) has native integration to pull credentials from Vault at runtime. This guide covers the full integration: configuring Vault for Ansible, setting up AAP external credential lookups, using dynamic database credentials, and implementing enterprise patterns for credential rotation at scale. ## Why Vault + AAP | Challenge | Without Vault | With Vault | |-----------|--------------|------------| | Secret storage | Ansible Vault files in Git | Centralized, encrypted, API-driven | | Credential rotation | Manual, error-prone | Automatic, policy-driven | | Audit trail | Git blame (who committed) | Full API access logs | | Dynamic secrets | Not possible | Database, cloud, SSH creds on demand | | Access control | File permissions | Fine-grained policies per team/project | | Secret sprawl | Copies in multiple repos | Single source of truth | ## Architecture Overview [code example] ## Prerequisites | Component | Version | Purpose | |-----------|---------|---------| | AAP Controller | 2.4+ | External credential plugin support | | HashiCorp Vault | 1.12+ | Secrets engine | | Vaul... --- ## Managing Virtual Environments with Pipenv for Ansible Projects URL: https://www.ansiblebyexample.com/articles/managing-virtual-environments-with-pipenv-for-ansible-projects Description: Set up isolated Python environments for Ansible with Pipenv. Install Ansible in a virtual environment, manage dependencies with Pipfile, compare Pipenv vs. ## Introduction Running Ansible in a Python virtual environment keeps your system Python clean and lets you pin exact versions of Ansible, collections, and Python dependencies per project. Pipenv combines `pip` + `virtualenv` into a single workflow with lockfiles for reproducible builds. ## Why Virtual Environments for Ansible? | Problem | Virtual Env Solution | |---------|---------------------| | System Ansible conflicts with pip packages | Isolated Python environment | | Different projects need different Ansible versions | Separate venv per project | | "Works on my machine" issues | Lockfile ensures identical deps | | CI/CD needs reproducible installs | `Pipfile.lock` deterministic builds | ## Quick Start ### Install Pipenv [code example] ### Create an Ansible Project [code example] ### Activate the Environment [code example] ### Run Without Activating [code example] ## Understanding Pipfile [code example] ### Version Pinning [code example] ## Pipfile.lock — Reproducible Builds [code example] ## Common Workflows ### Add a New Dependency [code example] ### Update Dependencies [code example] ### Show Dependency Tree [code example] ## Pipenv vs venv vs conda | Feature | Pipenv | venv + pip | conda | |---------|--------|-----------|-------| | Lockfile | ✅ Pipfile.lock | ❌ (use pip freeze) | ✅ environment.yml | | Auto-creates venv | ✅ | ❌ Manual | ✅ | | Security audit | ✅ `pipenv check` | ❌ | ❌ | | Dependency resolution | ✅ Advanced | Basic | ✅ Advance... --- ## Master Ansible Automation for Docker, Podman, and Kubernetes URL: https://www.ansiblebyexample.com/articles/ansible-for-containers-by-examples Description: Automate Docker, Podman, and Kubernetes with Ansible. Complete guide covering container modules, image management, Kubernetes resources, and production. ## Introduction Containers have transformed how we build, ship, and run applications. Ansible brings Infrastructure as Code to container management — automating image builds, container lifecycles, Kubernetes deployments, and multi-environment orchestration from a single playbook. This guide covers the essential Ansible modules for Docker, Podman, and Kubernetes with practical examples for each platform. ## Docker Automation with Ansible ### Install Docker with Ansible [code example] ### Manage Docker Images [code example] ### Run Docker Containers [code example] ### Docker Compose with Ansible [code example] ### Docker Network and Volume Management [code example] ## Podman Automation with Ansible Podman is the rootless, daemonless alternative to Docker. Ansible supports it through the `containers.podman` collection: [code example] ### Run Podman Containers [code example] ### Podman Image Management [code example] ### Generate systemd Units from Podman [code example] ## Kubernetes Automation with Ansible ### Install the Collection [code example] ### Create Kubernetes Resources [code example] ### Apply YAML Files [code example] ### Wait for Deployment [code example] ## Container Module Quick Reference | Task | Docker Module | Podman Module | Kubernetes Module | |------|--------------|---------------|-------------------| | Run container | `docker_container` | `podman_container` | `k8s` (Pod/Deployment) | | Manage images | `docker_image` | `podman... --- ## Master Ansible Automation: Comprehensive Guide for IT Pros URL: https://www.ansiblebyexample.com/articles/ansible-automation-platform-mastery-unleash-the-power-of-enterprise-automation Description: Embark on a journey to master Ansible Automation Platform. Explore tutorials, best practices, and advanced techniques to automate IT infrastructure. 🚀 Embark on a transformative journey into the world of automation with our comprehensive "Ansible Automation Platform Mastery"! 🌐 Whether you're a seasoned IT professional or just taking your first steps with Ansible, this curated collection of tutorials covers everything you need to know about harnessing the full power of Ansible for efficient and scalable automation. 🛠️ Playbooks 101: Lay a solid foundation with in-depth tutorials covering the basics of Ansible playbooks. Master the art of crafting efficient automation scripts for streamlined workflows. 🔧 Inventory Management Strategies: Dive deep into Ansible's inventory management capabilities. Explore strategies for organizing and maintaining inventories to suit diverse IT environments. 🚦 Ansible Tower Essentials: Unlock the advanced capabilities of Ansible Tower with comprehensive tutorials. Learn how Ansible Tower elevates your automation game with its intuitive web interface and advanced features. 🌐 Scaling and Orchestrating Complex Infrastructures: Explore advanced topics on orchestrating complex IT infrastructures with Ansible. Dive into strategies for managing large-scale deployments and orchestrating tasks across diverse environments. 🔄 Security Best Practices: Master Ansible security best practices to ensure the integrity of your automation workflows. Explore techniques for securing sensitive data, managing credentials, and ensuring compliance. 📊 Monitoring and Optimization Strategies: Gain insights... --- ## Master Ansible Magic Variables: A Practical Playbook Guide URL: https://www.ansiblebyexample.com/articles/ansible-magic-variables-ansible-tip-and-tricks Description: Discover how to use Ansible Magic Variables in your playbooks. Follow a live Playbook, explore key variables, and see practical examples for efficient. ## How to Use Ansible Magic Variables in Ansible Playbook ## Ansible Magic Variables How to Ansible Magic Variables in Ansible Playbook. The good news is that Ansible provides some internal variables that come out of the box with some information such as running the Ansible version, inventory details, or execution options. Some examples: - `playbook_dir` The path to the directory of the playbook that was passed to the ansible-playbook command line - `inventory_dir` The directory of the inventory source in which the inventory_hostname was first defined - `inventory_file` The file name of the inventory source in which the inventory_hostname was first defined - `inventory_hostname` The inventory name for the 'current' host is being iterated over in the play - `ansible_check_mode` / `ansible_diff_mode` Boolean that indicates if we are in check/diff mode or not - `ansible_version` Dictionary/map that contains information about the currently running version of ansible, it has the following keys: full, major, minor, revision and string. ## Links The full list is available on the official Ansible website Magic variables ## Playbook How to use Ansible Magic Variables in Ansible Playbook? Let's see in action some of the most common Ansible Magic Variables in an Ansible Playbook. I'm going to display the current value of the following variables: - `ansible_config_file` The full path of the used Ansible configuration file playbook_dir The path to the directory of the p... --- ## Master SQL with Microsoft Management Studio (SSMS) and Ansible URL: https://www.ansiblebyexample.com/articles/master-sql-with-microsoft-management-studio-ssms-guide Description: Explore Microsoft Management Studio (SSMS) for SQL Server. Discover its features, benefits, installation steps, and tips for efficient database management. Microsoft Management Studio (SSMS) is a comprehensive, integrated environment for managing SQL Server databases and infrastructure. Paired with **Ansible automation**, SSMS becomes an even more powerful tool for automating database administration, configuration, and management tasks. --- ## What is Microsoft Management Studio (SSMS)? SSMS is a powerful tool from Microsoft that provides a unified interface for managing SQL Server databases. It includes tools for: - **Database Management**: Create, modify, and query databases. - **Server Management**: Configure, monitor, and administer SQL Server instances. - **Advanced Development**: Support for T-SQL, Stored Procedures, and other database development tasks. With **Ansible**, you can automate routine SSMS-related tasks, such as managing SQL queries, scheduling backups, or creating databases. --- ## Key Features of SSMS 1. **Comprehensive Interface**: - Easy-to-navigate GUI for database and server management. 2. **Integrated Query Editor**: - Write and execute SQL queries with syntax highlighting and debugging. 3. **Backup and Restore**: - Schedule and execute backup operations with ease. 4. **Performance Tuning**: - Monitor and optimize query performance using advanced tools. 5. **Azure Integration**: - Manage Azure SQL Databases and SQL Managed Instances directly. 6. **Automation with Ansible**: - Use playbooks to schedule recurring tasks or deploy configuration changes at scale. --- ## Why Use SSMS w... --- ## Mastering Ansible Command: Ad-Hoc Tasks and System Management URL: https://www.ansiblebyexample.com/articles/ansible-ad-hoc-command-ansible-command Description: Explore the basics of the Ansible command, including how to run ad-hoc tasks, execute modules, and retrieve system facts. Perfect for beginners. ## What does the ansible command? I’m going to show you a live Playbook. ## ansible command - Included in Ansible installation - command line - Ansible ad-hoc The `ansible` command is probably the first helpful command to learn when you start your journey with Ansible. It is included in every Ansible installation for the most modern operating system. It relies on Python language and some libraries such as Jinja2, YAML, WinRM, etc. It is a command line tool so interact with that using your terminal. Using the `ansible` command, you could perform some operation to your target node(s), for example, executing single modules or retrieving system information (AKA Ansible Facts). Each command in the Ansible jargon is called a module. Each module has its own parameter for the execution that you could read in the documentation. It is useful when you would like to execute only one module (AKA task) against a limited amount of host(s). The next step in your automation journey will be to use the `ansible-playbook` command with an Ansible Playbook that enables you to execute more tasks against more hosts. ## Links - Introduction to ad hoc commands ## Playbook Let me show you how to execute some Ansible ad-hoc commands via ansible command. I will show you how to use the ping module, run a command and retrieve the Ansible Facts from a target node via the ansible command line. ### ping module You can execute any Ansible module, for example ping , using the following Ansible ad-hoc... --- ## Mastering Ansible Config: Essential Commands and Actions URL: https://www.ansiblebyexample.com/articles/an-in-depth-guide-to-ansible-config-managing-ansible-configuration Description: Discover how to use ansible-config commands to manage Ansible configurations. List, dump, view, and initialize settings efficiently with step-by-step. ## Introduction Ansible is a powerful automation tool used for configuration management, application deployment, and task automation. It simplifies the management of complex infrastructures by allowing users to define tasks in easy-to-understand YAML files. However, to harness its full potential, it’s essential to understand and manage its configuration effectively. This is where the `ansible-config` command comes into play. In this article, we'll explore the `ansible-config` tool, its various actions, and how to use it to manage Ansible's configuration. ## What is `ansible-config`? `ansible-config` is a command-line utility provided by Ansible that allows users to view, manipulate, and manage Ansible's configuration settings. It provides a way to interact with Ansible's configuration files, making it easier to customize and troubleshoot Ansible's behavior. ## Links - https://docs.ansible.com/ansible/latest/cli/ansible-config.html - https://docs.ansible.com/ansible/latest/reference_appendices/config.html ### Configuration Files Ansible looks for configuration files in specific locations; their precedence determines which one is used. Here are the two main configuration files: - `/etc/ansible/ansible.cfg`: This is the system-wide configuration file used if present. It applies to all users. - `~/.ansible.cfg`: This is the user-specific configuration file and takes precedence over the system-wide configuration. It allows users to customize Ansible's behavior for their spec... --- ## Mastering Ansible-Creator: Scaffold Collections and Roles Fast URL: https://www.ansiblebyexample.com/articles/ansible-content-creator-with-ansible-creator Description: Complete guide to ansible-creator — scaffold Ansible collections, roles, and plugins with proper structure. Installation, commands, VS Code integration,. ## Introduction `ansible-creator` is the official scaffolding tool for Ansible content — it generates the directory structure, boilerplate files, and configuration for new collections, roles, and plugins. Instead of manually creating dozens of files and directories, one command gives you a properly structured project ready for development. ## Installation [code example] ### Install with Ansible Dev Tools (Recommended) [code example] ## Create a New Collection ### Basic Initialization [code example] This generates: [code example] ### With Custom Output Path [code example] ### Force Reinitialize [code example] ## Create a Role [code example] Generates standard role structure: [code example] ### Role Inside a Collection [code example] ## Add Plugins to Existing Collection ### Add a Module [code example] ### Add a Filter Plugin [code example] ### Add a Lookup Plugin [code example] ## Command Reference | Command | Description | |---------|-------------| | `init collection ` | Create new collection | | `init role ` | Create new role | | `add plugin module` | Add module to collection | | `add plugin filter` | Add filter plugin | | `add plugin lookup` | Add lookup plugin | | `add plugin action` | Add action plugin | ### Global Options | Option | Description | |--------|-------------| | `--init-path ` | Output directory | | `--force` | Overwrite existing files | | `--no-ansi` | Disable colored output | | `--log-file ` | Write logs to file | | `--log-leve... --- ## Mastering Automation Explore Ansible’s Power with Three Essential Books URL: https://www.ansiblebyexample.com/articles/learn-ansible-with-three-books Description: Learn the Potential of Ansible: Dive into VMware, Kubernetes, and Hands-on Infrastructure Automation. With tested, real-world examples. ## Introduction Hi friends. What an incredible day it is today. I’m so proud to be here holding my books. So this is the effort that I put in place in the last. I would say the last two years to create something tangible and a big contribution to the world. ### Ansible for VMware by Examples [](https://amzn.to/3XHeDLd) {{}} So, I started my day with my journey with Ansible for VMware by examples. Great book published with a great price per value. So proud to be able to publish this book, and I still think that it is a masterpiece, how to use Ansible with VMware so you can automate your snapshot of the deployment of your infrastructure. And this is a cool book because it has a lot of code and examples. I would say that most of the book is actually about the code. As you can see, there are a lot of examples inside as well. Also, some screenshots of expected results in the VMware infrastructure. If you’re familiar with VMware, This looks very useful. This is a great book and was published in December 2022. Yes. I was so proud. This was the best Christmas gift that I can give to my friends. {{}} ### Ansible for Kubernetes by Example [](https://amzn.to/3NLCAMB) {{}} So I was already working on this by Christmas day on this book. Ansible for Kubernetes by example, was published in, was published in May 23. I was so proud of his book because it distilled all the knowledge about the containers and how to manage the Kubernetes infrastructure. Kubernetes is very important ... --- ## Mastering Conditionals in Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/mastering-conditionals-in-ansible-playbooks Description: Learn how to use conditionals in Ansible to dynamically control task execution. Explore practical examples, common use cases, and advanced tips for. ## Introduction In Ansible, conditional statements are a cornerstone of efficient and dynamic playbooks. They enable you to control task execution based on specific criteria, ensuring that only relevant actions are performed. This article explores the `when` clause, showcasing how conditionals can streamline automation workflows. ## What are Conditionals in Ansible? Conditionals allow you to execute tasks only when certain conditions are met. This is achieved using the `when` keyword, which evaluates a condition and determines whether the task should run. ### Basic Syntax [code example] In this example, the task runs only if the operating system family is `RedHat`. --- ## Common Use Cases for Conditionals ### 1. Operating System Checks Conditionals are often used to execute tasks specific to an operating system. #### Example: [code example] ### Use Case: - Ensures tasks are executed only on compatible systems, avoiding unnecessary or conflicting actions. --- ### 2. Variable Validation Conditionals can check if a variable is defined or has a specific value. #### Example: [code example] ### Use Case: - Avoids errors in playbooks by verifying variable existence or value before execution. --- ### 3. Combining Multiple Conditions You can combine multiple conditions using logical operators like `and` and `or`. #### Example: [code example] ### Use Case: - Enforces complex preconditions for task execution. --- ## Advanced Techniques with Conditionals ### 1... --- ## Mastering CPU Scheduling with chrt Command URL: https://www.ansiblebyexample.com/articles/mastering-cpu-scheduling-with-chrt-command Description: Optimize Your System with Advanced Scheduling Techniques and the Power of the chrt Command. Tested on real machines with clear, copy-paste examples. ## Introduction In the realm of system administration, mastering the intricacies of CPU scheduling and resource management is akin to possessing a secret code that unlocks enhanced system efficiency and performance. Among the powerful tools at the disposal of system administrators, the `chrt` command stands out as a potent instrument for fine-tuning process scheduling, ensuring that critical tasks receive the attention they deserve while maintaining the delicate balance of system resources. This article delves into the nuances of the `chrt` command, shedding light on its role in controlling CPU scheduling algorithms and optimizing process management. ## 1. Understanding CPU Scheduling Algorithms At the heart of CPU scheduling lies a range of algorithms designed to allocate processor time among various processes. These include Time Sharing (TS), Completely Fair Scheduler (CFS), and First-In, First-Out (FIFO), among others. Each algorithm has its unique approach to managing how processes share CPU time, influencing system responsiveness and efficiency. For instance, CFS aims to distribute CPU time equally among processes, whereas FIFO schedules processes in the order they arrive, without preemption. ## 2. The Role of Context Switching Context switching is a fundamental concept in multitasking environments, enabling the CPU to switch between different processes. This mechanism allows a single CPU to manage multiple tasks by saving the state of a currently running process an... --- ## Mastering Nested Lists in Ansible Playbooks: A Practical Guide URL: https://www.ansiblebyexample.com/articles/nested-lists-with-flatten-and-unique Description: Learn how to handle nested lists in Ansible using powerful filters like flatten and unique. Simplify data structures for efficient automation workflows. ## Introduction Ansible's flexibility in automation often involves handling intricate data structures. Nested lists, a common scenario, can pose challenges for efficient processing in playbooks. In this guide, we’ll explore how to manipulate and optimize nested lists in Ansible, leveraging powerful filters like `flatten` and `unique` to simplify workflows. --- ## The Challenge: Nested Lists Imagine this scenario: you have a data structure like the one below that needs processing: [code example] The structure has nested lists, empty elements, and requires transformation into a single, flat list for further tasks. Our goal: - Flatten the structure. - Remove unnecessary empty elements. - Ensure the integrity of the data for seamless automation. --- ## Solution: Flatten and Optimize Lists Ansible's `flatten` filter is your go-to tool for collapsing nested structures into manageable lists. Let’s see it in action. ### Playbook Example [code example] --- ### Output The playbook will transform the list into: [code example] --- ## Advanced Techniques ### Removing Duplicates In cases where the flattened list contains duplicate entries, apply the `unique` filter: [code example] ### Comparing Lists To compare two lists and validate their content, use filters like `map(attribute='name')` and `difference`. This ensures all elements match between lists. --- ## Use Cases 1. **Dynamic Inventories**: Simplify nested inventory data for efficient host management. 2. **Config... --- ## Mastering the Red Hat Certified Engineer (RHCE) Exam URL: https://www.ansiblebyexample.com/articles/red-hat-certified-engineer Description: A comprehensive guide to RHCE certification, featuring Linux administration, Ansible automation, and cutting-edge technologies like containers. ## Introduction Achieving the Red Hat Certified Engineer (RHCE) certification is a transformative step for IT professionals aiming to excel in Linux system administration and automation. Luca Berton’s "Mastering the Red Hat Certified Engineer (RHCE) Exam" serves as a comprehensive guide for aspiring candidates. This Kindle edition is crafted to demystify the RHCE exam, combining theoretical concepts with hands-on labs. [](https://amzn.to/3ZOJ2IM) {{}} ## Why RHCE Certification? The RHCE certification validates your expertise in managing Red Hat Enterprise Linux (RHEL) systems and automating tasks using tools like **Ansible**. In today's IT landscape, where automation and cloud integration are pivotal, holding an RHCE credential is a career accelerator. ## Book Highlights ### Key Features - **Complete Coverage**: Exam preparation with theory, practical labs, and strategy tips. - **Ansible Proficiency**: Dive deep into automation with Ansible playbooks. - **Networking and Security**: Master SELinux, firewalls, and secure system management. - **Emerging Technologies**: Learn container management, virtualization, and cloud integration. ### What You'll Learn 1. **Linux Administration**: Fundamental and advanced RHEL skills. 2. **Automation Mastery**: Automate repetitive tasks with Ansible. 3. **Networking Expertise**: Configure services and secure RHEL systems. 4. **Performance Optimization**: Troubleshoot and enhance system performance. 5. **Container and Virtualization*... --- ## Mastering Time in Ansible: The now() Function Guide URL: https://www.ansiblebyexample.com/articles/mastering-time-in-ansible-the-now-function Description: Complete guide to the Ansible now() function. Format dates with strftime, calculate uptime, compare timestamps, and use UTC/local time in playbooks. ## Introduction The `now()` function, introduced in Ansible 2.8, gives you access to the current date and time directly inside Jinja2 templates. Unlike `ansible_date_time` facts (which are captured once during fact gathering), `now()` evaluates at the moment the task runs — making it ideal for accurate timestamps in deployments, log files, and time-based logic. ## Syntax and Arguments [code example] | Argument | Type | Default | Description | |----------|------|---------|-------------| | `utc` | bool | `false` | Return UTC time instead of local time | | `fmt` | string | None | `strftime` format string. If omitted, returns a Python datetime object | When `fmt` is provided, `now()` returns a **string**. Without `fmt`, it returns a **datetime object** that supports arithmetic operations. ## Common strftime Format Codes | Code | Output | Example | |------|--------|---------| | `%Y` | 4-digit year | `2024` | | `%m` | Zero-padded month | `03` | | `%d` | Zero-padded day | `07` | | `%H` | Hour (24-hour) | `14` | | `%M` | Minute | `30` | | `%S` | Second | `45` | | `%s` | Unix epoch | `1709821845` | | `%B` | Full month name | `March` | | `%A` | Full day name | `Thursday` | | `%Z` | Timezone name | `UTC` | | `%j` | Day of year | `067` | | `%U` | Week number | `09` | ## Practical Examples ### Timestamped Backup Directories [code example] ### Deployment Metadata [code example] ### Log File Naming [code example] ### Conditional Execution Based on Time Run tasks only during ... --- ## Maximize Ansible Efficiency with Callback Plugins for Resource Monitoring URL: https://www.ansiblebyexample.com/articles/assess-resource-consumption-with-ansible-callback-plugins Description: Learn how to use Ansible callback plugins like cgroup_memory_Conclusion and cgroup_perf_recap to monitor resource consumption and optimize performance. ## Introduction When managing infrastructure with Ansible, it’s essential to have insights into resource consumption and performance metrics during playbook execution. Ansible provides a powerful tool for this purpose: callback plugins. This article explores how callback plugins can help you assess resource consumption, troubleshoot issues, and gain deeper insights into Ansible playbook execution. ### Understanding Ansible Callback Plugins What are Ansible callback plugins? According to Ansible’s documentation, callback plugins enable adding new behaviors to Ansible when responding to events. These plugins control most of the output you see when running Ansible commands, but they can also be used to: - Add additional output. - Integrate with other tools. - Marshal events to a storage backend. Callback plugins are a versatile way to customize and enhance Ansible’s functionality. ## Focus on cgroup_memory_Conclusion and cgroup_perf_recap This article focuses on two specific callback plugins: `cgroup_memory_Conclusion` and `cgroup_perf_recap`. These plugins utilize cgroups (Control Groups) to profile resource consumption during Ansible tasks and playbook execution. - `cgroup_memory_Conclusion`: This plugin profiles the maximum memory usage of Ansible and individual tasks and provides a recap at the end using cgroups. - `cgroup_perf_Conclusion`: This plugin profiles system activity, including memory and CPU usage, of Ansible and individual tasks and displays a recap at the e... --- ## Meet Anže Luzar of XLAB Spotter at Ansible Community Day 2023 URL: https://www.ansiblebyexample.com/articles/meeting-anze-luzar-of-xlab-spotter-at-ansible-community-day-berlin-2023 Description: Learn about XLAB Spotter's Ansible Playbook Scanning Tool and contributions to the Ansible community. Join the Ansible Challenge starting October 12,. ## Introduction At the Ansible Community Day in Berlin 2023, I had the privilege of sitting down with Anže Luzar from XLAB Spotter to discuss the groundbreaking Ansible Playbook Scanning Tool known as “Steampunk Spotter.” This innovative tool complements the enterprise journey of Ansible automation by optimizing processes, enhancing reliability, security, and compliance, and offering a suite of advanced features for playbook developers and IT professionals. In our engaging conversation with Anže Luzar of XLAB Spotter at the Ansible Community Day in Berlin, we gained valuable insights into the remarkable contributions and future aspirations of this dynamic team. Anže, a DevSecOps Engineer, leads the charge in toolchain development, particularly in crafting the CLI and integrations for Steampunk Spotter. ### Ansible Community Day The Ansible Community Day in Berlin 2023 is an event organized by The Ansible Community Team at Red Hat. It is designed to connect with people who use, contribute to, and develop the Ansible project globally. This event serves as a platform to engage with the diverse Ansible community, including users, contributors, and developers, and to highlight their experiences and contributions. ### Understanding XLAB Steampunk Spotter Before diving into our interview with Anže, let’s take a moment to grasp the significance of XLAB Spotter. This Ansible Playbook Scanning Tool is designed to analyze Ansible playbooks comprehensively. It goes beyond merely identi... --- ## Microsoft SQL Server: Performance Tuning Essentials URL: https://www.ansiblebyexample.com/articles/microsoft-sql-server-performance-tuning-essentials Description: Learn how to optimize Microsoft SQL Server performance, enhance query tuning, and improve database efficiency with Luca Berton's course on Coursera. ## Introduction Do you want your applications to run smoothly, with fast database responses and minimal downtime? Welcome to "Microsoft SQL Server: Performance Tuning Essentials," a comprehensive course on Coursera taught by Luca Berton. Designed for database administrators, IT professionals, and technical managers, this course provides practical strategies and techniques to optimize SQL Server performance and ensure consistent, reliable operations. {{}} --- ## What You'll Learn This course empowers you with the knowledge and tools to: - **Analyze and tune SQL queries** to enhance performance and reduce latency. - **Implement effective indexing strategies** to improve database efficiency. - **Monitor and troubleshoot performance issues** in SQL Server. - **Apply best practices** for maintaining SQL Server operations effectively. By mastering these skills, you'll be able to enhance database performance, minimize downtime, and ensure smooth back-end operations for your applications. --- ## Course Highlights ### Key Features - **1 Module:** Focused on practical SQL performance optimization strategies. - **Intermediate Level:** Recommended for those with basic SQL Server knowledge. - **Flexible Schedule:** Learn at your own pace. - **2 Hours to Complete:** Concise, targeted learning. - **Certificate Included:** Showcase your skills with a shareable credential. ### Learning Tools - **11 Videos:** Covering essential topics like query tuning, indexing strategies, database ... --- ## Mitigate CVE-2021-4034 on RHEL with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/how-to-mitigate-polkit-privilege-escalation-pwnkit-cve-2021-4034-on-redhat-like-systems-ansible-playbook-mitigation Description: HUse Ansible to mitigate CVE-2021-4034 on RHEL systems. Automate the installation of SystemTap, debugging packages, and deploy mitigation scripts. ## What is Polkit Privilege Escalation - (CVE-2021–4034)? - "A memory corruption vulnerability in Polkit's pkexec, witch allows any unprivileged user to gain full root privilege on a vulnerable system using default polkit configuration" cit. Bharat Jogi, qualys.com {{}} ## Links - In deth analysis from Bharat Jogi, qualys.com - Red Hat CVE-2021-4034 - Red Hat RHSB-2022-001 Ansible Playbook 1.0 ## Playbook How to mitigrate Polkit Privilege Escalation - PWNKIT (CVE-2021–4034) on RedHat-like systems using the Ansible Playbook downloaded from RHSB-2022–001. ### code Code downloaded from Red Hat RHSB-2022-001 Ansible Playbook 1.0 . ### execution [code example] ### before execution [code example] ### after execution [code example] ## Conclusion Now you know how to mitigate the Polkit Privilege Escalation - PWNKIT (CVE-2021–4034) on RedHat-like systems using the Ansible Playbook 1.0 published on RHSB-2022–001. --- ## Nested Lists in Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/nested-lists-in-ansible-playbooks Description: Learn how to work with nested lists in Ansible playbooks. Practical examples of iterating over complex data structures using loops and filters. ## Introduction CfgMgmtCamp 2025, the premier event for systems administrators, DevOps engineers, and Infrastructure as Code enthusiasts, is taking place in **Ghent, Belgium**, from **February 3–5, 2025**. Among the many notable speakers, **Luca Berton**, a globally recognized Ansible expert, will share his expertise on automating AI-driven environments. ## Session Overview: Automating AI-Powered Graph Databases with Ansible **Title**: Automating AI-Powered Graph Databases with Ansible: A Neo4j GenAI Case Study **Date & Time**: February 4, 2025, 14:00–14:25 **Location**: Ansible 1 (B.1.017) **Session Type**: Short Talk (25 minutes) In this insightful session, Luca Berton will demonstrate: - Automating the deployment of Neo4j GenAI environments using **Ansible playbooks**. - Integrating OpenAI for **retrieval-augmented generation (RAG)** tasks. - Best practices for configuring, managing, and optimizing AI-powered graph databases in **hybrid cloud environments**. This talk is tailored for IT professionals looking to streamline complex AI setups using modern Infrastructure as Code (IaC) techniques. Expect hands-on demonstrations and actionable takeaways to enhance your automation journey. ## About Luca Berton Luca Berton is a seasoned Ansible Automation Expert and the author of best-selling books, including: - **Ansible for Kubernetes by Example**: Automate Your Kubernetes Cluster - **Ansible for VMware by Example** With over 15 years of experience, Luca has been... --- ## Official Recording Ansible Pilot Community: Ansible Anwendertreffen 2022 URL: https://www.ansiblebyexample.com/articles/15-02-2022-from-zero-to-hero-how-to-build-the-ansible-pilot-community-ansible-anwendertreffen Description: Official Recording! Join Luca Berton on February 15, 2022, at Ansible Anwendertreffen for insights on building the Ansible Pilot Community. Register. ## TL;DR: From Zero to Hero: How to build the Ansible Pilot Community - Ansible Anwendertreffen 15 February 2022 conference {{}} - 15:15 - 16:00 CET timezone - From Zero to Hero: How to build the Ansible Pilot Community - by Luca Berton (Red Hat CZ) - The full program of the conference. ## My presentation: 15 Feb 2022 Ansible Anwendertreffen🇩🇪 - Ansible Anwendertreffen — 3rd edition — 15 Feb 2022 - **15:15 – 16:00** CET timezone From Zero to Hero: How to build the Ansible Pilot Community by Luca Berton - Focus on Ansible Users - Ansible Anwendertreffen🇩🇪 ## What is Ansible Anwendertreffen? It’s a very nice meeting place, especially for the German speakers' Ansible users! Danke schön 🇩🇪 Wir sehen uns dort. Prost! My German is bad, apologies. The conference started three years ago by two fellow Red Hat Solution Architects aim to support the day-to-day Ansible Users, real use case, not a marketing event! The event is public, free, and probably interesting for many Developers, System Administrator, DevOps, Cloud Engineers. Hurry up and register on the Ansible Anwendertreffen🇩🇪 website. I was one of the speakers of the Breakout Track 1–15:15–16:00 From Zero to Hero: How to build the Ansible Pilot Community by Luca Berton. In the video some interesting insight, the awards, some behind scenes, and lessons learn from the creation of the Ansible Pilot Community. Many thanks to the organizer of the conference Christian Jung, Principal Specialist Solution Architect EMEA, a... --- ## OpenClaw Agentic Automation with Ansible — CVE Remediation Demo URL: https://www.ansiblebyexample.com/articles/openclaw-agentic-automation-with-ansible-cve-remediation-demo Description: OpenClaw orchestrates end-to-end CVE remediation: agent detection, ServiceNow ticketing, OPA policy review, AAP execution, and compliance reporting. # OpenClaw Agentic Automation with Ansible — CVE Remediation Demo ## Introduction OpenClaw orchestrates end-to-end CVE remediation: agent detection, ServiceNow ticketing, OPA policy review, AAP execution, and compliance reporting. This article covers the key announcements, architecture decisions, and practical implications for Ansible automation teams. ## Key Highlights ### What Changed The Red Hat ecosystem continues evolving toward AI-driven, event-reactive automation. The 2026 updates focus on reducing manual intervention while maintaining governance and compliance. ### Architecture Overview [code example] ## Impact on Automation Teams | Area | Before | After | |------|--------|-------| | Incident response | Manual triage | AI-assisted diagnosis | | Playbook creation | YAML from scratch | Natural language + AI | | EE building | CLI only | Visual self-service | | Event handling | Reactive scripts | Governed pipelines | | Compliance | Periodic audits | Continuous verification | ## Getting Started [code example] ## Migration Considerations 1. **Version check** — ensure AAP 2.5+ before upgrading to 2.7 2. **PostgreSQL upgrade** — plan for PostgreSQL 13 → 17 migration 3. **Gateway architecture** — consolidate entry points 4. **Collection updates** — pin to compatible versions 5. **Training** — upskill team on EDA and MCP concepts ## Best Practices 1. **Start small** — pilot AI features with non-critical workflows 2. **Keep humans in the loop** — approval gates fo... --- ## Optimize Kubernetes CPU Resources with Ansible Playbooks URL: https://www.ansiblebyexample.com/articles/assign-cpu-resources-to-kubernetes-k8s-or-openshift-ocp-containers-and-pods-ansible-module-k8s Description: Learn to assign CPU resources to Kubernetes and OpenShift pods using Ansible. Streamline your container management with effective resource configuration. ## How to Assign CPU Resources to Kubernetes (K8s) or OpenShift (OCP) Containers and Pods with Ansible Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today I'll show you how to manage CPU resource allocation for containers and pods in Kubernetes (K8s) and OpenShift (OCP) using Ansible. In Kubernetes and OpenShift, containers cannot exceed their configured CPU limits. If there's available CPU time, a container is guaranteed as much CPU as it requests. You can control this behavior using the `resources` field in your container's manifest. Specifically, `resources:requests` sets the amount of CPU the container is guaranteed, while `resources:limits` specifies the maximum amount of CPU the container can use. ## Using Ansible for Kubernetes and OpenShift ### Introduction to the `k8s` Module Ansible provides the `kubernetes.core.k8s` module to manage Kubernetes (K8s) and OpenShift (OCP) resources. This module allows you to create, update, and delete various Kubernetes objects. #### Key Parameters - **name**: The name of the Kubernetes object. - **namespace**: The namespace in which the object resides. - **api_version**: The API version of the object (e.g., "v1"). - **kind**: The type of the object (e.g., Pod, Namespace). - **state**: Desired state of the object (e.g., `present`, `absent`, `patched`). - **definition**: A YAML or JSON definition of the object. - **src**: Path to a file containing the YAML or JSON definition. - **template**: A YAML or JSON te... --- ## Output Ansible Playbooks as YAML with Callback Plugin URL: https://www.ansiblebyexample.com/articles/output-ansible-playbooks-as-yaml-with-callback-plugin Description: Learn how to use Ansible ping module to test connections and customize output with callback plugins, demonstrated with a detailed playbook. ## Introduction Ansible, a powerful open-source automation tool, simplifies complex IT tasks by automating configuration management, application deployment, and other repetitive operations. One of Ansible's strengths lies in its extensibility, allowing users to customize their workflows. In this article, we'll explore the use of Ansible callback plugins and how they can enhance playbook output. ## Ansible Playbook Overview Before diving into callback plugins, let's examine a simple Ansible playbook. The playbook named `ping.yml` showcases the basic functionality of the Ansible `ping` module. It verifies the connectivity to target hosts and reports the results. [code example] Additionally, an `inventory` file specifies the target host, in this case, `localhost` with a local connection: [code example] ## Executing the Playbook Without Callback Plugins When running the playbook without callback plugins, the command looks like this: [code example] The output shows the default Ansible playbook execution summary: [code example] This standard output provides essential information, but what if you want a more detailed and customized report? ## Introducing Callback Plugins Callback plugins in Ansible offer a way to customize and extend the output of playbook runs. In the provided `ansible.cfg` configuration file, the following lines enable the callback plugin: [code example] Now, when running the playbook with the callback plugin, use the same command: [code example] ... --- ## Paramiko Deprecated for network_cli — Migrate to libssh URL: https://www.ansiblebyexample.com/articles/paramiko-deprecated-for-network-cli-migrate-to-libssh Description: Paramiko is deprecated for Ansible network_cli connections. Migrate to ansible-pylibssh before the 2028 removal deadline with this step-by-step guide. # Paramiko Deprecated for network_cli — Migrate to libssh ## Introduction The Ansible project has officially deprecated Paramiko as an SSH transport for `network_cli` connections. Paramiko support will be **removed after 2028-02-01**. The recommended replacement is `ansible-pylibssh`, which provides better performance and aligns with Ansible's direction toward OpenSSH/libssh for all SSH connectivity. This guide covers why the change is happening, how to migrate, and how to verify your network automation playbooks work with libssh. ## Why Paramiko Is Being Deprecated | Aspect | Paramiko | libssh (pylibssh) | |--------|----------|-------------------| | Performance | Pure Python, slower | C library, faster | | Maintenance | Community-maintained | Part of Ansible direction | | SSH features | Limited subset | Full OpenSSH compatibility | | Key exchange | Older algorithms | Modern algorithms | | Future support | Removed after 2028-02-01 | Long-term supported | Ansible's SSH strategy is converging on OpenSSH and libssh across all connection types — `ssh`, `network_cli`, `httpapi`, and `netconf`. ## Timeline [code example] ## Check Your Current Configuration [code example] [code example] ## Migration Steps ### Step 1: Install ansible-pylibssh [code example] ### Step 2: Update Configuration [code example] [code example] ### Step 3: Test Connectivity [code example] ### Step 4: Handle SSH Key Differences [code example] ## Example Network Playbook (After Migration) ... --- ## Participate in the Ansible Project Survey 2024 & Join the Community URL: https://www.ansiblebyexample.com/articles/participate-in-the-ansible-project-survey-2024 Description: Take part in the Ansible Project Survey 2024 to help shape the future of automation. Join the community and share your valuable feedback today! ## Help Shape the Future of Ansible: Participate in the 2024 Project Survey and Stay Engaged with the Ansible Community As we continue to advance in the world of automation, collaboration, and open-source innovation, we are excited to announce a significant milestone in the Ansible community: the launch of the **Ansible Project Survey 2024**. This survey is the first of its kind—a project-wide effort to gather insights, feedback, and data directly from the people who matter most: **you, the users**. Whether you’ve been with us since the early days or are just starting your Ansible journey, your voice is crucial in shaping the future of Ansible. This comprehensive survey aims to understand how you use Ansible, what features are most valuable, what challenges you face, and how your experiences evolve over time. ### Why Your Participation Matters For years, we’ve done smaller, targeted surveys—like the one in 2020 that focused on documentation—but **we’ve never conducted a full-scale survey** like this. As the Ansible ecosystem grows, the need to understand how different industries, roles, and skill levels interact with our tools has become more important than ever. We’re diving into questions such as: - Which versions of Ansible are you using? - How do your experiences with Ansible change based on your role or industry? - What impact do advanced features and tools have on your satisfaction? - What can we do to improve your Ansible experience? With your input, we can devel... --- ## Preparing for KubeCon London 2025: My First-Time Attendee Experience URL: https://www.ansiblebyexample.com/articles/kubeconf-2025 Description: Join me, Luca Berton, as I prepare for my first-ever KubeCon + CloudNativeCon Europe 2025 in London. Discover my expectations, goals, and tips for making. As the days count down to KubeCon + CloudNativeCon Europe 2025 in London, I, Luca Berton, am eagerly preparing for my first-ever attendance at this premier Kubernetes and cloud-native event. With excitement and anticipation building up, I want to share my thoughts, expectations, and preparations ahead of this transformative experience. ## Why Attend KubeCon? KubeCon is the flagship conference for Kubernetes, bringing together developers, engineers, and thought leaders from around the world. With over 15,000 attendees expected in London, this event is the perfect opportunity to explore the latest trends in cloud-native technologies, network with industry professionals, and gain hands-on experience with Kubernetes. ## My Goals for KubeCon London 2025 ### Expand My Knowledge - Deepen my understanding of Kubernetes, service mesh, GitOps, and container security. - Attend hands-on workshops and technical sessions to stay ahead of industry advancements. ### Engage with the Community - Connect with fellow engineers, open-source contributors, and CNCF project maintainers. - Participate in community meetups and networking events. ### Explore Career and Business Opportunities - Learn about new tools and technologies from top tech companies in the exhibitor hall. - Engage with hiring managers and industry leaders for potential career collaborations. ## My KubeCon 2025 Preparation Checklist ✅ **Register and Plan My Schedule** - Shortlist keynotes, breakout sessions, and co-located... --- ## Private Automation Hub: Empowering Secure and Efficient Automation URL: https://www.ansiblebyexample.com/articles/private-automation-hub Description: Explore how the Private Automation Hub enhances security and efficiency in managing and distributing Ansible content within your organization. ## Private Automation Hub: Empowering Secure and Efficient Automation As organizations continue to embrace automation to streamline their IT operations, the need for secure, efficient, and manageable repositories for automation content becomes paramount. The Private Automation Hub is a key component of the Red Hat Ansible Automation Platform, providing organizations with a powerful solution to manage and distribute Ansible content within their own infrastructure. This article explores the concept, benefits, and practical applications of the Private Automation Hub. ## What is the Private Automation Hub? The Private Automation Hub is an on-premises repository that allows organizations to store, manage, and distribute their own Ansible Content Collections. It is designed to work seamlessly with the Red Hat Ansible Automation Platform, ensuring that automation resources are securely available and easily accessible to internal teams. ## Key Features and Benefits 1. **Centralized Repository**: The Private Automation Hub provides a centralized platform for storing Ansible Content Collections, which includes roles, modules, and playbooks. This centralization ensures that all team members have access to the most up-to-date and validated content. 2. **Enhanced Security**: By keeping automation content within the organization's infrastructure, the Private Automation Hub enhances security and control over the automation assets. This is particularly crucial for organizations dealing... --- ## Project signing with GPG and ansible-sign URL: https://www.ansiblebyexample.com/articles/project-signing-with-gpg-and-ansible-sign Description: How to sign an Ansible project using GPG and ansible-sign command line utility. With clear, copy-paste, step-by-step examples. ## How to sign an Ansible project? From a non-signed to a GPG-signed Ansible project. ## ansible-sign - available since 2022 - GPG signature - command line The `ansible-sign` command has been available since 2022 for installation in the most modern operating system. It is a command line tool so simplify the Project signing process using your terminal. Using the `ansible-sign` command, you sign a project using a GPG signature. ## Playbook - GPG sign a project I'm going to show you how to sign an Ansible project using the `ansible-sign` command line utility. At the beginning of this example, we start with a project with all our Ansible files without any GPG signature files. By the end of this Playbook, you are obtaining a GPG-signed project directory. Project directory files: - playbooks/ping.yml [code example] - inventory [code example] - MANIFEST.in [code example] ### 1. install ansible-sign Verify if the `ansible-sign` command is available in your terminal. When you obtain a command not found error, you should install it. [code example] When the package is not available on our favorite package manager (apt, DNF, yum, zypper, brew, conda), we can rely on the PIP Python package manager: `$ pip3 install ansible-sign` Expected output: [code example] By the end of this step, the command will be available with the following output: [code example] ### 2. create a MANIFEST.in file When the MANIFEST.in file is not present, we obtain the following message on the... --- ## Publishing Ansible Collections to Ansible Galaxy and Automation Hub URL: https://www.ansiblebyexample.com/articles/publishing-ansible-collections-to-ansible-galaxy-and-automation-hub Description: How to distribute our custom Ansible Collection to Ansible Galaxy and Automation Hub. With clear, copy-paste, step-by-step examples. ## Introduction Ansible Collections provides a structured way to package and distribute Ansible content, offering a modular and organized approach to automation. Collections typically include modules, plugins, roles, and playbooks that address specific use cases. In this article, we'll delve into the process of distributing Ansible Collections, covering key aspects such as configuring distribution servers, building tarballs, and publishing collections. ## Distribution Servers Before distributing an Ansible Collection, you need to choose a distribution server. The prominent options include: 1. Ansible Galaxy: Supports all collections and is widely used for community-driven content. 2. Pulp 3 Galaxy: Similar to Ansible Galaxy but with added support for signed collections. 3. Red Hat Automation Hub: Specifically for Red Hat-certified collections, with support for signed collections. 4. Privately Hosted Automation Hub: Enables distribution of collections authorized by the owners. ## Distribution Process Overview Distributing an Ansible Collection involves several steps: 1. Initial Configuration of Distribution Servers: - Create a namespace on each distribution server. - Obtain an API token for each server. - Specify the API token and distribution server in the configuration. 2. Building the Collection Tarball: - Review and update the version number in the `galaxy.yml` file. - Use the `ansible-galaxy collection build` command to create a tarball of the collection. 3. Prepa... --- ## Python Clean Build Directory — Remove dist, egg, __pycache__ URL: https://www.ansiblebyexample.com/articles/cleaning-the-build-directory-in-python Description: Clean Python build artifacts automatically. Remove dist, egg-info, __pycache__, and .pyc files with shutil, pathlib, and setup.py commands. ## Introduction In the dynamic world of Python development, maintaining a clean and efficient build environment is crucial for project stability and ease of updates. An often overlooked yet essential part of this process involves managing the build directory through your `setup.py` script. This article delves into techniques for automating the pre-deletion and post-deletion of the build directory, ensuring a cleaner, more manageable project structure. ### The Importance of a Clean Slate The build directory in a Python project, typically generated during the build process, can become cluttered with outdated or unnecessary files over time. Cleaning this directory before and after each build can prevent potential conflicts and reduce the overall size of your project, making version control and distribution more straightforward. ## Pre-Deletion and Post-Deletion Strategies **Pre-Deletion:** To ensure a clean starting point, the build directory should be deleted before the setup process begins. This can be achieved programmatically by using `distutils.dir_util.remove_tree` to remove the directory at the start of your `setup.py` script. **Example:** [code example] **Post-Deletion:** Cleaning up after your build is equally important. This step involves removing the build directory once the setup process has completed, ensuring that no unnecessary files linger in your project. One effective method for post-deletion is to subclass specific setup commands, overriding their `run... --- ## QPDF Decrypt PDF — Remove Password Protection Fast URL: https://www.ansiblebyexample.com/articles/unlocking-your-pdfs-a-step-by-step-guide-to-using-qpdf-for-decryption Description: Remove PDF password protection with QPDF in one command. Decrypt, merge, split, and convert PDFs locally — no uploads needed. Step-by-step examples. ## Introduction Are you stuck with a password-protected PDF and can't remember the password? Or perhaps you've been given the authorization to access a secured PDF file for work, but you're unsure how to go about it? In the digital age, where document security is paramount, such scenarios are commonplace. Fortunately, there's a straightforward solution to decrypting PDF files, and it lies in a powerful tool known as QPDF. ### What is QPDF? QPDF is a command-line program that’s a hidden gem for manipulating PDF files. It's not just a decryption tool; it can merge, split, and even convert PDFs into different formats. But its most sought-after feature is its ability to decrypt password-protected PDFs. ## Why Use QPDF for PDF Decryption? 1. **Ease of Use**: Despite being a command-line tool, QPDF is surprisingly user-friendly. With a simple command, you can decrypt your PDF files quickly. 2. **Security**: It handles your files locally, meaning you don’t have to upload sensitive documents to an online service. 3. **Free and Open Source**: QPDF is available for free, and being open-source, it has been vetted by a community of developers for any vulnerabilities. ## How to Decrypt a PDF Using QPDF Before you start, ensure you have QPDF installed on your computer. It’s available on most operating systems, including Windows, MacOS, and Linux. ### Step-by-Step Guide: 1. **Open Your Command Line Interface**: This could be Command Prompt on Windows, Terminal on MacOS, or a S... --- ## Quota Management for WinRM Remote Shells URL: https://www.ansiblebyexample.com/articles/quota-management-for-winrm-remote-shells Description: Mastering WinRM Quotas for Optimal System Resource Management. Hands-on, tested examples and best practices for Quota Management for WinRM Remote Shells. ## Introduction Managing system resources efficiently is paramount for the smooth operation of any networked environment. Windows Remote Management (WinRM), a crucial component in Windows Server environments, comes with its own set of quotas to ensure better service quality, mitigate denial of service issues, and allocate server resources to concurrent users effectively. These quotas are crucial for maintaining optimal system performance and security, and they are rooted in the quota infrastructure used by Internet Information Services (IIS). In this article, we’ll delve into the WinRM quota system, its settings, and how to configure them for your specific needs. ## The Importance of Quota Management The implementation of quotas within WinRM serves several critical purposes: 1. Limiting Shell and Process Creation: Quotas restrict the number of shells and shell processes a user can create. This prevents excessive resource consumption and potential system instability. 2. Controlling Concurrent Users: WinRM quotas help manage the maximum number of concurrent users who can access the system through remote shells. This is vital for maintaining the system’s responsiveness and preventing overuse. 3. Memory Allocation Management: Quotas also govern the amount of memory allocated to a shell, including its child processes. Effective memory management ensures that the system remains stable and responsive. 4. Inactive Shell Timeout: An idle timeout is set for remote shells. When shells... --- ## RAnsible's leadership in Forrester's evaluation validates its pivotal role in modern IT. As hybrid and multi-cloud environments grow, the need for reliable, scalable automation tools becomes critical. With tools like [Ansible Lightspeed](/articles/ansible-lightspeed-with-ibm-watson-code-assistant), which leverage AI for faster playbook creation, Red Hat continues to innovate, ensuring that Ansible remains indispensable.d Hat Ansible: Forrester Wave Market Leader Q4 2024 URL: https://www.ansiblebyexample.com/articles/red-hat-ansible-forrester-wave-market-leader-q4-2024 Description: Discover how Red Hat Ansible leads automation in Forrester Wave Q4 2024. Learn why Ansible is essential for IT professionals in 2024 and beyond. **Red Hat Ansible Automation Platform: Dominating Infrastructure Automation in 2024** Hi friends, I’m thrilled to share a significant milestone in the automation ecosystem. The latest **Forrester Wave™: Infrastructure Automation Platforms, Q4 2024** report confirms what many of us in the industry have believed for years—**Red Hat Ansible Automation Platform** is leading the charge as the market leader. This independent analysis, conducted by one of the most trusted names in the industry, highlights Ansible’s unmatched capabilities and strategic direction. ## Why Ansible in 2024 and Beyond? Forrester’s detailed evaluation, released on November 25th, 2024, underscores the competitive edge of the **Ansible Automation Platform**. Even with its version 2.4 being evaluated (while version 2.5 just launched), Ansible stood out for its comprehensiveness and robustness. This affirms the relevance of learning and mastering Ansible not just for today, but for the transformative years ahead in IT automation. Here’s why Ansible is worth your time and effort in 2024 and beyond: - **Wide-Range Capabilities**: It excels in infrastructure provisioning, configuration management, and orchestrating application lifecycles. - **Community-Driven Ecosystem**: Ansible benefits from a vibrant, collaborative open-source community, continuously enhancing its modules and integrations. - **Event-Driven Automation**: The addition of event-driven features significantly reduces manual intervention, posit... --- ## Read a JSON file into a variable — Ansible lookup plugin file URL: https://www.ansiblebyexample.com/articles/read-a-json-file-into-a-variable-ansible-lookup-plugin-file Description: How to automate the reading of example.json file on Ansible host, assign to a variable and use in your Ansible Playbook code. ## How to Read a JSON file into a variable on the host with Ansible? The JSON (JavaScript Object Notation) is an open standard file format used a lot for data interchange. ## Ansible reads a JSON file into a variable - `ansible.builtin.file` - read file contents - `from_json filter` - converts the variable to JSON. Let's dive deep into the Ansible lookup plugin file. Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources. The full name is `ansible.builtin.file`; it's part of `ansible-core` and is included in all Ansible installations. The purpose of the `file` lookup plugin is to read file contents. The "from_json" is an Ansible-specific filter to convert the input to JSON. Let's combine the result of the `file` lookup plugin with the `from_json` filter for our use case. ## Playbook How to read the example.json JSON file, assign it to a variable and use it in your Ansible Playbook code. ### code - example.json [code example] - read_json.yml [code example] ### execution [code example] ### idempotency [code example] code with ❤️ in GitHub ### Conclusion Now you know how to read a JSON file into a variable on the host with Ansible. --- ## Read an environment variable — Ansible lookup plugin env URL: https://www.ansiblebyexample.com/articles/read-an-environment-variable-ansible-lookup-plugin-env Description: How to automate the reading of HOME environmental variable and use it in your Ansible Playbook code with lookup plugin env. ## How to read an environment variable on Ansible Controller with Ansible? ## Ansible read an environment variable - ansible.builtin.env - Read the value of environment variables Let's deep dive into the Ansible lookup plugin env. Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources. The full name is `ansible.builtin.env`, it's part of `ansible-core` and is included in all Ansible installations. The purpose of the `env` lookup plugin is to read the value of environment variables. ## Parameters and Return Value ### Parameters - \_terms string - Environment variable ### Return Values - \_raw list - Values from the environment variables The parameters of plugin env. The only required parameter is the default "\_terms", with the name of the environment variable to read. The normal usage is to assign the lookup plugin to a variable name but you could use it in your Ansible task directly. ## Playbook Read an environment variable with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ## Conclusion Now you know how to read an environment variable with Ansible. You know how to use it based on your use case. --- ## Read file from remote hosts — Ansible module slurp URL: https://www.ansiblebyexample.com/articles/read-file-from-remote-hosts-ansible-module-slurp Description: How to automate the read of /proc/cpuinfo file from Linux remote host with Ansible. The file is copied as base 64 encoding and decoded with an Ansible. ## Read a file from remote hosts - Ansible module slurp How to automate the read of `/proc/cpuinfo` file from Linux remote host with Ansible. The file is copied as base 64 encoding and decoded with an Ansible Filter. ## Ansible Read file from remote hosts - ansible.builtin.slurp - Slurps a file from remote nodes - Fetching a base64-encoded blob of the data in a remote file. Today we're talking about the Ansible module `slurp`. The full name is `ansible.builtin.slurp` which means is part of the collection of modules "builtin" with ansible and shipped with it. This module is pretty stable and out for years and supports Linux and Windows targets. The purpose is to slurp a file from a remote location. Please note that the read operation is going to fetch a base64-encoded blob containing the data in a remote file. ## Parameters - src string - Remote file path This module has only one parameter "src", which is also mandatory. The parameter "src" specifies the source files in the remote hosts. It must be a file, not a directory. ## Links - ansible.builtin.slurp ## Playbook Read a file from remote hosts with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### verification [code example] code with ❤️ in GitHub ## Conclusion Now you know how to read a file from remote hosts with Ansible. --- ## Red Hat Achieves Top Recognition in G2 Rankings for 2024 URL: https://www.ansiblebyexample.com/articles/red-hat-achieves-top-recognition-in-g2-rankings-for-2024 Description: Red Hat has been recognized as the leader in network automation, container orchestration, and operating systems by G2. Tested, copy-paste examples included. ## Red Hat Leads the Pack in G2 Rankings Red Hat, a pioneer in open-source solutions, has once again secured top honors in G2’s peer-reviewed software rankings for 2024. Based on authentic user feedback, Red Hat has achieved #1 positions in three critical categories: - **Red Hat Ansible Automation Platform**: #1 in Network Automation Tools - **Red Hat OpenShift**: #1 in Container Orchestration - **Red Hat Enterprise Linux (RHEL)**: #1 in Container Engine and Operating System These accolades reflect Red Hat’s unparalleled contributions to automation, orchestration, and enterprise-grade software solutions. --- ## G2’s Recognition Explained G2, a trusted software review platform, bases its rankings on real-world feedback from verified users. This ensures unbiased insights into product usability, satisfaction, and overall value. The recognition highlights Red Hat's ability to deliver innovative solutions that address complex IT challenges. --- ## Why Red Hat Stands Out ### Red Hat Ansible Automation Platform: The Network Automation Leader Ansible simplifies network management by automating configuration, deployment, and monitoring tasks. Its agentless architecture and human-readable playbooks empower IT teams to streamline operations while reducing errors. G2 users specifically highlight: - **Ease of Use**: Simple YAML-based syntax - **Scalability**: From small businesses to global enterprises - **Cost Efficiency**: Reducing manual overhead Explore Network Automation ... --- ## Red Hat AI llm-d — Enterprise GenAI Inference on OpenShift URL: https://www.ansiblebyexample.com/articles/red-hat-ai-llm-d-enterprise-genai-inference-on-openshift Description: Red Hat's llm-d transforms LLM inference into composable Kubernetes-native architecture with disaggregated serving and Model-as-a-Service tiers. # Red Hat AI llm-d — Enterprise GenAI Inference on OpenShift ## Introduction Red Hat's llm-d transforms LLM inference into composable Kubernetes-native architecture with disaggregated serving and Model-as-a-Service tiers. This article covers the key announcements, architecture decisions, and practical implications for Ansible automation teams. ## Key Highlights ### What Changed The Red Hat ecosystem continues evolving toward AI-driven, event-reactive automation. The 2026 updates focus on reducing manual intervention while maintaining governance and compliance. ### Architecture Overview [code example] ## Impact on Automation Teams | Area | Before | After | |------|--------|-------| | Incident response | Manual triage | AI-assisted diagnosis | | Playbook creation | YAML from scratch | Natural language + AI | | EE building | CLI only | Visual self-service | | Event handling | Reactive scripts | Governed pipelines | | Compliance | Periodic audits | Continuous verification | ## Getting Started [code example] ## Migration Considerations 1. **Version check** — ensure AAP 2.5+ before upgrading to 2.7 2. **PostgreSQL upgrade** — plan for PostgreSQL 13 → 17 migration 3. **Gateway architecture** — consolidate entry points 4. **Collection updates** — pin to compatible versions 5. **Training** — upskill team on EDA and MCP concepts ## Best Practices 1. **Start small** — pilot AI features with non-critical workflows 2. **Keep humans in the loop** — approval gates for product... --- ## Red Hat Ansible Automation Platform 2.4 Released: Key Features and Enhancements URL: https://www.ansiblebyexample.com/articles/ansible-news-ansible-automation-platform-2-4-general-available Description: Discover the latest updates in Ansible Automation Platform 2.4, including the general availability of Event-Driven Ansible, a new web UI, and enhanced. Hello Ansible Pilot Community! We’re excited to announce that Red Hat Ansible Automation Platform 2.4 has been generally available since June 27, 2023. This latest release is based on Ansible Core 2.15.0 and introduces several significant new features and enhancements. **Key Highlights of Ansible Automation Platform 2.4:** 1. **Event-Driven Ansible:** - **General Availability:** The standout feature of this release is the full integration of Event-Driven Ansible. This includes a new (tech-preview) web UI and controller, providing a more streamlined interface for event-driven automation. - **New User Interface:** The Event-Driven Ansible architecture is now integrated into the Automation Controller, allowing for more dynamic and responsive automation workflows. 2. **Enhanced Content Management:** - **Collection Repository Management:** The Automation Hub now supports better control over access to automation content with improved repository management. - **Validated Content Integration:** Ansible validated content is now fully integrated into the private Automation Hub, enhancing security and reliability. 3. **Improved Tooling:** - **Ansible Builder 3.0:** This version offers enhanced content tooling, making it easier to create and customize Ansible Execution Environments. - **Platform Support:** The release introduces support for ARM architectures and technology preview support for Linux on Power and Z. 4. **User Interface and Integration Updates:** ... --- ## Red Hat Ansible Automation Platform 2.5: New Features & Updates URL: https://www.ansiblebyexample.com/articles/red-hat-ansible-automation-platform-2-5 Description: Explore the new features of Red Hat Ansible Automation Platform 2.5, from AI-driven playbooks to a unified UI and automation tools that boost efficiency. Hi friends, Exciting news! The Red Hat Ansible Automation Platform 2.5 is now officially available, as of September 30, 2024! This latest release introduces a host of new features and improvements designed to streamline your automation workflows and enhance efficiency across your IT infrastructure. ## 1. Unified Web UI - A Major Enhancement One of the most exciting changes in Ansible Automation Platform 2.5 is the unified web UI. If you're familiar with Istio and Kubernetes, you'll appreciate how this update aggregates all API calls under a single component. This redesign means that **authentication, authorization, and role-based access control (RBAC)** are now managed from one place, greatly simplifying user management. Whether you're configuring controller, Automation Hub, or event-driven authentication, everything is centralized. This unified UI improves design and streamlines enterprise authentication, eliminating the need to replicate configurations across different components. This is a big step forward in making the platform easier to manage! ## 2. Automation Calculator – Optimize Your Automation Jobs A new feature I'm particularly excited about is the **Automation Calculator**. This tool suggests ways to optimize your automation jobs and even offers insights into your **ROI (Return on Investment)** from using Ansible. It's going to be fascinating to see how accurate the suggestions are in real-world scenarios, especially as we push for greater efficiency in our wor... --- ## Red Hat Ansible Automation Platform book by Luca Berton URL: https://www.ansiblebyexample.com/articles/red-hat-ansible-automation-platform-book-by-luca-berton Description: Discover Luca Berton comprehensive guide to the Ansible Automation Platform. Learn to streamline, automate, and enhance IT operations efficiently. ## Introduction Ansible Automation Platform provides an enterprise framework for building and operating IT automation at scale, from security and networking to operations and software development teams. In the fast-paced world of IT, where agility, scalability, and reliability are non-negotiable, automation has emerged as a cornerstone for efficient data center management. Luca Berton’s book, “Mastering Automation: A Guide to the Ansible Automation Platform,” serves as an indispensable companion for those navigating the complexities of modern IT environments. This comprehensive guide empowers both beginners and seasoned professionals to harness the full potential of the Ansible Automation Platform, a versatile solution for streamlining operations, enhancing deployment processes, and automating critical tasks. [](https://amzn.to/41K0cbm) {{}} ## Author Bio Luca Berton is an Ansible Automation Expert. He has been working for the Red Hat Engineer Team for three years. With more than 15 years of experience as a System Administrator, he has strong expertise in Infrastructure Hardening and Automation. Enthusiast of the Open Source supports the community sharing his knowledge in different events of public access. ## Promise of the Book Embark on a journey to modernize your data center through Infrastructure as Code and Automation. This book guides you to mastering the Red Hat Ansible Automation Platform, enabling you to streamline processes, enhance security, and boost effici... --- ## Red Hat Developer Subscription — Free Renewal Guide URL: https://www.ansiblebyexample.com/articles/the-red-hat-developer-subscription-renewal-process Description: Renew your free Red Hat Developer Subscription step by step. Access RHEL, Satellite, and developer tools at no cost for personal use. ## Introduction Developers who leverage the Red Hat Developer Subscription for Individuals enjoy a host of benefits, including support, security, updates, and more. While this subscription is provided at no cost to developers, it’s essential to be aware of the one-year term limit and the renewal process. In this article, we’ll explore the key aspects of the Red Hat Developer Subscription, its term length, and the steps to seamlessly renew it. ### Understanding the Term Length The Red Hat Developer Subscription for Individuals (SKU RH00798) comes with a duration of one year. As the expiration date approaches, developers receive email notifications 30 days in advance and on the day of expiration. These notifications serve as reminders to re-register for the subscription, ensuring uninterrupted access to the valuable resources it offers. The following error might appear on the screen: - No enabled repositories [code example] - System Status Disabled [code example] - Auto attach failed [code example] ## Renewal Process To renew the Red Hat Developer Subscription, developers can follow a straightforward process. If the account was created before October 29th, 2022, it’s advisable to enable Simple Content Access for a more seamless experience. This can be done by clicking on the avatar on the right-hand side of the navigation bar, accessing Subscriptions, and toggling the Simple content access switch. The email reminder looks like the following Figure: For those who miss ... --- ## Red Hat Enterprise Linux 10 x86-64-v3 feature URL: https://www.ansiblebyexample.com/articles/red-hat-enterprise-linux-10-x86-64-v3-feature Description: Discover the potential performance benefits of the x86-64-v3 microarchitecture in RHEL 10, focusing on enhanced vector operations, FMA instructions. Introduction to x86--64-v3 in RHEL 10 ==================================== In Red Hat Enterprise Linux (RHEL) 9, Red Hat upgraded the instruction set architecture (ISA) baseline to the x86--64-v2 microarchitecture level. For RHEL 10, Red Hat is exploring an advancement to the x86--64-v3 level, potentially bringing significant performance benefits to various applications, particularly in data science and numerical computing domains. New CPU Capabilities in x86--64-v3 ================================= x86--64-v3 offers substantial improvements over its predecessor: - Enhanced vector register width in AVX and AVX2 instruction sets from 128 bits to 256 bits, adding new vector operations. - Support for the fused multiply-add (FMA) instruction, enabling more precise and efficient computations. - VEX encoding to improve instruction variants and reduce code redundancy, enhancing code density and reducing instruction cache pressure. - Additional bit manipulation operations for scalar registers, aiding in efficient data processing. Compatibility Impact ==================== The x86--64-v3 architecture first appeared in Intel's Haswell CPUs (2013) and AMD's Excavator microarchitecture (2015). However, adopting x86--64-v3 in RHEL 10 may exclude some systems without these capabilities, similar to the transition to x86--64-v2 in RHEL 9. Verifying Performance Improvements ================================== The CentOS ISA SIG has conducted experiments by rebuilding CentOS 9 wi... --- ## Red Hat Enterprise Linux 9 for SysAdmins Book by Luca Berton & Jerome Gotangco URL: https://www.ansiblebyexample.com/articles/red-hat-enterprise-linux-9-for-sysadmins-book-by-luca-berton-and-jerome-gotangco Description: Luca Berton and Jerome Gotangco present 'Red Hat Enterprise Linux 9 for SysAdmins'—a hands-on technical guide for secure, production-ready Linux. ## 🚀 **Announcing "Red Hat Enterprise Linux 9 for SysAdmins"** [](https://amzn.to/3CVHOUW) {{}} I'm excited to announce the release of **"Red Hat Enterprise Linux 9 for SysAdmins"**, co-authored with **Jerome Gotangco**! 🎉 This book is a **comprehensive, hands-on guide** designed for **system administrators, DevOps engineers, and IT professionals** who want to master **RHEL 9**. Whether you're **new to Linux** or an **experienced sysadmin**, this book will **elevate your skills** in managing, securing, and automating RHEL 9 environments. ## 📖 **What’s Inside the Book?** This book covers everything from **installation** to **advanced security hardening**, providing **practical knowledge** for **real-world system administration**. ### 🔹 **Key Topics Covered** ✅ **RHEL 9 Installation & Setup** (bare-metal, cloud, virtualized environments) ✅ **Cloud Deployments** on AWS, Azure, and GCP ✅ **Subscription & Package Management** ✅ **Infrastructure & Database Administration** ✅ **Podman & Containerized Applications** ✅ **Networking, Storage, & Filesystem Management** ✅ **Security Hardening & Auditing** ✅ **Virtualization & KVM Management** ✅ **DevOps Pipelines & Automation with Ansible** ✅ **AI/ML Workloads on RHEL 9** This book **not only teaches administration** but also **prepares you for RHEL-based certifications** and **real-world Linux management**. ## 🛒 **Where to Buy?** 📌 **Paperback:** Amazon 📌 **Kindle Edition:** Amazon Kindle [](https... --- ## Red Hat Enterprise Linux 9 Repos URL: https://www.ansiblebyexample.com/articles/red-hat-enterprise-linux-9-repositories-list Description: Explore Red Hat Enterprise Linux 9 repositories tailored for 64-bit Intel, AMD, and ARM architectures, supporting essential system packages and diverse. ## Introduction Red Hat Enterprise Linux (RHEL) 9 is a powerful operating system that caters to diverse hardware architectures, ensuring a seamless experience across various platforms. One of the key aspects of RHEL 9 is its repository system, which provides a centralized location for software packages, updates, and enhancements. In this article, we’ll explore the different repositories available for RHEL 9, focusing on the BaseOS and AppStream repositories for three major hardware architectures: 64-bit Intel and AMD, 64-bit ARM, and IBM Power (little endian) and IBM Z. ## 64-bit Intel and AMD ### BaseOS Repository Repository ID: `rhel-9-for-x86_64-baseos-rpms` Repository name: Red Hat Enterprise Linux 9 for `x86_64` — BaseOS (RPMs) Release version: `x86_64 ` The BaseOS repository for 64-bit Intel and AMD architecture serves as the foundation for RHEL 9. It contains essential packages and libraries required for the core functionality of the operating system. ### AppStream Repository Repository ID: `rhel-9-for-x86_64-appstream-rpms` Repository name: Red Hat Enterprise Linux 9 for `x86_64` — AppStream (RPMs) Release version: `x86_64 ` The AppStream repository complements the BaseOS by providing additional user-space applications, development tools, and runtime environments. It ensures a rich and diverse software ecosystem for RHEL 9 on 64-bit Intel and AMD platforms. ## 64-bit ARM ### BaseOS Repository Repository ID: `rhel-9-for-aarch64-baseos-rpms` Repository name... --- ## Red Hat Tech Day Netherlands 2026 — From Prompt to Harness Engineering URL: https://www.ansiblebyexample.com/articles/red-hat-tech-day-netherlands-2026-from-prompt-to-harness-engineering Description: Inside Red Hat Tech Day 2026: AgentOps, agentic AI, Quarkus, LangChain4j, hybrid cloud inference, and the shift from prompt to harness engineering. # Red Hat Tech Day Netherlands 2026 — From Prompt to Harness Engineering ## Introduction Inside Red Hat Tech Day 2026: AgentOps, agentic AI, Quarkus, LangChain4j, hybrid cloud inference, and the shift from prompt to harness engineering. This article covers the key announcements, architecture decisions, and practical implications for Ansible automation teams. ## Key Highlights ### What Changed The Red Hat ecosystem continues evolving toward AI-driven, event-reactive automation. The 2026 updates focus on reducing manual intervention while maintaining governance and compliance. ### Architecture Overview [code example] ## Impact on Automation Teams | Area | Before | After | |------|--------|-------| | Incident response | Manual triage | AI-assisted diagnosis | | Playbook creation | YAML from scratch | Natural language + AI | | EE building | CLI only | Visual self-service | | Event handling | Reactive scripts | Governed pipelines | | Compliance | Periodic audits | Continuous verification | ## Getting Started [code example] ## Migration Considerations 1. **Version check** — ensure AAP 2.5+ before upgrading to 2.7 2. **PostgreSQL upgrade** — plan for PostgreSQL 13 → 17 migration 3. **Gateway architecture** — consolidate entry points 4. **Collection updates** — pin to compatible versions 5. **Training** — upskill team on EDA and MCP concepts ## Best Practices 1. **Start small** — pilot AI features with non-critical workflows 2. **Keep humans in the loop** — approval ga... --- ## Reduce Intel CPU Overheating on Linux with Ansible and Thermald URL: https://www.ansiblebyexample.com/articles/reduce-intel-laptop-cpu-temperature-overheating-in-linux-ansible-module-package-and-thermald Description: Install and configure thermald on Intel Linux laptops using Ansible. Reduce CPU overheating with the package module — supports Debian, Ubuntu, and RHEL. ## How to Reduce Laptop CPU Temperature Overheating In Linux? I’m going to show you a live Playbook and some simple Ansible code. ## Reduce Intel Laptop CPU Temperature Overheating In Linux Today we’re talking about the open source project “Linux thermal daemon” (`thermald`) that monitors and controls the temperature in laptops, tablets PC with the latest Intel sandy bridge and latest Intel CPU releases. The thermald tool operates in two modes: - Zero Configuration Mode For most users, this should be enough to bring the CPU temperature of the system under control. This uses a DTS temperature sensor and uses Intel P state driver, Power clamp driver, Running Average Power Limit control, and cpufreq as cooling methods. - User-defined configuration mode This allows ACPI-style configuration in a thermal XML configuration file. This can be used to fix the buggy ACPI configuration or fine-tune it by adding more sensors and cooling devices. This is the first step in implementing a close loop thermal control in user mode and can be enhanced based on community feedback and suggestions. It’s available as a package “thermald” for the most used distribution today. Please note that this service might degrade laptop performance byslowing the CPU. ## Ansible Install a package in Linux - ansible.builtin.package - Generic OS package manager Today we’re talking about the Ansible module package. The full name is ansible.builtin.package, which means it is part of the collection of mod... --- ## Remove a local group on Windows-like systems — Ansible module win_group URL: https://www.ansiblebyexample.com/articles/remove-a-local-group-on-windows-like-systems-ansible-module-win-group Description: How to automate the removal of a local group \"accounting\" on Windows-like systems using the Ansible module win_group. Tested, copy-paste examples included. ## How to Remove a local group on Windows-like systems with Ansible? Note: Be very careful about typing the right group name because the delete operation is irreversible! ## Ansible Remove a group on Windows-like systems - `ansible.windows.win_group` - Add or remove groups Today we're talking about Ansible module `win_group`. The full name is `ansible.windows.win_group `, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It adds and removes local groups. For Linux target use the `group` module instead. ## Parameters - name _string_ - group name - state _string_ - present/absent - description _string_ - description of the group The only required is "name", which is the group name. The "state" parameter allows us to remove or delete a group, in our use case we need to specify "absent" to remove a group. The "description" parameter allows you to specify a description of the group, it's not necessary in this use case. ## Playbook How to remove a local group on Windows-like systems with Ansible Playbook. I'm going to show you how to automate the deletion of the "accounting" group on my Playbook Windows machine. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to remove a local... --- ## Remove a local user on Windows-like systems — Ansible module win_user URL: https://www.ansiblebyexample.com/articles/remove-a-local-user-on-windows-like-systems-ansible-module-win-user Description: How to automate the removal of a local user “example” on Windows-like systems using the Ansible module win_user. With tested, real-world examples. ## How to Remove a local user on Windows-like systems with Ansible? ## Ansible remove local user account - `ansible.windows.win_user` - Manages local Windows user accounts Today we're talking about Ansible module `win_user`. The full name is `ansible.windows.win_user`, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It manages local Windows user accounts. For Linux target use the `user` module instead. ## Parameters - name _string_ - user name - state _string_ - present/absent The only required is "name", which is the user name. The "state" parameter allows us to create or delete a user. For our use case, we need to use the "absent" option. ## Playbook How to Remove a local user on Windows-like systems with Ansible Playbook. I'm going to show you how to automate the deletion of the "example" user on my Playbook Windows machine. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution ### after execution code with ❤️ in GitHub ## Conclusion Now you know how to Remove a local user on Windows-like systems with Ansible. --- ## Rename a PostgreSQL Database — Ansible module postgresql_db URL: https://www.ansiblebyexample.com/articles/rename-a-postgresql-database-ansible-module-postgresql-db Description: Rename a PostgreSQL database with Ansible using the community.postgresql.postgresql_db module. Step-by-step playbook with examples and best practices. ## How to Rename a PostgreSQL Database with Ansible? ## Ansible Rename a PostgreSQL Database - `community.postgresql.postgresql_db` - Add or remove PostgreSQL databases from a remote host Let's talk about the Ansible module `postgresql_db`. The full name is `community.postgresql.postgresql_db`, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with `ansible-core` version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to add or remove PostgreSQL databases from a remote host. ## Parameters - name _string_ - Name of database - state _string_ - present/absent/dump/restore/rename - The operation Let me summarize the main parameters of the module `postgresql_db`. Ansible supposes that PostgreSQL is in the target node. The only required parameter is "name", the name of the database to interact with. The parameter "state" specify the desired state or the operation for the selected database. The option "present" means that the database should be Renamed and the option "absent" means that the database should be deleted. Other useful operations are "dump" and "restore" that uses `pg_dump`, the embedded PostgreSQL utility to backup and restore to the `target` file. Another useful operation is `rename`, from `name` to `target`. This module uses `psycopg2`, a Python PostgreSQL database library. You must ensure that `python3-ps... --- ## Restore a PostgreSQL Database — Ansible module postgresql_db URL: https://www.ansiblebyexample.com/articles/restore-a-postgresql-database-ansible-module-postgresql-db Description: How to automate the restore of a backup file of a “testdb” database on PostgreSQL using Ansible Playbook and postgresql_db module. ## How to Restore a PostgreSQL Database with Ansible? ## Ansible Restore a PostgreSQL Database - `community.postgresql.postgresql_db` - Add or remove PostgreSQL databases from a remote host Let's talk about the Ansible module postgresql_db. The full name is community.postgresql.postgresql_db, which means that is part of the collection of modules "community.postgresql" maintained by the Ansible Community to interact with PostgreSQL. The collection is tested with ansible-core version 2.11+, prior versions such as 2.9 or 2.10 are not supported. The purpose of the module is to add or remove PostgreSQL databases from a remote host. ## Parameters - name _string_ - Name of database - state _string_ - present/absent/dump/restore/rename - The operation - targer _string_ - filename Let me summarize the main parameters of the module postgresql_db. Ansible supposes that PostgreSQL is in the target node. The only required parameter is "name", the name of the database to interact with. The parameter "state" specifies the desired state or the operation for the selected database. The option "present" means that the database should be created and the option "absent" means that the database should be deleted. Other useful operations are "dump" and "restore" which use `pg_dump`, the embedded PostgreSQL utility to backup and restore to the target file. Another useful operation is rename, from name to target. This module use psycopg2, a Python PostgreSQL database library. You must ensure t... --- ## Restore Ansible Automation Platform URL: https://www.ansiblebyexample.com/articles/restore-ansible-automation-platform Description: Learn how to restore your Ansible Automation Platform from a backup, ensuring system recovery and continuity with a detailed step-by-step guide for a. ## Introduction Restoration Process: Bringing Your System Back to Life The restoration process is a critical aspect of any backup strategy. It ensures that your system can be recovered and brought back to a functional state in case of data loss, system failures, or other unforeseen incidents. In the context of the Ansible Automation Platform, the restoration process involves recovering your Automation Controller instance from a previously created backup. ## Step-by-Step Guide ### 1. Preparation: Before initiating the restoration process, there are a few key considerations and preparations: Backup File: You need to have a backup file (tarball) that was previously created using the backup process of the Ansible Automation Platform. This file contains the data and configuration needed to restore your system. Backup Location: Make sure you know the location of the backup file. By default, the backup file is stored in the same directory as the `setup.sh` script. However, you can use the `-e` flag with the `setup.sh` command to specify a non-default path for the backup file. Backup Version Compatibility: Ensure that the backup file corresponds to the version of the Ansible Automation Platform that you intend to restore. Attempting to restore from a backup created on a different version can lead to compatibility issues. ### 2. Execute Restoration: To initiate the restoration process, follow these steps: 1. Open a terminal and navigate to the directory where the `setup.sh` scri... --- ## Retrieve ASM Policy Facts from F5 BIG-IP with Ansible URL: https://www.ansiblebyexample.com/articles/retrieve-asm-policy-facts-from-the-f5-network-infrastructure Description: Automate F5 BIG-IP ASM policy retrieval using Ansible. Complete guide with the bigip_device_info module, filtering techniques, and practical network. ## Introduction F5 BIG-IP Application Security Manager (ASM) protects web applications from attacks. Using Ansible's `f5networks.f5_modules` collection, you can automate the retrieval of ASM policy information — useful for auditing, compliance reporting, and configuration management across your F5 infrastructure. ## Prerequisites ### Install the F5 Collection [code example] ### Python Dependencies [code example] ### Connection Setup F5 modules use the `httpapi` connection plugin or local connection with provider parameters: [code example] ## Retrieve ASM Policies ### Basic Example [code example] ### Available Gather Subsets for F5 | Subset | Description | |--------|-------------| | `asm-policies` | Application Security Manager policies | | `asm-policy-stats` | ASM policy statistics | | `asm-server-technologies` | ASM server technologies | | `asm-signature-sets` | ASM signature sets | | `ltm-pools` | Load balancer pools | | `ltm-virtual-servers` | Virtual servers | | `system-info` | System information | | `devices` | Device cluster info | | `vlans` | VLAN configuration | | `self-ips` | Self IP addresses | ## Filtering and Reporting ### Filter Policies by Name [code example] ### Generate Compliance Report [code example] Report template (`asm_report.j2`): [code example] ### Export Policies to JSON [code example] ## Multi-Device Inventory [code example] ## Common Issues ### Authentication Errors [code example] ### Timeout on Large Deployments [code e... --- ## Revolutionising Ansible: Testing the Limits of OpenAI’s ChatGPT for Smarter Automation URL: https://www.ansiblebyexample.com/articles/openai-chatgtp-and-ansible Description: Exploring the Power of OpenAI’s ChatGPT in Revolutionizing Ansible Coding: Advancing Automation to the Next Level. Tested, copy-paste examples included. ## OpenAI ChatGPT ChatGPT is a revolutionary artificial intelligence in that we can interact in a conversational way. Version 3 was launched in November 2022, and ChatGPT in March 2023. Its closest competitor is Google Bard. ## Links - Introducing ChatGPT - GPT-4 is OpenAI’s most advanced system, producing safer and more useful responses ## Four Challenges I decided to judge the quality of the AI using the following four challenges: 1. How to Pass Variables to Ansible Playbook in the command line? - Ansible extra variables 2. Configure a Windows Host for Ansible - Ansible winrm 3. Using Date, Time, and Timestamp in Ansible Playbook - Ansible Tip and Tricks 4. Change user password - Ansible module user ## Challenge 1 - How to Pass Variables to Ansible Playbook in the command line? - Ansible extra variables Score: Good ## Challenge 2 - Configure a Windows Host for Ansible - Ansible winrm Score: Bad ## Challenge 3 - Using Date, Time, and Timestamp in Ansible Playbook - Ansible Tip and Tricks Score: Good ## Challenge 4 - Change user password - Ansible module user Score: Good ## Conclusion ChatGPT is a great companion that speeds up prototyping and boosts our productivity. I'm impressed by the quality of the result. They appear good-looking and well-organized. However, at the moment, the outcome requires some manual rework before being able actually to use in our laboratory. The challenges saw that it is excellent for minor problems but lacks for those requirin... --- ## RHCE EX294 — Red Hat Certified Engineer Exam Guide URL: https://www.ansiblebyexample.com/articles/mastering-rhce-a-comprehensive-guide-to-red-hat-certified-engineer-ex294-exam Description: Complete RHCE EX294 exam guide: study topics, Ansible automation objectives, practice exercises, exam tips, and study resources for Red Hat Certified. ## Introduction The Red Hat Certified Engineer (RHCE) exam (EX294) is one of the most respected certifications in the Linux and DevOps world. Unlike multiple-choice exams, EX294 is a **performance-based exam** where you must complete real tasks on live systems within a time limit. The current version focuses heavily on Ansible automation, making it essential for anyone serious about infrastructure automation. This guide covers all exam objectives, practical study tips, and the Ansible skills you need to pass. ## Exam Overview | Detail | Information | |--------|-------------| | **Exam code** | EX294 | | **Duration** | 4 hours | | **Format** | Performance-based (hands-on tasks) | | **Prerequisite** | RHCSA (EX200) recommended | | **RHEL version** | RHEL 9 | | **Ansible version** | Ansible Core 2.14+ | | **Passing score** | 210 out of 300 (70%) | | **Cost** | ~$400 USD (varies by region) | ## Exam Objectives ### 1. Be a Red Hat Certified System Administrator (RHCSA) RHCE builds on RHCSA skills. You should already be proficient with: - File management and permissions - User and group administration - Service management with systemd - Firewall configuration with firewalld - SELinux management - LVM and storage management - Network configuration ### 2. Understand Core Components of Ansible This is the foundation of the exam. You must understand: **Inventories:** [code example] **Modules:** Know the most common modules: - `ansible.builtin.yum` / `ansible.builtin.dnf` - `... --- ## RHSB-2024–001 Leaky Vessels — runc — (CVE-2024–21626) URL: https://www.ansiblebyexample.com/articles/rhsb-2024-001-leaky-vessels-runc Description: Discover how to mitigate a critical vulnerability in Red Hat's runc component (CVE-2024-21626) that allows container escapes, potentially giving. ## Introduction Red Hat has identified a critical vulnerability in `runc`, a key component of container infrastructure, which facilitates container escapes, potentially allowing attackers unauthorized access to the host operating system from within a container. Exploitation methods include deceiving users into using or constructing a malicious image, or executing a malevolent process within the container with `runc exec`. This vulnerability, designated CVE-2024-21626, has been classified with an important severity impact. Affected Red Hat products include: - Red Hat OpenShift Container Platform versions 4 and 3.11 - Red Hat Enterprise Linux versions 7, 8, and 9 - Additional products running on Red Hat Enterprise Linux and RHEL CoreOS Notably, this issue also extends to product containers based on RHEL or UBI container images and product drawing packages from the RHEL channel. Related vulnerabilities, CVE-2024--23651, CVE-2024--23652, and CVE-2024--23653, found in moby buildkit, are under investigation. ## Technical Details The vulnerability stems from how `runc` handles the `WORKDIR` and `RUN` directives in Dockerfiles, leading to File Descriptor Leak and Path Traversal attacks. This flaw enables containers to bind to directories on the host system, thereby gaining unauthorized access to host resources. The issue arises from `runc`'s processing of the `WORKDIR` directive, allowing attackers to exploit the directive to access privileged file descriptors and manip... --- ## Rolling Update Debian-like systems — Ansible module apt URL: https://www.ansiblebyexample.com/articles/rolling-update-debian-like-systems-ansible-module-apt Description: Perform rolling updates on Debian/Ubuntu systems with Ansible apt module — full upgrade, selective updates, serial strategy, and reboot handling. ## Introduction Keeping your fleet of Debian-based servers consistently updated is one of the most critical — and time-consuming — tasks in system administration. The Ansible `ansible.builtin.apt` module automates package updates across Debian, Ubuntu, Linux Mint, Kali Linux, and all other APT-based distributions. This article covers single-package updates, full system upgrades, rolling update strategies with `serial`, reboot handling, and production best practices. ## Module Overview The `ansible.builtin.apt` module manages packages on Debian-like systems. For rolling updates, the key parameters are: | Parameter | Type | Description | |---|---|---| | `name` | string/list | Package name(s), or `"*"` for all packages | | `state` | string | `present`, `absent`, `latest`, `fixed` | | `update_cache` | boolean | Run `apt-get update` before install | | `cache_valid_time` | integer | Skip cache update if refreshed within N seconds | | `upgrade` | string | `no`, `safe`, `full`, `dist` | | `autoremove` | boolean | Remove unused dependencies | | `autoclean` | boolean | Clean local repository of old packages | | `force_apt_get` | boolean | Use `apt-get` instead of `aptitude` | | `dpkg_options` | string | Additional dpkg options | | `only_upgrade` | boolean | Only upgrade, don't install new | ## Update Strategies ### Strategy 1: Update a Single Package [code example] ### Strategy 2: Update All Packages [code example] ### Strategy 3: Safe Upgrade Uses `aptitude safe-upgrade` — ... --- ## Rolling Update Windows-like systems — Ansible module win_updates URL: https://www.ansiblebyexample.com/articles/rolling-update-windows-like-systems-ansible-module-win-updates Description: How to automate the Windows Update process and rebook if needed on Windows-like systems using Ansible Playbook and win_updates module. ## How to perform Rolling Update with Ansible on Windows-like systems? Every System Administrator knows how important is to maintain an up-to-date fleet in a consistent state. ## Ansible Rolling Update Windows-like systems - `ansible.windows.win_updates` - Download and install Windows updates Today we're talking about the Ansible module `win_updates`. The full name is `ansible.windows.win_updates `, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It downloads and installs Windows updates. For Linux target use the `yum` module for RedHat-like systems, `apt` for Debian-like, and `zypper` for Suse-like. ## Parameters - category_names _string_ - **CriticalUpdates**, DefinitionUpdates, DeveloperKits, FeaturePacks, **SecurityUpdates**, ServicePacks, **UpdateRollups** - state _string_ - searched / downloaded / **installed** - reboot _boolean_ /reboot_timeout - no / yes - log_path _path_ - append log file - accept_list / reject_list _list_ - titles or KB to whitelist or blacklist The parameter list is pretty wide but today we are focused only on the relevant for our use case. The most important is "category_names". The options are a lot here. The default is to enable only "CriticalUpdates", "SecurityUpdates" and "UpdateRollups" but could add or remove different categories. The "state" parameter specifies if the update i... --- ## Root Cause Analysis — Coursera Review URL: https://www.ansiblebyexample.com/articles/root-cause-analysis-principles-and-benefits Description: Review of the Coursera Root Cause Analysis course. Key principles, 5 Whys, fishbone diagrams, and how RCA applies to IT incident management. ## Introduction In the rapidly evolving business landscape, the ability to identify and address underlying issues that impact operations and productivity is crucial. Root Cause Analysis (RCA) is a systematic process designed to pinpoint the fundamental causes of issues, ensuring they are effectively addressed to prevent recurrence. The new course on Coursera, "Root Cause Analysis: Principles and Benefits," led by Luca Berton, offers a comprehensive dive into this critical thinking methodology, providing learners with the tools necessary to enhance their problem-solving capabilities. {{}} ## What is Root Cause Analysis? Root Cause Analysis is a method used by organizations to solve problems or prevent them from happening by addressing the root causes, rather than simply tackling the symptomatic outcomes. This approach not only helps in solving the immediate problem but also prevents similar issues from arising in the future. RCA can be applied across various industries and sectors, making it an invaluable skill for professionals aiming to improve their expertise in quality assurance, project management, and operational efficiency. ## Course Overview The Coursera course, taught in English, is structured for beginners and does not require prior expertise, although a basic understanding of business processes may be beneficial. This course is designed to be completed in just one hour, with a flexible schedule that allows learners to progress at their own pace. ## Learning ... --- ## Run a Python Script on Remote Machines — Ansible module script URL: https://www.ansiblebyexample.com/articles/run-a-python-script-on-remote-machines-ansible-module-script Description: How to automate the execution of a "cars.py" custom Python script on a remote machine after transferring it and processing the output as an Ansible. ## How to Run Python Script on Remote Machines after transferring it? ## Run Python Script on Remote Machines - `ansible.builtin.script` - Runs a local script on a remote node after transferring it Let’s talk about the Ansible module `script`. The full name is `ansible.builtin.script`, which means that is part of the Ansible builtin modules included in ansible-core. The purpose of the module is to Runs a local script on a remote node after transferring it. ## Parameters - `cmd` string - script name or path - `executable` string - executable name or path Let me summarize the main parameters of the module `script`. This module doesn't have any required parameters bus some options become necessary in this use case. The `cmd` parameter specifies the script name or path. The `executable` parameter specifies the interpreter name or path. ## Links - `ansible.builtin.script` ## Demo Let's jump into a real-life Ansible Playbook to Run Python Script on Remote Machines after transferring it. I'm going to show you how to create a `cars.py` custom Python script that output a JSON file, transfers it to a remote machine, and executes it using `python3` interpreter. ### code - cars.py [code example] - run_python_script.yml [code example] ### execution [code example] ### verbosity two execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Run Python Script on Remote Machines after transferring it with Ansible. --- ## Run and Stop Ansible AWX in Docker URL: https://www.ansiblebyexample.com/articles/run-and-stop-ansible-awx-in-docker-containers-ansible-awx Description: How to start, stop, manage, and troubleshoot Ansible AWX in Docker containers. Covers docker-compose commands, container architecture, accessing the Web. ## Introduction After building AWX from source, you need to know how to start, stop, and manage the Docker containers. This guide covers all the commands and troubleshooting you need for day-to-day AWX Docker operations. > **Note:** Docker-based AWX is recommended for development and testing. For production, use the AWX Operator on Kubernetes. ## Start AWX [code example] Your terminal attaches to the AWX container and streams logs in real time. The first startup runs database migrations to initialize the PostgreSQL schema. ## Container Architecture AWX runs six containers by default: | Container | Image | Purpose | |-----------|-------|---------| | `tools_awx_1` | `ghcr.io/ansible/awx_devel:HEAD` | Main AWX application (Web UI + API) | | `tools_postgres_1` | `postgres:12` | PostgreSQL database | | `tools_redis_1` | `redis:latest` | Redis cache and message broker | | `tools_receptor_hop` | `quay.io/ansible/receptor:devel` | Receptor mesh hop node | | `tools_receptor_1` | `ghcr.io/ansible/awx_devel:HEAD` | Receptor worker node 1 | | `tools_receptor_2` | `ghcr.io/ansible/awx_devel:HEAD` | Receptor worker node 2 | Verify all containers are running: [code example] [code example] ## Access the Web UI Navigate to `https://awx.example.com/` in your browser. Default credentials: - **Username:** `admin` - **Password:** `password` > Create a proper superuser with `awx-manage createsuperuser` — see Create AWX Superuser ## Access the API The REST API is available at `http... --- ## Run Ansible AWX in Docker — Install URL: https://www.ansiblebyexample.com/articles/run-the-latest-ansible-awx-in-docker-containers Description: Deploy AWX in Docker containers with docker-compose. Complete setup guide with PostgreSQL, Nginx, and initial configuration for Ansible automation. ## How to run the latest AWX in Docker containers? Running AWX in local Docker containers allows you to test the AWX web-UI and API to easily manage Ansible Playbook execution. AWX run on Docker is considered for Testing or Development only, the preferred way is via the AWX Operator since version 18.0. This initial configuration sometimes is a roadblock for some Ansible AWX users. ## Ansible AWX - Ansible AWX is the upstream project of Ansible Automation Controller (fromelly Ansible Tower) AWX is a very modern web UI and API that allows you to manage Ansible Playbooks, Inventories, Credentials, and Vaults between your team in your organization. Running AWX is a convenient way to centralize the storing and execution of all your Ansible resources and grant the relevant permissions only to selected users across your organization. Ansible AWX is the upstream project of Ansible Automation Controller (formerly Ansible Tower). The Ansible Automation Controller is part of the Red Hat Ansible Automation Platform (AAP). Red Hat released the AWX project under the Apache 2.0 Open Source license. Under the hood, it relies on cutting-edge Open Source technologies such as Redis, PostgreSQL, Django, and Python. ## Links - ansible/AWX GitHub repository ## Playbook How to run AWX in a Docker container. I'm going to show you how to get started on the latest AWX stable version (21.5.0 at the moment). I tested the following procedure on a Fedora 36 workstation. A step-by-step guide on ho... --- ## Run Long-Running Ansible Tasks Without Timeout — async & poll Guide URL: https://www.ansiblebyexample.com/articles/ansible-async-poll-long-running-tasks-timeout Description: Prevent Ansible task timeouts with async and poll. Run long tasks in the background, check status, and handle async results properly. # Run Long-Running Ansible Tasks Without Timeout ## The Problem [code example] Or tasks that take 30+ minutes (updates, backups, compilations) timing out. ## Solution: async & poll [code example] ## Fire and Forget (poll: 0) [code example] ## Parallel Long Tasks [code example] ## Common Patterns ### With Timeout Increase [code example] ### Check Multiple Background Jobs [code example] ## Limits - `async` doesn't work with `become` on some connection types - Not all modules support async - Fire-and-forget tasks (`poll: 0`) won't report failures unless you check ## Conclusion Use `async` + `poll` for any task over 30 seconds. Fire-and-forget (`poll: 0`) with `async_status` checks is the most efficient pattern for truly long tasks. --- ## Run RHEL 9.2 on Mac Using VMware Fusion: A Step-by-Step Guide URL: https://www.ansiblebyexample.com/articles/how-to-run-red-hat-enterprise-linux-rhel-9-2-on-an-apple-mac Description: Learn how to run Red Hat Enterprise Linux 9.2 on your Mac with VMware Fusion. Follow our step-by-step guide for seamless installation and configuration. ## Step by step To run Red Hat Enterprise Linux (RHEL) 9.2 on an Apple Mac using VMware Fusion, follow these steps: 1. Install VMware Fusion: Download and install VMware Fusion, virtualization software for macOS, from the VMware website. Ensure that you have a valid license for VMware Fusion. 2. Obtain the RHEL 9.2 ISO: Download the RHEL 9.2 ISO image from the Red Hat customer portal or the official Red Hat website. Make sure you have a valid subscription or evaluation license for RHEL. 3. Create a new virtual machine: Open VMware Fusion and click on “New” to create a new virtual machine. Choose the option to install from disc or image and select the RHEL 9.2 ISO file you downloaded. 4. Configure the virtual machine: Specify the name and location for the virtual machine. Select the desired operating system as “Linux” and the version as “Red Hat Enterprise Linux 9 (64-bit)”. Set the desired virtual machine settings, such as disk size, memory, and CPU allocation. 5. Customize virtual hardware (optional): You can customize the virtual hardware settings based on your requirements. This includes adjusting the number of processor cores, memory allocation, network settings, and storage options. 6. Begin the installation: Start the virtual machine, and it will boot from the RHEL 9.2 ISO. Follow the on-screen instructions to install RHEL within the virtual machine. This process will be similar to a regular RHEL installation on physical hardware. 7. Complete the installation: Pr... --- ## Run Windows 11 ARM on Apple Silicon — VMware Fusion URL: https://www.ansiblebyexample.com/articles/run-windows-11-client-arm64-insider-preview-in-apple-silicon-with-vmware-fusion Description: Install Windows 11 ARM64 on Apple Silicon M1, M2, M3, M4 with VMware Fusion. Step-by-step guide with Insider Preview ISO and TPM bypass. ## Introduction ARM-based processors have transformed the computing landscape, introducing greater efficiency and performance to various devices. Apple has been at the forefront of this revolution with its Apple Silicon lineup, including the M1, M2, and potentially M3 chips. Windows enthusiasts who own these devices might be excited to explore the possibility of running Windows 11 on Apple Silicon using the ARM64 Insider Preview. This article will delve into the steps to achieve this intriguing cross-platform setup. ### The Apple Silicon Advantage Apple Silicon processors, powered by ARM architecture, have gained immense popularity for their impressive power efficiency and performance. These chips have redefined the performance standards for laptops and desktops and Playbooknstrated potential for supporting other operating systems, such as Windows. ### Windows 11 ARM64 Insider Preview Microsoft’s Windows 11 ARM64 Insider Preview offers an exciting opportunity for users to experience Windows 11 on ARM-based devices. This includes support for ARM64 architecture, allowing it to run seamlessly on ARM-based processors, such as Apple’s M1, M2, and potentially M3 chips. ## Links - https://www.microsoft.com/en-us/software-download/windowsinsiderpreviewarm64 ## Step-by-Step Guide While running Windows 11 on Apple Silicon might sound complex, it can be achieved with the right set of tools and instructions. Here’s a step-by-step guide to help you get started. ### Virtual Machine 1... --- ## Running a Playbook with JetPorch: A Quick Guide URL: https://www.ansiblebyexample.com/articles/running-a-playbook-with-jetporch Description: Explore a basic JetPorch playbook syntax example Playbooknstrating task execution using the shell module to print \"hi\". Tested, copy-paste examples included. JetPorch, the Jet Enterprise Professional Orchestrator, is a powerful IT automation platform designed for Linux and Mac systems. Whether you're configuring, deploying, orchestrating, patching, or executing various tasks, JetPorch provides a flexible and community-driven solution. In this guide, we'll explore how to run a playbook with JetPorch, covering installation and basic playbook syntax. ## Installing JetPorch JetPorch can be installed either from packages or built from source. As of the first release (Tech Preview 1 on September 29th, 2024), following the development branch is encouraged for the latest features and bug fixes. Monthly releases are expected, making it worthwhile to stay up-to-date. ### Installing from Packages For Rust users, JetPorch can be installed using the following command: [code example] This command installs the `jetp` executable into `~/.cargo/bin`. Verify the installation using: [code example] ### Installing from Source Following the development branch ensures access to the latest features. Clone the repository and build JetPorch: [code example] ## Understanding Plays In JetPorch, a playbook is a YAML list consisting of one or more Play structures. Plays assign work or configurations to hosts using tasks and groups. The playbook structure is best understood by referring to the official documentation. ### What's in a Name? While the term "runbook" is common in IT, JetPorch adopts the term "playbook" from Ansible, using it as a sport... --- ## Schedule a Cron Job task in Linux — Ansible module cron URL: https://www.ansiblebyexample.com/articles/schedule-a-cron-job-task-in-linux-ansible-module-cron Description: How to automate the schedule of command execution to a specific minute, hour, day, month, weekday, and user in Linux using cron service. ## Ansible schedule a Cron Job task in Linux - ansible.builtin.cron - Manage cron.d and crontab entries Today we're talking about Ansible module cron. The full name is ansible.builtin.cron, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years and it works in a different variety of operating systems. It manages cron.d and crontab entries. For Windows targets, use the `ansible.windows.win_scheduled_task` module instead. ## Parameters - name string - crontab name - state string - present/absent - job string - command to execute - user string - defaults to the current user - minute, hour, day, month, weekday string - '\*', '1–31', '\*/2' - special_time - annually/daily/hourly/monthly/reboot/weekly/yearly - cron_file - NEVER use for /etc/crontab This module has some parameters to perform any tasks. The only required is "name", where you specify the description of a crontab entry. The parameter "state" sets whether the cron job is present or not in the target host. The parameter "job" sets the command to execute or, if env is set, the value of the environment variable. The parameter "user" sets the specific user for the crontab, when unset, this parameter defaults to the current user. The most important part is the moment to run the crontab, specifically: "minute", "hour", "day", "month", "weekday". In this field, you could use the star operator "\*" to specify all the minutes, hours, we... --- ## Search for a String in a File — Ansible module lineinfile URL: https://www.ansiblebyexample.com/articles/search-for-a-string-in-a-file-ansible-module-lineinfile Description: How to automate searching for the string "PasswordAuthentication no" in the "/etc/ssh/sshd_config" file using Ansible Playbook and the lineinfile module. ## How to Search for a String in a File with Ansible? I'm going to show you some simple Ansible code. ## Ansible module lineinfile > `ansible.builtin.lineinfile`: insert, update and remove a single line of text in a file Today we're talking about the Ansible module `lineinfile`. The full name is `ansible.builtin.lineinfile`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years and it supports a large variety of operating systems. You are able to insert, update and remove a single line of text in a file. ## Parameters - `path` string - file path - `line` string - text - `insertafter`/`insertbefore` string - EOF/regular expression - `validate` string - validation command - `create` boolean - create if not exist - `state` string - present/absent - `mode`/`owner`/`group` - permission - `setype`/`seuser`/`selevel` - SELinux This module has some parameters to perform any tasks. The only required is "path", where you specify the filesystem path of the file you're going to edit. "line" is the line of text we would like to insert in the file, easy! By default, the text is going to be inserted at the end of the file, but we could personalize it in a specific position with insertafter/insertbefore. If there is any tool to validate the file we could specify in the validate parameter, very useful for configuration files. If the file does not exist we could also "create" it! Usually, we would l... --- ## Search for AWS EC2 AMI ID by Region — Ansible module ec2_ami_info URL: https://www.ansiblebyexample.com/articles/search-for-aws-ec2-ami-id-by-region-ansible-module-ec2-ami-info Description: How to automate the search of an AWS EC2 machine AMI ID running the operating system RHEL-8.3.0 in the region "us-east-1" using Ansible Playbook. ## How to Search for EC2 AMI ID by AWS Region with Ansible? ## Ansible Search for EC2 AMI ID by AWS Region - `amazon.aws.ec2_ami_info` - Gather information about ec2 AMIs Let's talk about the Ansible module `ec2_ami_info`. The full name is `amazon.aws.ec2_ami_info`, which means that is part of the collection of modules to interact with AWS. The module's purpose is to gather information about ec2 AMIs. ## Parameters - filters _dictionary_ - filter terms Example: [code example] The following parameters are useful in order to Search for EC2 AMI ID by AWS Region using the module `ec2_ami_info`. The only parameter needed is the `filters` and specify the filters keys and values. For example, let's search for Red Hat Enterprise Linux machines version 8.3.0 running on HVM infrastructure, architecture x86_64 Hourly paid. ## Links - `amazon.aws.ec2_ami_info` ## Playbook How to Search for EC2 AMI ID by AWS Region with Ansible. I'm going to show you how to Gather Information on a specific "`RHEL-8.3.0_HVM`" AWS EC2 Hourly Machine for the region "us-east-1" and select the EC2 AMI ID using Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] code with ❤️ in GitHub ## Conclusion Now you know how to Search for EC2 AMI ID by AWS Region with Ansible. --- ## Send Email Notifications with Ansible — community.general.mail URL: https://www.ansiblebyexample.com/articles/streamlining-notifications-with-ansible-sending-email-reports Description: Send email reports and alerts with Ansible using community.general.mail. Gmail SMTP setup, HTML emails, attachments, failure notifications. ## Introduction Ansible can send email notifications using the `community.general.mail` module — for deployment reports, error alerts, job completion summaries, and scheduled status updates. This article covers Gmail SMTP setup, HTML emails, attachments, conditional failure alerts, and securing credentials with Ansible Vault. ## Prerequisites Install the `community.general` collection: [code example] ## Basic Email [code example] ## Module Parameters | Parameter | Required | Default | Description | |---|---|---|---| | `host` | No | `localhost` | SMTP server hostname | | `port` | No | `25` | SMTP port (587 for TLS, 465 for SSL) | | `username` | No | — | SMTP authentication username | | `password` | No | — | SMTP authentication password | | `to` | Yes | — | Recipient(s) — string or list | | `cc` | No | — | CC recipients | | `bcc` | No | — | BCC recipients | | `from` | No | `root` | Sender address | | `subject` | Yes | — | Email subject line | | `body` | No | — | Email body content | | `subtype` | No | `plain` | `plain` or `html` | | `attach` | No | — | File paths to attach | | `headers` | No | — | Custom email headers | | `charset` | No | `utf-8` | Character encoding | | `secure` | No | `starttls` | `always`, `never`, `starttls`, `try` | | `timeout` | No | `20` | Connection timeout in seconds | ## Gmail SMTP Setup ### App Password (Required for Gmail) Gmail requires an App Password when 2FA is enabled: 1. Go to Google Account Security 2. Enable 2-Step Verification 3... --- ## Set Execute Permission (a+x) on Linux File Using Ansible URL: https://www.ansiblebyexample.com/articles/add-execute-permission-755-linux-file-ansible-module-file Description: Learn how to set execute permissions (a+x) on a Linux file using an Ansible playbook. Follow this guide for easy automation with the Ansible file module. ## How to Add Execute Permission 755 on Linux file with Ansible? ## Ansible Add Execute Permission - `ansible.builtin.file` - Manage files and file properties Today we're talking about the Ansible module `file`. The full name is `ansible.builtin.file`, which means that is part of the collection of modules "`builtin`" with ansible and shipped with it. It's a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties. For Windows targets, use the `ansible.windows.win_file` module instead. ## Main Parameters - `path` _string_ (dest, name) - file path - `owner` _string_ - user - `group` _string_ - group - `mode` _raw_ - Ex: '`0644`' or '`u=rw,g=r,o=r`' - `state` _string_ - `file`, `absent`, `directory`, `hard`, `link`, `touch` - setype/seuser/selevel - SELinux This module has some parameters to perform any tasks. The only required is "`path`", where you specify the filesystem path of the file you're going to edit. The parameter "`owner`" set the user that should own the file/directory. The parameter "`group`" set the group that should own the file/directory. The parameter "`mode`" set the permissions in the UNIX way of the file/directory. The state defines the type of object we are modifying, the default is "file" but we could handle also directories, hard links, symlinks, or only update the access time with the "`touch`" option. Let me also highlight that we could also specify the SELinux properties. ... --- ## Set remote environment per task or play — Ansible environment statement URL: https://www.ansiblebyexample.com/articles/set-remote-environment-per-task-or-play-ansible-environment-statement Description: How to set an EXAMPLE environmental variable at play and task Ansible Playbook code level and verify with echo Linux command. ## How to set remote environment per Ansible task or play? ## Set remote environment per Ansible task or play - `environment` statement You could set the remote environment with the Ansible statement `environment`. The `environment` statement could be applied at the task level or play level. It's very useful to set for example proxy in a corporate environment. ## Links - Setting the remote environment ## Playbook Set environment per Ansible Playbook task or play level. ### code [code example] ### execution You need to run the playbook with the verbose option (`-v`) in order to see the standard output on the console. [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to set remote environment per Ansible task or play. --- ## Set System-Wide Environment Variables on Linux with Ansible URL: https://www.ansiblebyexample.com/articles/permanently-set-remote-system-wide-environment-variables-on-linux-ansible-module-lineinfile Description: Learn to set system-wide environment variables on remote Linux systems using Ansible. Follow this guide for a live Playbook and simple Ansible code. ## How to permanently set system-wide environment variables on remote Linux with Ansible? ## Permanently Set System-Wide Environment Variables on Remote Linux - /etc/environment - /etc/profile.d directory There are principally two ways to configure System-Wide Environment Variables on Linux: - `/etc/environment` is a system-wide configuration file, which means it is used by all users. It is owned by root so you need admin user privilege or sudo to modify it. Specifically, this file stores the system-wide locale and path settings. - `/etc/profile` and `/etc/profile.d/*.sh` are the global initialization scripts. This file gets executed whenever a bash login shell is entered via console, terminal, ssh, or graphical user interface. The global scripts get executed before the user-specific scripts though, and the main `/etc/profile` executes all the `*.sh` scripts in `/etc/profile.d/` just before it exits. Each user could customize their `~/.profile`, the user's personal shell initialization scripts. Every user has one and can edit their file without affecting others. This is the equivalent to `/etc/profile` for each user. ## Links - ansible.builtin.lineinfile ## Playbook How to permanently set System-Wide Environment variables on Remote Linux with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now y... --- ## Set the SELinux Policy States and Modes on Linux — Ansible module selinux URL: https://www.ansiblebyexample.com/articles/set-the-selinux-policy-states-and-modes-on-linux-ansible-module-selinux Description: How to automate the setting and verification of the "enforcing" SELinux mode and state with "targeted" policy and relabel the filesystem if necessary. ## How to Set the SELinux Policy States and Modes on Linux with Ansible? ## SELinux Modes and States - `enforcing` - enabled, load security policy "targeted" and active - `permissive` - enabled, load security policy, log, don't deny - `disabled` - disabled, not load security policy ## What is SELinux? Security-Enhanced Linux (SELinux) is a Linux kernel security module that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC). Let's quickly Conclusion the three SELinux Modes: enforcing, permissive and disabled. The "enforce" mode is recommended, SELinux is enabled and fully operates. It applies the security policy to the entire system. Please note that in this mode SELinux is expected to deny some actions that don't complain about the security policy. You could choose the name of the security policy, most distributions use the "targeted" security policy out-of-the-box. It's the recommended option for production systems. The "permissive" mode is someway in the middle, SELinux is enabled and load the security policy. It labels objects and emits access denial entries in the logs, but it does not actually deny any operations. This mode is useful in the development and debugging. The "disabled" mode completely disables the SELinux system. This option is discouraged. More advanced user ser set the system running in enforcing mode but individual domain as permissive. ## Ansible set the SELinux Policy States and Modes on L... --- ## Set Up Apache Vhost on Debian with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/deploy-a-web-server-apache-httpd-virtualhost-on-debian-like-systems-ansible-modules-apt-copy-service-and-ufw Description: Learn to configure an Apache virtual host on Debian using Ansible. Automate web server setup, document root creation, and firewall rules. ## How to deploy a webserver apache httpd virtual host on Debian-like systems with Ansible? ## Deploy a web server apache httpd virtual host on Debian-like systems - install packages => ansible.builtin.apt - document root => ansible.builtin.file - custom index.html => ansible.builtin.copy - Apache virtualhost => ansible.builtin.template - enable new site => ansible.builtin.command - open firewall => community.general.ufw - reload service => ansible.builtin.service Today we're talking about how to Deploy a web server apache httpd on Debian-like Linux systems. The full process requires seven steps that you could automate with different Ansible modules. Firstly you need to install the `apache2` package and dependency using the `ansible.builtin.apt` Ansible module. Secondly, you need to create the document root with the right permission with the `ansible.builtin.file` module. Thirsty, you need to create the custom index.html with the `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Fourthly, you need to set up Apache configuration for the specific virtual host using the `ansible.builtin.template` module. Fifty, you need to enable a new site using the `a2ensite` via the `ansible.builtin.command` module. Sixty, you need to start the `apache2` service and enable it on boot and all the dependant using the `ansible.builtin.service` Ansible module. Seventy you need to open the relevant firewall service-related ports using the `community... --- ## Set Up Apache Webserver on Debian with Ansible Playbook URL: https://www.ansiblebyexample.com/articles/deploy-a-web-server-apache-httpd-on-debian-like-systems-ansible-modules-apt-copy-service-and-ufw Description: Learn to deploy and configure an Apache web server on Debian using Ansible. Automate installation, custom index.html setup, and firewall rules. How to deploy a webserver apache httpd on Debian-like systems with Ansible? ## Deploy a web server apache httpd on Debian-like systems - install packages => `ansible.builtin.apt` - custom index.html => `ansible.builtin.copy` - start service => `ansible.builtin.service` - open firewall => `community.general.ufw` Today we're talking about how to Deploy a web server apache httpd on Debian-like Linux systems. The full process requires six steps that you could automate with different Ansible modules. Firstly you need to install the `apache2` package and dependency using the `ansible.builtin.apt` Ansible module. Secondly, you need to create the custom index.html with `ansible.builtin.copy` Ansible module. You could upgrade this step using the `template` module. Thirsty you need to start the `apache2` service and enable it on boot and all the dependant using the `ansible.builtin.service` Ansible module. Fourthly you need to open the relevant firewall service-related ports using the `community.general.ufw` Ansible module. ## Playbook How to deploy a web server apache httpd on Debian-like systems with Ansible Playbook. ### code [code example] ### execution [code example] ### idempotency [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to deploy a webserver apache httpd on Debian-like systems with Ansible. --- ## Setting Up Neo4j GenAI Environment on Fedora Using Ansible URL: https://www.ansiblebyexample.com/articles/setting-up-neo4j-genai-environment-on-fedora-using-ansible Description: Learn how to set up a Neo4j GenAI environment on Fedora using Ansible, including full-text and vector indexing, and OpenAI integration ## Setting Up a Neo4j GenAI Environment on Fedora In this article, we will walk through the steps to set up a Neo4j GenAI Python environment on a Fedora system using Ansible automation. This setup will enable you to deploy a Retrieval-Augmented Generation (RAG) system that integrates with a Neo4j graph database and utilizes OpenAI’s language models for interactive data retrieval and analysis. ### Prerequisites Before starting, ensure you have: - A Fedora system with root access. - Ansible installed on your control machine. - Access to the OpenAI API and a valid API key. - Credentials and URI for your Neo4j database. Additionally, we will be using the Northwind dataset to populate our Neo4j database. For more information on importing the Northwind dataset into Neo4j, refer to the Northwind Dataset Guide. ## Step-by-Step Setup 1. **Create an Ansible Playbook** Create a file named `setup_neo4j_genai.yml` with the following content: [code example] This playbook automates the setup of the Neo4j GenAI environment by installing necessary packages, configuring environment variables, and deploying the application. 2. **Define Variables** Create a variables file named `servers.yml` to store sensitive information. Ensure to replace the values with your actual credentials. [code example] **Note:** Replace sensitive values like the Neo4j URI, credentials, and OpenAI API key with placeholders or secure vault mechanisms in a production environment. Follow this... --- ## Simplify Ansible Output with the community.general.dense Callback Plugin URL: https://www.ansiblebyexample.com/articles/simplify-ansible-output-with-the-community-general-dense-callback-plugin Description: Learn how to reduce verbosity in Ansible output using callback plugins, enhancing efficiency and integration in large-scale automation tasks. ## Introduction Ansible, an open-source automation tool, simplifies complex IT tasks by orchestrating configuration management, application deployment, and task automation. One of the essential features of Ansible is its ability to provide feedback on the tasks it performs through output messages. In certain scenarios, especially when dealing with large-scale automation or integrating Ansible with other tools, reducing the verbosity of the output becomes crucial. This is where Ansible callback plugins come into play. ## Understanding Ansible Inventory and Playbooks Before diving into callback plugins, let's quickly revisit the basic components of an Ansible setup: the inventory file and playbooks. ### Inventory The inventory file defines the hosts on which Ansible will perform tasks. In the example, we see a simple inventory file with the localhost defined as the target host. [code example] ### Playbook (ping.yml) A playbook is a YAML file that outlines a set of tasks to be executed on specified hosts. In this example, we have a playbook named `ping.yml` that tests the connection to the hosts using the Ansible ping module. [code example] ### Ansible Configuration (ansible.cfg) The Ansible configuration file (`ansible.cfg`) allows users to customize various settings. In this case, the configuration includes a callback plugin configuration to control the output verbosity. [code example] ## Introducing community.general.dense Callback Plugin The `community.general.den... --- ## Simplify Disk Management with Ansible Quota Module URL: https://www.ansiblebyexample.com/articles/simplify-disk-management-with-ansible-quota-module Description: Learn how to use the Ansible quota module to automate disk space quotas for users and groups, ensuring efficient resource management. Managing disk usage quotas is critical for ensuring fair resource allocation in shared environments like multi-user servers or DevOps pipelines. Although Ansible doesn't have a dedicated `quota` module, it remains a powerful tool for automating disk quota management using alternative modules and techniques. In this article, we’ll explore practical ways to manage disk quotas with Ansible. --- ## What Are Disk Quotas? Disk quotas are limits set on the amount of disk space or inodes that a user or group can use on a filesystem. They are essential for: - **Preventing Resource Hoarding**: Ensures no single user consumes excessive disk space. - **Maintaining System Performance**: Prevents systems from becoming sluggish due to storage overuse. - **Enforcing Compliance**: Helps adhere to organizational storage policies. Linux provides tools like `quota` and `xfs_quota` to manage disk quotas. While Ansible lacks a specific quota module, you can leverage its capabilities to automate quota-related tasks. --- ## Automating Quota Management with Ansible ### 1. Enable Quotas on the Filesystem Before managing quotas, you must enable them on the target filesystem. For ext4 filesystems: [code example] For XFS filesystems: [code example] In Ansible, you can automate this process: [code example] --- ## Playbook: Manage XFS Quotas for User and Group `devops` Here’s an example playbook where both the user and group are named `devops`. It configures quotas for the user `devops` an... --- ## Simplifying Ansible Output with the community.general.unixy Callback Plugin URL: https://www.ansiblebyexample.com/articles/simplifying-ansible-output-with-the-community-general-unixy-callback-plugin Description: Learn how to enhance Ansible playbook readability by using the community.general.unixy callback plugin for cleaner and more concise output. ## Introduction Ansible is a powerful open-source automation tool that simplifies configuration management, application deployment, and task automation. When running Ansible playbooks, the default output can sometimes be overwhelming, especially when dealing with a large number of hosts and tasks. The `community.general.unixy` callback plugin offers a condensed and readable format for Ansible output, resembling the familiar style of LINUX/UNIX startup logs. ## Understanding Callback Plugins Callback plugins in Ansible allow you to customize and enhance the output generated during playbook execution. The `community.general.unixy` callback plugin is a stdout callback, meaning it alters the standard output format of Ansible when running playbooks. ## Configuration Setup To enable the `community.general.unixy` callback plugin, you need to make a few configurations in your Ansible setup. In the `ansible.cfg` file, add the following lines under the `[defaults]` section: [code example] This ensures that the `community.general.unixy` callback plugin is activated and set as the stdout callback. ## Example Playbook Let's consider a simple Ansible playbook named `ping.yml` that utilizes the `ansible.builtin.ping` module to test the connection to all hosts: [code example] In the provided inventory file (`inventory`), the connection is set to local: [code example] ## Running Playbooks Without and With Unixy Callback ### Without Unixy: [code example] The default output migh... --- ## Speed Up Ansible Playbooks — 10 Performance Tips URL: https://www.ansiblebyexample.com/articles/10-ways-to-speed-up-your-ansible-playbooks Description: Make Ansible playbooks faster with pipelining, mitogen, async tasks, fact caching, free strategy, and SSH multiplexing. Benchmarks and examples. ## Introduction Slow Ansible playbooks waste time and delay deployments. A playbook that takes 30 minutes could run in 5 minutes with the right optimizations. Whether you manage 10 servers or 10,000, performance tuning is essential. This guide covers 10 proven methods to speed up Ansible playbooks, from quick ansible.cfg tweaks to architectural changes that dramatically reduce execution time. ## 1. Measure Before Optimizing (Callback Plugins) Before optimizing, identify what's actually slow. Enable timing callback plugins in `ansible.cfg`: [code example] **Output example:** [code example] Now you know exactly where to focus your optimization efforts. ## 2. Disable Fact Gathering Fact gathering (`setup` module) runs on every play by default and takes 2-10 seconds per host. If you don't use `ansible_facts`, disable it: [code example] ### Selective Fact Gathering If you only need specific facts, gather a subset: [code example] ### Fact Caching If you need facts across multiple plays, cache them instead of re-gathering: [code example] With `gathering = smart`, Ansible only gathers facts if they're not in the cache. ## 3. Increase Parallelism (Forks) The `forks` setting controls how many hosts Ansible manages simultaneously. Default is 5 — far too low for most environments: [code example] **Guidelines:** | Environment | Recommended Forks | |-------------|-------------------| | Laptop/Dev | 10-20 | | CI/CD server | 30-50 | | Dedicated Ansible controller | 50-10... --- ## SSH Unknown Error in Ansible: Causes and Fixes URL: https://www.ansiblebyexample.com/articles/ssh-unknown-error-in-ansible-causes-and-fixes Description: Fix the SSH 'unknown error' when connecting to hosts on port 22 with Ansible. Covers common causes: key issues, firewall rules, DNS resolution, and SSH. ## The Error [code example] This means Ansible's SSH connection to the remote host failed. The "unknown error" typically indicates a network-level problem before SSH authentication even begins. ## Common Causes and Fixes ### 1. Host is Unreachable (Network) The most common cause — the host is down or not accessible: [code example] **Fix:** Verify the host is running and network routing is correct. ### 2. Firewall Blocking Port 22 [code example] ### 3. SSH Service Not Running [code example] ### 4. DNS Resolution Failure If using hostnames instead of IPs: [code example] ### 5. Wrong SSH Port [code example] ### 6. SSH Host Key Changed [code example] [code example] ### 7. SSH Key Permission Issues [code example] ### 8. Too Many SSH Connections (MaxSessions) When managing many hosts, SSH connection limits can cause failures: [code example] [code example] ## Debugging SSH Issues ### Increase Verbosity [code example] ### Test SSH Directly [code example] ### Check Ansible SSH Arguments [code example] ## Ansible SSH Configuration Optimize your `ansible.cfg` for reliable connections: [code example] ## Quick Diagnostic Checklist 1. ✅ Can you ping the host? (`ping 192.168.1.10`) 2. ✅ Is port 22 open? (`nc -zv 192.168.1.10 22`) 3. ✅ Is SSH running? (`systemctl status sshd`) 4. ✅ Can you SSH manually? (`ssh user@host`) 5. ✅ Are permissions correct? (`ls -la ~/.ssh/`) 6. ✅ Is the firewall allowing SSH? (`ufw status`) 7. ✅ Is DNS resolving? (`nslookup hos... --- ## Standardizing Ansible Best Practices: Community Initiative with Eric Lavarde and Moritz Schönwetter URL: https://www.ansiblebyexample.com/articles/meeting-eric-lavarde-and-moritz-schonwetter-automation-architects-from-red-hat-at-ansible-community-day-berlin-2023 Description: Discover Eric Lavarde and Moritz Schönwetter's initiative to standardize Ansible best practices. Learn how to contribute and elevate your Ansible projects. ## Introduction The Ansible Community Day Berlin 2023 brought together Ansible enthusiasts from around the world to discuss, collaborate, and share insights on the automation landscape. Among the attendees were Eric Lavarde and Moritz Schönwetter, who introduced us to a remarkable project focused on standardizing Ansible best practices. ### Meet Eric Lavarde and Moritz Schönwetter Eric Lavarde and Moritz Schönwetter) are prominent figures in the Red Hat community, holding roles as Principal Architects and Managers of the Automation Community of Practice (COP). Their project, aimed at consolidating and promoting Ansible best practices, showcases their dedication to elevating Ansible's capabilities. ### Standardizing Ansible Best Practices In their insightful presentation, Eric and Moritz delved into the importance of standardizing Ansible best practices. They recognized that while individual consultants, engineers, and support personnel had their own effective methods, there was a need to establish a unified approach. This approach ensures that everyone involved in Ansible-related activities follows a common set of guidelines and practices. The initiative began by adopting GitOps principles, treating best practices as code. Collaborative efforts led to the development of a repository that encompasses best practices for Ansible. These recommendations extend beyond the scope of Ansible-Lint, addressing code organization, role structure, inventory management, and more. ### Dif... --- ## Start a VMware vSphere Virtual Machine — Ansible module vmware_guest_powerstate URL: https://www.ansiblebyexample.com/articles/start-a-vmware-vsphere-virtual-machine-ansible-module-vmware-guest-powerstate Description: How to automate the change of power state from Powered Off to Powered On of the virtual machine guest “myvm” using Ansible Playbook. ## How to Start a VMware vSphere Virtual Machine with Ansible? ## Ansible Start a VMware vSphere Virtual Machine - `community.vmware.vmware_guest_powerstate` - Manages power states of virtual machines in vCenter Let's talk about the Ansible module `vmware_guest_powerstate`. The full name is `community.vmware.vmware_guest_powerstate`, which means that is part of the collection of modules to interact with VMware, community-supported. Manages power states of virtual machines in vCenter. ## Parameters - hostname string / username string / password string / datacenter string / validate_certs boolean - connection details - state string - present / powered-off / powered-on / reboot-guest / restarted / shutdown-guest / suspended - force boolean - no/yes - answer string - A list of questions to answer, should one or more arise while waiting for the task to be complete. The following parameters are useful in order to Start a VMware vSphere Virtual Machine using the module `vmware_guest_powerstate`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the desired power state, in this case, "powered-on". You could also force the power state change using the `force` parameter, default disabled. You could also specify the reply to some `answer` that could arise whil... --- ## Steampunk Ansible Challenge: Showcase Your Playbook Writing Skills URL: https://www.ansiblebyexample.com/articles/steampunk-ansible-challenge-showcase-your-playbook-writing-skills Description: Unleash Your Ansible Expertise and Win Big in the Steampunk Ansible Challenge! Hands-on, tested examples and best practices for Steampunk Ansible Challenge. ## Introduction Are you ready to embark on an exciting journey through automation and Ansible? If you’re passionate about Ansible and love solving complex automation problems, the Steampunk Ansible Challenge is your stage to shine. In this article, we’ll dive into the details of this thrilling competition and how you can participate to test and showcase your Ansible playbook writing skills. ## How It Works The Steampunk Ansible Challenge is a series of weekly competitions designed for Ansible enthusiasts of all levels. It’s a platform where you can engage in thrilling challenges, solve intricate automation puzzles, and Playbooknstrate your prowess in crafting Ansible playbooks. ## Five Exciting Challenges Each week, participants receive an email containing all the essential details for that week’s challenge. With a total of five challenges, there’s plenty of room for you to flex your Ansible muscles. The best part? Even if you miss the official end date of a challenge, you can still take it on and compete for the grand prize. ## Precision and Speed To claim the coveted title of Grand Winner, you must master the art of balancing precision and speed. Conquering all five challenges while crafting high-quality playbooks within record time is the key to your success. However, fret not if tackling all five challenges seems daunting. The competition acknowledges and celebrates excellence at every step by recognizing the top three performers for each individual challenge. Their na... --- ## Stop a VMware vSphere Virtual Machine — Ansible module vmware_guest_powerstate URL: https://www.ansiblebyexample.com/articles/stop-a-vmware-vsphere-virtual-machine-ansible-module-vmware-guest-powerstate Description: How to automate the gracefully use guest shutdown and forcefully power off to change the power state from Powered On to Powered Off of the virtual. ## How to Stop a VMware vSphere Virtual Machine with Ansible? ## Ansible Stop a VMware vSphere Virtual Machine - `community.vmware.vmware_guest_powerstate` - Manages power states of virtual machines in vCenter Let's talk about the Ansible module `vmware_guest_powerstate`. The full name is `community.vmware.vmware_guest_powerstate`, which means that is part of the collection of modules to interact with VMware, community-supported. It manages power states of virtual machines in vCenter. ## Parameters - hostname string / username string / password string / datacenter string / validate_certs boolean - connection details - state string - present / powered-off / powered-on / reboot-guest / restarted / shutdown-guest / suspended - force boolean - no/yes - answer string - A list of questions to answer, should one or more arise while waiting for the task to be complete. The following parameters are useful in order to Start a VMware vSphere Virtual Machine using the module `vmware_guest_powerstate`. First of all, we need to establish the connection with VMware vSphere or VMware vCenter using a plethora of self-explicative parameters: `hostname`, `username`, `password`, `datacenter`, and `validate_certs`. Once the connection is successfully established you could specify the desired power state, in this case "shutdown-guest" to gracefully ask the guest operating system to shutdown or "powered-off" to turn off the virtual machine guest. You could also force the power state to change... --- ## Streamline Ansible Development with Auto-Fixing FCQN Violations URL: https://www.ansiblebyexample.com/articles/streamline-your-ansible-development-with-auto-fixing-of-fcqn-rule-violations-using-ansible-lint Description: Learn how to use ansible-lint to automatically fix FCQN rule violations in Ansible playbooks, ensuring consistent, high-quality automation code. Streamline Your Ansible Development with Auto-Fixing of FCQN Rule Violations using Ansible-Lint. FCQN stands for Fully Qualified Collection Name. In Ansible, collections are a way to organize and distribute roles, modules, and plugins. The FCQN is a naming convention that specifies the full name of a collection, including the author's namespace, the collection name, and the version number. The purpose of using FCQN is to avoid naming conflicts between different collections, especially when collections are distributed across multiple namespaces. Ansible-lint checks for FCQN rule violations in Ansible playbooks to ensure that collections are referenced with their fully qualified names to avoid ambiguity and naming conflicts. As IT infrastructure management becomes more complex, many organizations turn to automation tools such as Ansible to help manage their systems more efficiently. Ansible playbooks provide a powerful toolset for automating system management tasks. However, as playbooks become more complex, maintaining their quality can become a daunting task. This is where `ansible-lint` comes in. The `ansible-lint` is a powerful linting tool for Ansible playbooks, roles, and collections. It checks for issues that may cause problems when executing Ansible tasks, such as syntax errors, indentation problems, or deprecated features. Recently, Ansible-Lint has added a new feature that allows auto-fixing of FCQN (Fully Qualified Collection Name) rule violations in Ansible playb... --- ## Streamline Vulnerability Scanning with Ansible and Terrapin Scanner URL: https://www.ansiblebyexample.com/articles/automating-vulnerability-assessment-with-terrapin-scanner-using-ansible Description: Learn how to use Ansible to automate the deployment and execution of the Terrapin Vulnerability Scanner. This guide walks through an Ansible playbook. ## Introduction In the rapidly evolving landscape of cybersecurity, regular vulnerability assessments are essential to identify and mitigate potential security risks. The Terrapin Vulnerability Scanner, developed by the RUB-NDS research group, offers a powerful tool for scanning and evaluating the security posture of systems. In this article, we explore how Ansible, a popular automation tool, can be leveraged to streamline the process of deploying and executing the Terrapin Scanner. ## Understanding the Ansible Playbook The provided Ansible playbook is a set of instructions written in YAML format, defining a sequence of tasks to be executed on remote hosts. Let’s break down the key components of the playbook: [code example] ## Explanation of the Playbook - `hosts: all`: Specifies that the tasks will be executed on all hosts. - `gather_facts: false`: Disables the gathering of facts about the target hosts. Facts include information about the system, such as IP address, OS version, etc. - `vars`: Defines variables used throughout the playbook, such as the scanner name, target host, version, download URL, destination directory, and command-line parameters. - `tasks`: Describes a series of tasks to be executed in order. - Download the scanner: Uses the `get_url` Ansible module to download the Terrapin Scanner from the specified URL and save it to the destination directory. - Set scanner execution permission: Uses the `file` Ansible module to set the execution permission for ... --- ## Streamlining Dell Computers Service Tag Management with Ansible URL: https://www.ansiblebyexample.com/articles/streamlining-dell-computers-service-tag-management-with-ansible Description: Discover how to use Ansible to automate Dell computer service tag retrieval and management. Simplify IT asset tracking and system identification. A **Dell computer service tag** is a unique identifier used to track, manage, and service Dell systems. When combined with **Ansible automation**, managing these service tags becomes faster, more efficient, and highly scalable, making it easier to maintain IT infrastructure. --- ## What is a Dell Computers Service Tag? The **service tag** is a unique alphanumeric code assigned to every Dell computer or server. It is used for: - **Asset Identification**: Helps IT teams track and manage devices. - **Warranty Checks**: Simplifies warranty and support service lookups. - **System Configuration**: Identifies device-specific hardware and software configurations. By integrating Ansible into service tag management, you can automate tasks like retrieving tags, updating inventories, and verifying warranty statuses. --- ## Why Use Ansible for Dell Service Tag Management? - **Automation**: Avoid manual checks by automating service tag retrieval. - **Consistency**: Ensure uniform workflows for hardware tracking. - **Scalability**: Manage service tags across hundreds or thousands of systems effortlessly. - **Efficiency**: Save time by automating repetitive tasks like inventory updates. --- ## How to Retrieve and Manage Dell Service Tags ### Manual Steps 1. **Locate the Service Tag**: - On desktops and laptops, check the label on the underside or back of the device. - On servers, find it on the front panel or through the iDRAC interface. 2. **Use Command-Line Tools**: - F... --- ## Strengthening Security: Automating CIS Benchmark Hardening for RHEL 9 with Ansible URL: https://www.ansiblebyexample.com/articles/automating-cis-benchmark-hardening-for-rhel-9-with-ansible Description: Automate CIS Benchmark hardening for RHEL 9 using Ansible with the Ansible Lockdown roles, ensuring robust security configurations across systems. ## CIS Benchmark In today’s cybersecurity landscape, hardening your systems is crucial to protect against evolving threats. Compliance with industry standards, such as the Center for Internet Security (CIS) benchmarks, helps organizations establish a secure foundation for their IT infrastructure. Red Hat Enterprise Linux (RHEL) 9 is a widely adopted operating system known for its stability and security features. By combining the power of RHEL 9 with Ansible automation, you can automate the implementation of CIS Benchmark guidelines, ensuring a robust and hardened system. This article will explore how to automate the hardening process using Ansible and the CIS Benchmark for RHEL 9. Automating the implementation of CIS benchmarks with Ansible provides several key benefits: 1. Standardization and Consistency: Implementing CIS benchmarks manually across multiple systems can be a complex and time-consuming task. Organizations can ensure standardized security configurations across their infrastructure by automating this process with Ansible. Ansible’s declarative language allows for consistently applying security controls, minimizing human errors, and ensuring adherence to the CIS benchmark guidelines. 2. Time and Resource Efficiency: Manually implementing CIS benchmarks on each system can be a labor-intensive process. Ansible automation significantly reduces the time and effort required to apply security configurations. With a single playbook, organizations can automate the har... --- ## Submit a GET request to a REST API endpoint — Interact with web services — Ansible module uri URL: https://www.ansiblebyexample.com/articles/submit-a-get-request-to-a-rest-api-endpoint-interact-with-web-services-ansible-module-uri Description: How to retrieve a JSON list of users via a GET request to a REST API web service HTTPS endpoint from a remote Linux host in a few lines of Ansible code. ## How to submit a GET request to a REST API endpoint with Ansible? ## Ansible submits a GET request to a REST API endpoint - ansible.builtin.uri - Interacts with web services supports Digest, Basic, and WSSE HTTP authentication mechanisms Today we're talking about Ansible module `uri`. The full name is `ansible.builtin.uri`, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years and it works in a different variety of POSIX operating systems. It interacts with web services and supports Digest, Basic, and WSSE HTTP authentication mechanisms. If you need to download content, use the Ansible `ansible.builtin.get_url` module. For Windows targets, use the `ansible.windows.win_uri` module instead. ## Parameters - url string - (http|https)://host.domain[:port]/path - method string - "GET", "POST", "PUT", "PATCH", "DELETE" - user (url_username), password (url_password) string - username, password credentials - force_basic_auth boolean - no,yes - Basic authentication header - status_code list/integer - [200, 202] - headers dictionary - custom HTTP headers, Content-Type - body_format string - raw, json, `form-urlencoded`,` form-multipart` - body raw - request body - return_content boolean - no/yes - return the body of the response - timeout integer - 30 seconds This module has some parameters to perform any tasks. The only required is "`url`", where you specify the API URL. The parameter "met... --- ## Task Manager in macOS X with Ansible Automation URL: https://www.ansiblebyexample.com/articles/task-manager-in-macos-x-with-ansible-automation Description: Learn how to use the macOS X Task Manager to monitor and control processes. Automate process management and monitoring with Ansible for efficiency. The **Task Manager** in macOS X, commonly referred to as **Activity Monitor**, is a powerful tool to monitor and manage system processes. Paired with **Ansible automation**, you can efficiently control, monitor, and optimize system performance on macOS devices at scale. --- ## What is the Task Manager in macOS X? In macOS X, the **Activity Monitor** serves as the Task Manager equivalent. It provides insights into: - **CPU Usage**: Shows processes consuming CPU resources. - **Memory Usage**: Displays how RAM is allocated. - **Energy Usage**: Monitors power consumption of apps. - **Disk Activity**: Tracks data read/write rates. - **Network Usage**: Reports on data sent and received. With **Ansible**, you can automate common Activity Monitor tasks like terminating processes, monitoring resource usage, and gathering system metrics. --- ## Why Use Ansible with Task Manager in macOS? - **Automation at Scale**: Manage processes across multiple macOS devices programmatically. - **Consistency**: Standardize task execution and monitoring using reusable Ansible playbooks. - **Efficiency**: Save time by automating repetitive tasks like process checks or system health reports. - **Remote Management**: Execute commands and monitor systems remotely. --- ## How to Use the Task Manager in macOS ### Manual Steps 1. **Access Activity Monitor**: - Open Spotlight (`Cmd + Space`) and type "Activity Monitor". - Navigate through tabs to monitor CPU, memory, energy, disk, and network ... --- ## Terrapin Attack Breaking Down SSH Security URL: https://www.ansiblebyexample.com/articles/terrapin-attack-breaking-down-ssh-security Description: Navigating the Terrapin Attack Landscape — Understanding, Detecting, and Mitigating SSH Vulnerabilities. Tested, copy-paste examples included. ## Introduction SSH (Secure Shell) serves as a crucial internet standard, providing secure access to network services, including remote terminal login and file transfer across organizational networks and over 15 million servers on the open internet. ## Terrapin Attack Overview The Terrapin attack, a prefix truncation assault on the SSH protocol, disrupts the integrity of the secure channel by manipulating sequence numbers during the handshake. This manipulation allows an attacker to remove messages at the channel’s initiation, downgrading connection security by truncating extension negotiation messages. Such truncation can compromise client authentication algorithms and deactivate specific countermeasures in OpenSSH 9.5. ## Implementation Flaws and Exploitation Terrapin extends its impact by exploiting implementation flaws. Weaknesses in the AsyncSSH servers’ state machine enable attackers to sign a victim’s client into another account unnoticed, potentially granting Man-in-the-Middle capabilities within encrypted sessions and facilitating strong phishing attacks. ## Practical Considerations To execute the Terrapin attack, a Man-in-the-Middle attacker with network layer interception capabilities is required. The connection must be secured using ChaCha20-Poly1305 or CBC with Encrypt-then-MAC, a configuration found in the majority of real-world SSH sessions according to a comprehensive scan. ## Vulnerability Scanner A vulnerability scanner, provided in Go, enables users to ... --- ## The best book about Ansible For Linux URL: https://www.ansiblebyexample.com/articles/the-best-book-about-ansible-for-linux Description: The best book and video course for learning Ansible on Linux operating systems, covering RedHat-like, Debian-like, SUSE-like, ArchLinux, and Gentoo. # The best book about Ansible For Linux ## Introduction The best book about Ansible For Linux. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of The best book about Ansible For Linux requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Us... --- ## The Best Udemy Courses for Ansible in Network Automation URL: https://www.ansiblebyexample.com/articles/the-best-udemy-courses-for-ansible-in-network-automation Description: Unlock the power of network automation with top-rated Udemy courses. Master Ansible and Python to automate network tasks efficiently and effectively. ## Introduction In today's rapidly evolving technological landscape, network automation has become an essential skill for network engineers and IT professionals. Automation not only streamlines repetitive tasks but also enhances network efficiency, reduces errors, and saves valuable time. Ansible, a powerful open-source automation tool, has gained significant popularity for its simplicity and effectiveness in automating network tasks. If you're looking to master Ansible for network automation, Udemy offers some exceptional courses to help you achieve your goals. ### 1\. Master Network Automation with Python for Network Engineers Learn the Master Network Automation with Python for Network Engineers on Udemy. *Instructors: Andrei Dumitrescu and Crystal Mind Academy* This comprehensive Udemy course is a fantastic resource for individuals looking to dive deep into network automation with Ansible. It caters to both beginners and experienced developers, making it suitable for a wide range of learners. The course focuses on real-life Python and Ansible automation applications, covering various aspects like SSH, Paramiko, Netmiko, Napalm, Telnet, and Ansible. What sets this course apart is its inclusivity. You don't need prior Python knowledge to enroll. The instructors take you through general Python programming topics, ensuring you have a solid foundation before delving into network automation specifics. Throughout the course, you'll work on hands-on projects that simulate r... --- ## The Best Wireless Mouse for Keyboard Users: An Ansible Automation Approach URL: https://www.ansiblebyexample.com/articles/wireless-mouse-for-keyboard Description: Find the perfect wireless mouse for keyboard users. Learn how to choose, pair, and automate device configurations using Ansible for efficiency. A **wireless mouse** is a vital companion for keyboard users, enhancing productivity, ergonomics, and convenience. Coupling these devices with **Ansible automation** allows you to simplify setup, configuration, and management of wireless peripherals across multiple systems. --- ## Why Choose a Wireless Mouse for Keyboard Users? A wireless mouse designed with keyboard users in mind offers: - **Ergonomic Design**: Reduces strain during prolonged use. - **Seamless Connectivity**: Integrates smoothly with keyboards for a clutter-free workspace. - **Customizable Buttons**: Speeds up repetitive tasks with programmable inputs. - **Portability**: Ideal for users on the go. --- ## Automating Wireless Mouse Management with Ansible ### Benefits of Using Ansible for Peripheral Management 1. **Automation**: Configure wireless mouse and keyboard setups across multiple systems effortlessly. 2. **Scalability**: Manage devices in large-scale environments like offices or labs. 3. **Consistency**: Apply uniform settings, such as DPI, polling rates, or button mappings. 4. **Error Reduction**: Minimize manual errors in device configuration. --- ## How to Set Up a Wireless Mouse for Keyboard Users ### Manual Steps 1. **Choose the Right Wireless Mouse**: - Look for ergonomic designs, adjustable DPI settings, and compatibility with your operating system. - Popular options include Logitech MX Master, Razer Pro Click, and Microsoft Surface Precision Mouse. 2. **Pair the Mouse**: - U... --- ## The New Ansible Community Website Preview URL: https://www.ansiblebyexample.com/articles/the-new-ansible-community-website-preview Description: An Inside Look at the Ansible Community's Holiday Surprise: Navigating the Transformative Journey of ansible.com. Tested, copy-paste examples included. ## Introduction As the holiday season approaches, the Ansible community has been busy working on a delightful gift for its users - a brand new website! This article aims to provide a sneak peek into the progress made on the Ansible community website, highlighting key features, contributors, and the community's collaborative spirit. ## Nikola: The Chosen One The Ansible community's decision to use Nikola as the static site generator has proven to be a stellar choice. This decision was reached through a community vote, as documented in the GitHub repository (https://github.com/ansible-community/community-topics/issues/210). Nikola has not only met but exceeded expectations, thanks to its flexibility and ease of use. The community expresses gratitude for the collective effort that went into making this decision and the subsequent success of the website. ## Homepage Wireframe and Layout One of the early milestones achieved was the implementation of the wireframe for the homepage layout. Tina Yip, a notable contributor, played a crucial role in this phase of development (https://github.com/ansible-community/community-website/issues/57). The collaboration and input from community members have been invaluable in shaping the website's user interface and overall design. ## WCAG Compliance Testing Ensuring inclusivity and accessibility for all users is a top priority for the Ansible community. Extensive testing for Web Content Accessibility Guidelines (WCAG) compliance has been ... --- ## The run_once statement in Ansible URL: https://www.ansiblebyexample.com/articles/the-run-once-statement-in-ansible Description: Learn how to use run_once in Ansible at play and task levels. Understand why run_once may behave differently when strategy is set to free, with. ## Introduction Ansible's `run_once` directive is a deceptively simple feature that can dramatically improve playbook efficiency. While it appears straightforward — "run this task only once" — its interaction with variables, delegation, strategies, and serial execution makes it one of Ansible's most powerful optimization tools. This guide covers everything you need to know about `run_once`, from basic usage to advanced patterns that can cut your playbook execution time significantly. ## What Does run_once Do? When you add `run_once: true` to a task, Ansible executes that task on only **one host** (the first host in the current batch) instead of running it on every host in the play. The key insight is that results — including registered variables — are still shared with all hosts. [code example] Even though the `date` command runs on only one host, every host in the play can access `current_date.stdout`. ## Play Level vs Task Level ### Play Level At the play level, `run_once` is equivalent to targeting only the first host: [code example] This is functionally the same as `hosts: host1` or `hosts: all[0]`. It works, but isn't particularly exciting. ### Task Level The real power of `run_once` shines at the task level, where you can mix single-execution and multi-host tasks in the same play: [code example] The download happens once, but the copy and deploy run on every host. ## run_once with register One of `run_once`'s best features is how it interacts with `regi... --- ## The Ultimate Automation Guide Books to Master Ansible URL: https://www.ansiblebyexample.com/articles/the-ultimate-automation-guide-books-to-master-ansible Description: A list of seven books to learn the automation that saves time, reduces human errors, and boosts your skill and productivity. ## Introduction Ansible, a powerful open-source automation tool, has revolutionized how IT operations are managed and streamlined. With its simple syntax and agentless architecture, Ansible is the go-to choice for automating tasks across IT environments. Whether you’re a beginner looking to get started or an experienced professional aiming to enhance your Ansible skills, choosing the right learning resources can make a significant difference. This article presents a curated list of book suggestions that will help you master Ansible and take your automation expertise to the next level. [](https://amzn.to/45ouAci) 1. “Ansible for DevOps” by Jeff Geerling: This book is a must-read for anyone interested in learning Ansible from scratch. Jeff Geerling, an experienced DevOps practitioner, provides practical insights into using Ansible for configuration management, infrastructure automation, and application deployment. The book covers essential Ansible concepts, including playbooks, roles, variables, and best practices. With real-world examples and step-by-step tutorials, readers can quickly grasp and apply Ansible’s core concepts to real projects. [](https://amzn.to/3OMbq94) 2. “Mastering Ansible” by Jesse Keating: For those who have a solid grasp of Ansible’s basics and are eager to dive deeper, “Mastering Ansible” is an excellent choice. This book delves into advanced Ansible topics, such as creating custom modules, building complex playbooks, and managing large-scale infrastru... --- ## Three options to Safely Limit Ansible Playbooks Execution to a Single Machine URL: https://www.ansiblebyexample.com/articles/three-options-to-safely-limit-ansible-playbooks-execution-to-a-single-machine Description: Three options to safely limit Ansible Playbook execution to a single machine using runtime parameters, playbook code, and variables. ## Three options to Safely Limit Ansible Playbooks Execution to a Single Machine. Today we're going to talk about the three options to limit the execution of a potentially harmful Ansible Playbook to only one host. ## Limit Ansible Playbook to only one HOSTNAME - use `--limit` at runtime - `hosts: HOSTNAME` Ansible Playbook - `hosts: "{{ HOSTS }}"` Ansible Playbook Let's deep dive into our use case to Limit Ansible Playbook to only one HOSTNAME. I'm going to show three different ways to achieve this result: using the `--limit` parameter at runtime, limit the HOSTNAME in the Playbook code and the most advanced way is to define a variable in the Ansible Playbook that you could populate on-demand. Let's discuss the pros and cons of each option. ## Playbook In the following Playbook scenarios, I'd like to execute my harmful Ansible Playbook ONLY against demo.example.com host. This is my Playbook inventory file: [code example] ## Ansible command limit option - `--limit` - `ansible-playbook - limit HOSTNAME PLAYBOOK` Using the `--limit` parameter of the `ansible-playbook` command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host. The drawback is that you should remember every time you execute the command and sometimes humans are not so reliable. ### code - playbook.yml [code example] ### execution [code example] ### wrong execution If we... --- ## Top AI Models: ChatGPT, Claude, Gemini, LLaMA in Communication URL: https://www.ansiblebyexample.com/articles/chatgpt-claude-gemini-llama Description: Discover how ChatGPT, Claude, Gemini, and LLaMA are revolutionizing communication, content creation, and research with their advanced AI capabilities. ## Introduction In the rapidly evolving world of artificial intelligence, language models have become pivotal in transforming how we communicate, create, and interact with technology. Four of the most prominent AI models in this space are ChatGPT, Claude, Gemini, and LLaMA. Each of these models brings unique strengths to the table, catering to various needs across industries. In this article, we'll explore what makes each of these AI models stand out and how they are shaping the future of AI-driven communication. ## ChatGPT: The Versatile Conversationalist Developed by OpenAI, ChatGPT has quickly become a household name in the AI community. Known for its versatility, ChatGPT excels in generating human-like text, making it a valuable tool for a wide range of applications. From casual conversation to detailed content creation, ChatGPT can handle it all. One of its key strengths is its ability to generate creative and engaging content. Whether you're drafting a blog post, brainstorming ideas, or even writing code, ChatGPT provides insightful and relevant responses. Its adaptability makes it a go-to resource for individuals and businesses looking to enhance their communication and content creation efforts. ## Claude: The Safe and Collaborative Assistant Anthropic's Claude is designed with a strong focus on safety and collaboration. In an era where ethical considerations in AI are becoming increasingly important, Claude stands out by prioritizing user safety and minimizing r... --- ## Top Tools for Writing and Testing Ansible Content Efficiently URL: https://www.ansiblebyexample.com/articles/streamline-your-ansible-development-process-with-these-essential-devtools-and-projects Description: Discover essential tools for Ansible development: VSCode extension, Language Server, Ansible-Lint, Molecule, and Ansible-Navigator for efficient. As an Ansible automation expert, I know how important it is to have efficient tools to make writing and testing Ansible content easier. The Ansible ecosystem provides many tools and resources to streamline the development process, but it can be overwhelming for newcomers to navigate. I’m excited to share some of my favorite projects and tools for creating Ansible content. ## VSCode Extension The Ansible extension for Visual Studio Code (VSCode) is an essential tool for any Ansible developer. This extension provides syntax highlighting, code completion, and other features to enhance your Ansible coding experience. It also includes support for Ansible Vault, making it easy to manage your encrypted data. ## Language Server The Ansible Language Server is a powerful tool that provides intelligent code completion, code navigation, and syntax highlighting for Ansible content. It works by analyzing your Ansible content and providing real-time feedback on syntax errors, making it easier to catch mistakes early in development. ## Ansible-Lint Ansible-Lint is a command-line tool that checks your Ansible content for common issues and errors. It enforces best practices and ensures consistency in your codebase, making it easier to maintain and collaborate on. It can be integrated into your CI/CD pipeline to catch issues before they make it to production. ## Molecule Molecule is a tool for testing Ansible roles and collections. It provides an easy-to-use testing framework to validate yo... --- ## Transforming JSON Data with Ansible and Jinja2 URL: https://www.ansiblebyexample.com/articles/transforming-json-data-with-ansible-and-jinja2 Description: Learn how to automate JSON data transformations with Ansible and Jinja2 templates. This guide walks you through a practical example, including. ## Introduction In the world of IT automation, JSON data manipulation is a common task. Whether it’s reformatting data for API consumption or simplifying configurations, efficient handling of JSON is crucial. This article delves into leveraging **Ansible** and **Jinja2 templates** to transform JSON data dynamically. We’ll tackle a specific example: renaming a JSON key while preserving the nested structure. By the end of this guide, you’ll be equipped to handle similar transformations in your automation workflows. --- ## The Problem Statement Here’s the source JSON we want to transform: [code example] The goal is to transform it into: [code example] This involves renaming the top-level key from `primary_network` to `network`, keeping the data structure intact. --- ## The Solution: Using Ansible and Jinja2 Ansible, combined with Jinja2 templates, provides a clean and reusable approach to solving this problem. ### Ansible Playbook Below is an example playbook that defines the input JSON and applies a Jinja2 template to transform it. [code example] --- ### Jinja2 Template Create a Jinja2 template named `transform_template.j2` to perform the transformation. [code example] --- ## Explanation of the Process 1. **Access the Source JSON**: - The `vars` section in the playbook defines the source JSON under the variable `source_json`. 2. **Jinja2 Transformation**: - The template accesses `primary_network` and iterates over its key-value pairs using `items... --- ## Troubleshooting: Configure User Quotas on Ansible Managed Systems URL: https://www.ansiblebyexample.com/articles/troubleshooting-configure-user-quotas-on-ansible-managed-systems Description: Learn how to resolve the error when configuring user quotas in Ansible and ensure quota management is correctly set up on your systems. ## Troubleshooting: Configure User Quotas on Ansible Managed Systems Learn how to resolve the common error related to user quota configuration using Ansible. --- ### Error Summary When attempting to configure user quotas with Ansible, you might encounter the following error: [code example] This error occurs because the file system where quotas are being configured lacks the necessary mount options to support quota management. --- ### Root Cause The file system `/` is not mounted with the options required for quotas (`uquota`, `usrquota`, `quota`, `uqnoenforce`, or `qnoenforce`). These options enable the kernel to track and enforce disk usage limits per user or group. --- ### Solution: Enable Quota Support #### 1. **Verify the Current Mount Options** Use the `mount` command to check the mount options for `/`: [code example] #### 2. **Update `/etc/fstab` to Enable Quotas** Edit the `/etc/fstab` file to include the required quota options for the root file system. For example: [code example] Replace `/dev/sda1` with the appropriate device name for your root file system. #### 3. **Remount the File System** Apply the changes by remounting the root file system: [code example] #### 4. **Initialize Quota Management** Run the following commands to set up and enable quota tracking: [code example] #### 5. **Test Quota Functionality** Ensure that quotas are working as expected: [code example] --- ### Updating Your Ansible Playbook Update your Ansible playbook to include... --- ## Two Ways to Run Multiple Ansible Handlers — Ansible Playbook URL: https://www.ansiblebyexample.com/articles/two-ways-to-run-multiple-ansible-handlers-ansible-playbook Description: Discover two methods to trigger multiple Ansible handlers based on changed status in playbooks, enhancing task execution efficiency. ## Two ways to run multiple Ansible handlers How to execute two Ansible handlers on a changed status of Ansible Playbook. ## What is an Ansible handler? > Handler runs tasks on change. Handlers execute some tasks only when the previous task returns a changed status. If not necessary, they don't execute. ## Links - https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_handlers.html ## Demo Let's jump into two real-life examples of how to run multiple Ansible handlers. First of all, we need a task changed status. The simplest Ansible module returning a "changed" status is the command module with a Linux command, like "uptime". Let's suppose we would like to execute two handlers on the screen, for example, two messages on the screen. ## Solution 1 ### code - two-1.yml [code example] - inventory [code example] ## execution [code example] ## Solution 2 ### code - two-2.yml [code example] ### execution [code example] ## Conclusion Now you know Two ways to run multiple Ansible handlers. --- ## Understanding Ansible Builtin vs Legacy Collections: Key Differences URL: https://www.ansiblebyexample.com/articles/ansible-collections-ansible-builtin-vs-ansible-legacy Description: Explore the essential differences between Ansible's ansible.builtin and ansible.legacy collections. Understand how each affects your playbooks with. What is the "ansible.builtin" Ansible collection? What is the "ansible.legacy" collection? Today we're going to talk about Ansible's most essential modules and plugins and how we can use them in our everyday Playbook. I'm Luca Berton, Ansible Automation Expert, and welcome to today's lesson. ## What is ansible.builtin collection? The "ansible.builtin" collection refers to modules & plugins shipped with ansible-core. Technically is a synthetic collection, virtually constructed by the core engine. ## What is ansible.legacy collection? The "ansible.legacy" collection is a superset of "ansible.builtin" with 'custom' plugins in the configured paths and adjacent directories. We use the "ansible.legacy" when we don't specify any Ansible collection in our playbook. Technically is a synthetic collection, virtually constructed by the core engine. ## Links - https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#what-is-the-difference-between-ansible-legacy-and-ansible-builtin-collections - https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-action-plugin-path ## Demo Live Playbook about "ansible.builtin" vs. "ansible.legacy" collections. Let's jump in a quick Playbook to demonstrate the difference between the "ansible.builtin" vs. "ansible.legacy" collections. I'm going to create a custom "debug" module that prints the extra text "foo" when used with the "msg" parameter. Let's see the different results when we execute with "ansible.builti... --- ## Understanding Quiet Hiring: The 2023 HR Trend and Ansible's Role URL: https://www.ansiblebyexample.com/articles/ansible-for-quiet-hiring Description: Discover Quiet Hiring, the latest HR trend in 2023. Learn how Ansible can empower IT professionals to adapt and thrive in evolving job markets by. ## Introduction Hello, friends. Today we are going to talk about Ansible for Quiet Hiring. So, what is Quiet Hiring? This is the newest 2023 trend in the job market. You’ve probably heard about the "Great Resignation" and "Quiet Quitting," two major trends from 2022. Now, as we face a new economic situation that is still evolving, we don’t know if it’s leading to a recession. The latest news shows that some companies, including FANG and other big IT firms, are conducting layoffs, yet the need for productivity remains high. ## What is Quiet Hiring? Quiet Hiring is a new HR trend for 2023, according to Forbes. > Quiet Hiring is when an organization hires short-term contractors or reassigns existing employees to new positions. This trend presents an opportunity to upskill ourselves and become more valuable in the job market. As IT professionals, we know how quickly technology evolves, and managing modern IT infrastructure is more critical than ever for the core business of any enterprise. IT is no longer just a support function; it’s a critical piece of the entire business operation. ## Why Ansible? Why is Ansible so important? Ansible is a powerful technology that has become a standard for interacting with cloud providers. Whether it’s AWS, Azure, Google Cloud Platform, or others like Alibaba, Tencent, or IBM, Ansible has the capabilities to manage these resources effectively—from provisioning to day-to-day operations. With Ansible, you can connect to servers, deploy ap... --- ## Understanding Split in Ansible: A Powerful Tool for Data Transformation URL: https://www.ansiblebyexample.com/articles/understanding-split-in-ansible Description: Learn to use the split filter in Ansible Playbooks for tasks like converting CSV strings to lists, extracting substrings, and splitting lists into smaller. ## Introduction Ansible is a powerful automation tool widely used in IT operations for configuration management, application deployment, and task automation. One of the lesser-known but incredibly useful features of Ansible is the "split" filter. This filter allows you to divide strings into smaller components or split lists into sublists, making it a valuable tool for data transformation and manipulation in your playbooks. In this article, we will explore the split filter in Ansible, its syntax, and various use cases. ## Understanding the Split Filter The split filter in Ansible allows you to divide a string or list into smaller elements based on a specified delimiter. You can use it to extract specific information from a string or restructure a list into more manageable parts. The syntax for using the split filter is straightforward: [code example] - `some_variable`: The variable you want to split. - `delimiter`: The character or substring used as a separator to split the variable. ## Common Use Cases ### 1. Splitting Strings: Let's say you have a string containing comma-separated values and you want to convert it into a list. Here's how you can achieve that using the split filter: [code example] In this example, the split filter takes the `csv_values` string and divides it into a list using a comma as the delimiter. ### 2. Extracting Substrings: Another useful application of the split filter is extracting substrings from a larger string. For instanc... --- ## Understanding the ansible-console Command URL: https://www.ansiblebyexample.com/articles/understanding-the-ansible-console-command Description: Master the ansible-console interactive REPL for ad-hoc commands. Run modules, manage packages, debug hosts, and test tasks in real-time without writing. ## Introduction The `ansible-console` command provides an interactive REPL (Read-Eval-Print Loop) for running Ansible modules against your inventory in real-time. It's ideal for ad-hoc tasks, debugging, and exploring hosts without writing full playbooks. ## Starting ansible-console [code example] You'll see a prompt showing your target and number of hosts: [code example] The prompt shows: `user@group (host_count)[f:forks]$` ## Basic Commands ### Ping All Hosts [code example] ### Run Shell Commands [code example] ### Gather Facts [code example] ## Switching Targets [code example] ## Change Settings [code example] ## Package Management [code example] ## File Operations [code example] ## Service Management [code example] ## User Management [code example] ## Practical Use Cases ### Quick Health Check [code example] ### Debug Connectivity Issues [code example] ### Emergency Maintenance [code example] ## Help and Tab Completion [code example] ## Exiting [code example] ## ansible-console vs ansible (ad-hoc) | Feature | ansible-console | ansible (ad-hoc) | |---------|----------------|------------------| | Interactive | ✅ REPL | ❌ One-shot | | Switch targets | ✅ `cd group` | Specify each time | | Tab completion | ✅ | ❌ | | Session state | ✅ Persistent | ❌ | | Scripting | ❌ | ✅ Pipeline-friendly | | Best for | Exploration, debugging | Scripted one-liners | ## Best Practices 1. **Test in non-production first** — commands execute immediately on all... --- ## Understanding Tokens: The Key to Smarter AI Models URL: https://www.ansiblebyexample.com/articles/understanding-tokens-the-key-to-smarter-ai-models Description: Discover how tokens are the building blocks of AI, influencing how much data models can process and how smart they can become. ## Introduction In the world of artificial intelligence (AI), tokens are often discussed but not always fully understood by those outside the technical community. Yet, they are one of the most critical elements in making AI models smarter and more efficient. If you're curious about how AI models process information and why token count matters, this article will break down the basics and explain why tokens are the building blocks of AI. ## What Are Tokens in AI? In the simplest terms, tokens are the pieces of data that AI models use to understand and generate language. When you interact with an AI model, it doesn’t process whole sentences or paragraphs as a human does. Instead, it breaks down the text into smaller units called tokens. These tokens can be individual words, subwords, or even characters, depending on the model and its design. For example, the sentence "AI is transforming the world" might be broken down into tokens like "AI," "is," "transform," "ing," "the," and "world." The AI model then processes these tokens, one by one, to understand the meaning and context of the sentence. ### Why Token Count Matters The number of tokens an AI model can handle directly affects its performance. Here’s why token count is so crucial: 1. **Understanding Context**: The more tokens an AI model can process, the better it can understand the context of the information. For example, when dealing with a long text or conversation, a higher token count allows the model to retain mo... --- ## Unlocking 2023 Cyber Monday Learning Bonanza URL: https://www.ansiblebyexample.com/articles/unlocking-2023-cyber-monday-learning-bonanza Description: Explore the best 2023 Cyber Monday deals for IT and DevOps courses. Save on Linux Foundation, Udemy, Pluralsight, KodeKloud, and HashiCorp training. Introduction ============ The 2023 post-Thanksgiving whirlwind of Black Friday and Cyber Monday is here, and the tech education sector is buzzing with incredible deals. Whether you're a seasoned IT professional looking to sharpen your skills or someone eager to venture into the world of DevOps, there's a plethora of opportunities waiting for you. In this article, we'll explore some of the most enticing Cyber Monday sales and promotions that could shape your learning journey. Linux Foundation Cyber Monday Sale --- Up to 65% OFF ================================================== - CYBER DEALS at The Linux Foundation! Up to 65% off, and a FREE GIFT with EVERY PURCHASE! Limited Time, Don't Delay! {{}} The Linux Foundation, a key player in open-source technology education, is offering up to a staggering 65% off in their Cyber Monday sale. With a countdown already underway, this is your chance to secure discounts on courses that cover a broad spectrum of technologies. The Linux Foundation is renowned for its quality content, making this deal a golden opportunity for those looking to dive deep into the world of Linux and open-source technologies. 🚨 Promo Details: ✨ 65% Off IT Professional Programs - Code: CYBER23ITPP ✨ 65% Off Power Bundles - Code: CYBER23PB ✨ 65% Off Bundles - Code: CYBER23BUN ✨ 50% Off Courses & Certifications - Code: CYBER23CC ✨ 50% Off SkillCreds - Code: CYBER23SKILLCRED ✨ 50% Off Instructor-Led Courses - Code: CYBER23ILT Pluralsight Black Friday Promo... --- ## Update Zoom flatpak(s) in Linux systems — Ansible module command URL: https://www.ansiblebyexample.com/articles/update-zoom-flatpak-in-linux-systems-ansible-module-command Description: How to automate the update of the Zoom flatpak from version 5.9.1.1380 to 5.9.6.2225 in Linux using Ansible module command. How to update Zoom flatpak in Linux systems with Ansible? ## Ansible update Zoom flatpak in Linux systems - `ansible.builtin.command` - Execute commands on targets Today we are going to talk about the Ansible module `command`. The full name is `ansible.builtin.command`, it's part of `ansible.builtin` modules maintained by the Ansible Core. The purpose of the `command` module is to Execute commands on a target system. ## Playbook How to Update Zoom flatpak in Linux systems with Ansible Playbook. ### code [code example] ### execution [code example] ### before execution [code example] ### after execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to update Zoom flatpak in Linux systems with Ansible. --- ## Upgrade Ansible on macOS — Homebrew URL: https://www.ansiblebyexample.com/articles/how-to-upgrade-ansible-on-macos-using-homebrew Description: Keeping Your Ansible Environment Up-to-Date with Homebrew Step-by-step Ansible tutorial with practical examples and best practices. ## Introduction Ansible is a powerful open-source automation tool that simplifies the management of your infrastructure through code. If you’re using Ansible on macOS and want to keep it up to date, Homebrew is a convenient package manager to help you with that. In this guide, we’ll walk you through the steps to upgrade Ansible on your macOS using Homebrew. Prerequisites: 1. Homebrew: Ensure that you have Homebrew installed on your macOS. If not, you can install it by following the instructions on the Homebrew website. 2. Terminal: You’ll need access to your macOS terminal to run the necessary commands. ## Checking the Current Version Before upgrading Ansible, it’s a good practice to check the current installed version. Open your terminal and run the following command: [code example] This command will display information about your current Ansible installation, including the version number. [code example] ## Upgrading Ansible Now that you have confirmed the current version, you can proceed with upgrading Ansible using Homebrew. Follow these steps: 1. Update Homebrew: Ensure Homebrew is up to date by running the following command: [code example] This command fetches the latest package information from Homebrew’s repository. 2. Upgrade Ansible: Upgrade Ansible to the latest version using the following command: [code example] Homebrew will automatically download the latest version of Ansible and install it on your system. If you already have the latest version insta... --- ## Upgrading Fedora Linux Using DNF System Plugin URL: https://www.ansiblebyexample.com/articles/upgrading-fedora-linux-using-dnf-system-plugin Description: Learn how to seamlessly upgrade your Fedora system using the DNF System Plugin, ensuring you stay updated with the latest features, improvements. Introduction ============ The Fedora Linux operating system is known for its frequent releases, bringing the latest features, improvements, and security updates to users. Upgrading your Fedora system is a crucial process to ensure you are benefiting from the latest advancements. In this guide, we'll explore the DNF system plugin, a powerful tool for upgrading your Fedora system seamlessly. Understanding DNF System Plugin ------------------------------- The dnf-plugin-system-upgrade is an essential component of the DNF package manager designed specifically for upgrading Fedora systems. It offers a reliable and efficient command-line method for transitioning your system to the most recent Fedora release. It's important to note that if you're using Fedora Silverblue or Fedora CoreOS, which utilize rpm-ostree, you should refer to the rpm-ostree documentation for upgrade instructions. Preparing for the Upgrade ========================= Before initiating the system-wide upgrade, it's crucial to back up your data. While the upgrade process is generally smooth, unexpected issues can arise, making data backup a necessary precaution. Downloading the Fedora Workstation Live image provides an additional safety net in case something goes wrong during the upgrade. To ensure a successful upgrade, it's recommended to perform routine system updates using the following command: [code example] This step is essential for receiving signing keys of higher-versioned releases and addressing ... --- ## Upgrading to Ansible Automation Platform 2.6 — EOL Timeline Guide URL: https://www.ansiblebyexample.com/articles/upgrading-to-ansible-automation-platform-2-6-eol-timeline-guide Description: AAP 2.4 reaches end of life June 2026. Complete upgrade timeline, Extended Update Support costs, and Red Hat Consulting's 5-phase engagement model. # Upgrading to Ansible Automation Platform 2.6 — EOL Timeline Guide ## Introduction AAP 2.4 reaches end of life June 2026. Complete upgrade timeline, Extended Update Support costs, and Red Hat Consulting's 5-phase engagement model. This article covers the key announcements, architecture decisions, and practical implications for Ansible automation teams. ## Key Highlights ### What Changed The Red Hat ecosystem continues evolving toward AI-driven, event-reactive automation. The 2026 updates focus on reducing manual intervention while maintaining governance and compliance. ### Architecture Overview [code example] ## Impact on Automation Teams | Area | Before | After | |------|--------|-------| | Incident response | Manual triage | AI-assisted diagnosis | | Playbook creation | YAML from scratch | Natural language + AI | | EE building | CLI only | Visual self-service | | Event handling | Reactive scripts | Governed pipelines | | Compliance | Periodic audits | Continuous verification | ## Getting Started [code example] ## Migration Considerations 1. **Version check** — ensure AAP 2.5+ before upgrading to 2.7 2. **PostgreSQL upgrade** — plan for PostgreSQL 13 → 17 migration 3. **Gateway architecture** — consolidate entry points 4. **Collection updates** — pin to compatible versions 5. **Training** — upskill team on EDA and MCP concepts ## Best Practices 1. **Start small** — pilot AI features with non-critical workflows 2. **Keep humans in the loop** — approval gates f... --- ## Use Ansible Vault in Ansbile Playbook — ansible vault URL: https://www.ansiblebyexample.com/articles/use-ansible-vault-in-ansbile-playbook-ansible-vault Description: Learn how to use Ansible Vault to secure sensitive data such as passwords and access keys in your playbooks with practical examples and a live Playbook. ## How to use an Ansible Vault in an Ansible Playbook? How to use an Ansible Vault to Protect Sensitive Data such as passwords, access keys, etc. I will show you a live Playbook with some simple Ansible code. ## Ansible Vault - Included in Ansible installation - `ansible-vault` command line Ansible Vault is included in every Ansible installation for the most modern operating system. It includes all the software encryption and a handy command line utility (`ansible-vault`) to encrypt, modify, change passwords or decrypt files. The encryption of the Ansible Vault files is strong and relies on the AES256 cipher. ## Links - https://docs.ansible.com/ansible/latest/user_guide/vault.html ## Playbook Use Ansible Vault in Ansible Playbook I will show you how to use Ansible Vault in Ansible Playbook to store passwords. This example uses a simple playbook that displays on screen a variable and one Ansible vault to store the variable encrypted on disk. In the real world, you can use the variable with any Ansible module without printing on the screen. ### code without Vault - playbook_without_vault.yml [code example] ### execution without Vault [code example] ### code with Vault - playbook_with_vault.yml [code example] - mypassword.yml [code example] ### execution with Vault [code example] ### execution with Vault (password forget) [code example] ### Conclusion Now you know how to use Ansible Vault in Ansible Playbook. --- ## Use Date and Time in Ansible Without Facts URL: https://www.ansiblebyexample.com/articles/using-date-time-and-timestamp-without-facts-in-ansible-playbook-ansible-date-and-lookup-plugin Description: Learn how to use date, time, and timestamp in Ansible playbooks without facts. Follow our Playbook and simple Ansible code examples for quick solutions. ## How to use Date, Time, and Timestamp without Facts in Ansible Playbook. A quick and dirty workaround using the `date` command-line utility. ## Using Date, Time, and Timestamp without Facts in Ansible Playbook Date and time - `date +%Y-%m-%d@%H:%M:%S` ISO8601 - `date --iso-8601=seconds` - `date +%Y-%m-%dT%H:%M:%S%z` How to Use the Date, Time, and Timestamp in Ansible Playbook. The `ansible_data_time` fact is an amazing resource but sometimes you can't have it or you don't want to use the date and time of the remote host. These solutions enable you to print the Date and Time and ISO8601 format. I ended up after carefully reading the `date` man page. Unfortunately not all the platforms support the `--iso-8601` parameter so you need to build it manually the format by yourself (for example in macOS operating system). ## Links - `ansible.builtin.pipe lookup plugin` - `date man page` - ISO8601 ## Playbook Let's jump into a quick live Playbook of Using Date, Time, and Timestamp in the Ansible Playbook. I'm going to share with you how to display the full `ansible_date_time ` and the ISO8601 format. ### code [code example] ### execution [code example] code with ❤️ in GitHub ## Conclusion Now you know how to use the Date, Time and Timestamp without Ansible Facts in Ansible Playbook. --- ## User password expiration — Ansible module user URL: https://www.ansiblebyexample.com/articles/user-password-expiration-ansible-module-user Description: Learn how to set user password expiration time on Linux with Ansible. Join Luca Berton in a live Playbook using the Ansible `ansible.builtin.user`. ## How to set user password expiration time on Linux with Ansible? ## Ansible user password expiration - ansible.builtin.user - Manage user accounts Today we're talking about the Ansible module `user`. The full name is ansible.builtin.user, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts and supports a huge variety of Linux distributions. For Windows, use the `ansible.windows.win_user` module instead. ## Linux password aging policy This schema represents the Linux password aging policy. Let me highlight that the Ansible native module `user` is able to set only the min days `-m` and max days `-M` parameter. Max days set password policy for requesting password should be renewed, for example in every 90 days. Min days set the minimum days should be waiting for changing the password again, for example after 7 days from the last change. To disable password aging specify the value of 99999. For the other parameters, you need to rely on the `chage` command-line utility or via the Ansible `shell` module. ## Parameters - name string - username - password_expire_min integer - Linux min days validity (-m) - password_expire_max integer - Linux max days validity (-M) This module has many parameters to perform any task. The only required is "name", which is the username. In the `password_expire_min` parameter you specify the value of the min days validity. In th... --- ## Using Ansible Tree Callback: Save Host Events to Files Easily URL: https://www.ansiblebyexample.com/articles/ansible-ansible-builtin-tree-callback-saving-host-events-to-files Description: Discover how to use the Ansible Tree callback to save host events to JSON files. Enhance your logging and auditing with this powerful feature introduced. ## Introduction Ansible, an open-source automation tool, is renowned for its ability to streamline IT tasks and configuration management. One of Ansible's powerful features is its extensible callback system, which allows users to capture and handle events triggered during playbook execution. In this article, we'll delve into the `ansible.builtin.tree` callback, introduced in Ansible-core version 2.11, and explore how it can be utilized to save host events to files. ## Understanding the Callback Parameters ### `directory` Parameter The `directory` parameter is a crucial component of the `ansible.builtin.tree` callback. It specifies the path to the directory where per-host JSON files will be saved. When using ad-hoc commands, this directory can be set using the `--tree` option. The default directory is "~/.ansible/tree." Let's break down the relevant details: - **Added in Ansible-core 2.11:** The `directory` parameter was introduced in Ansible-core version 2.11, making it available for users in more recent releases. - **INI Entry:** [code example] Users can configure the `directory` parameter in the `ansible.cfg` file under the `[callback_tree]` section. - **Environment Variable:** [code example] Alternatively, the `directory` parameter can be set using the `ANSIBLE_CALLBACK_TREE_DIR` environment variable. ## Practical Example To illustrate the usage of the `ansible.builtin.tree` callback, consider the following example playbook and configuration: ### Invento... --- ## Using Jenkins to Build Infrastructure with Terraform and Configure with Ansible URL: https://www.ansiblebyexample.com/articles/using-jenkins-to-build-infrastructure-with-terraform-and-configure-with-ansible Description: Learn how to automate infrastructure provisioning using Jenkins, Terraform, and Ansible, including secure repository access through a GitHub App Token. ## Introduction Modern DevOps practices rely heavily on automation tools to streamline infrastructure provisioning and configuration management. Jenkins, Terraform, and Ansible are widely used tools that work seamlessly to accomplish these tasks. In this guide, we demonstrate how to orchestrate the process using Jenkins, provision the infrastructure with Terraform, and finalize configurations with Ansible. We also integrate GitHub securely using a GitHub App Token. --- ## 1. Workflow Overview The workflow involves three primary tools: - **Jenkins**: CI/CD orchestrator that triggers and manages the process. - **Terraform**: Automates infrastructure provisioning (e.g., servers, networks). - **Ansible**: Configures the provisioned infrastructure (e.g., installing software, managing services). ### Key Benefits - **Automation**: Eliminates manual effort, reducing errors. - **Scalability**: Easily adaptable to different environments. - **Security**: Uses GitHub App Tokens for secure repository access. --- ## 2. Setting Up Jenkins ### Installation 1. Download and install Jenkins from the official Jenkins site. 2. Configure Jenkins with necessary plugins: - `Terraform` - `Ansible` - `GitHub Integration` ### Configure GitHub Token in Jenkins 1. Create a GitHub App Token: - Go to **Settings** > **Developer Settings** > **Personal Access Tokens** > **Fine-grained Tokens**. - Generate a token with `read-only` access to repositories. 2. Add the token to Jenkins: ... --- ## Vertex AI vs SageMaker — AI Platform Comparison URL: https://www.ansiblebyexample.com/articles/ai-development-platforms-google-vertex-ai-vs-amazon-sagemaker Description: Compare Google Vertex AI and Amazon SageMaker for ML workflows. Pricing, AutoML, deployment, notebook support, and which platform fits your AI project. ## Introduction > Google Vertex AI vs. Amazon SageMaker: Navigating the AI Development Seas In the rapidly evolving landscape of artificial intelligence (AI) and machine learning (ML), two giants stand as beacons for developers and enterprises aiming to harness the power of AI: Google Vertex AI and Amazon SageMaker. Choosing the right platform can feel like navigating through a maze of technical jargon, feature sets, and pricing models. This article aims to shine a light on the path, comparing and contrasting these platforms to help intermediate practitioners elevate their AI projects. ## The Battle of the Titans: An Overview Google Vertex AI and Amazon SageMaker are comprehensive suites designed to simplify the process of building, training, and deploying machine learning models. At their core, both platforms strive to Playbookcratize AI, offering tools that span the full ML lifecycle. However, their approaches, ecosystems, and strengths vary, presenting a classic case of "right tool for the right job." ### 1. Ease of Use and Integration **Google Vertex AI** excels in its seamless integration with Google Cloud's ecosystem, providing an intuitive interface that allows for the quick assembly of ML models, especially for those already entrenched in Google Cloud services. Its AutoML feature stands out, enabling users with limited ML expertise to train high-quality models with minimal effort. For instance, a small e-commerce business can leverage Vertex AI to predict custom... --- ## What Are Ansible Collections? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-collections Description: Learn about Ansible collections, their purpose, structure, and how they simplify modular automation with reusable content. Ansible collections are a key feature that enhances modularity and reusability in automation workflows. They bundle content such as modules, plugins, roles, and documentation into a standardized format. This article explains what Ansible collections are, their structure, and how to use them. ## What Are Ansible Collections? Ansible collections are **distributable packages** of Ansible content, designed to organize and share automation resources. They are hosted in repositories like **Ansible Galaxy** or private registries, making it easier to manage and reuse automation code. ### Key Features of Collections: - **Modularity**: Collections group related content, simplifying distribution and use. - **Organization**: Provide a structured way to manage custom and community-contributed content. - **Standardization**: Use a consistent directory layout for easy integration. ## Structure of an Ansible Collection A collection has a predefined directory structure: [code example] ### Key Components: 1. **`plugins/`**: Contains custom modules, inventory plugins, lookup plugins, and filters. 2. **`roles/`**: Stores roles for task execution. 3. **`playbooks/`**: Includes example playbooks for using the collection. 4. **`docs/`**: Provides documentation for the collection. 5. **`galaxy.yml`**: Metadata file defining the collection name, description, dependencies, and version. ## Benefits of Using Ansible Collections 1. **Reusable Content**: Collections allow teams to package and ... --- ## What Are Ansible Facts? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-facts Description: Explore Ansible facts, their role in automation, and how they provide critical information about managed nodes to enhance playbook flexibility. Ansible facts are a cornerstone of Ansible automation, providing valuable information about managed nodes that can be dynamically used in playbooks. This article explains what facts are, how they work, and their role in enhancing automation workflows. ## What Are Ansible Facts? Ansible facts are **system variables** automatically collected from managed nodes during playbook execution. They include details about the system’s hardware, operating system, network interfaces, and more. These facts enable playbooks to adapt dynamically to different environments. ### Key Features of Facts: - **Automatically Gathered**: By default, Ansible collects facts using the `setup` module at the start of a playbook run. - **Dynamic Variables**: Facts provide real-time information about target systems. - **Versatile Usage**: Use facts in conditions, tasks, templates, and handlers. ## How to Use Ansible Facts ### 1. **Accessing Facts** Facts are accessible as variables in your playbooks. For example: [code example] ### 2. **Common Facts** - **OS Information**: [code example] - **Network Details**: [code example] - **Hardware Info**: [code example] ### 3. **Using Facts in Conditions** Facts are often used in `when` statements to create conditional tasks: [code example] ### 4. **Custom Facts** Define your own facts by placing files in `/etc/ansible/facts.d/` on managed nodes. For example: [code example] Access this custom fact in your playbook:... --- ## What Are Ansible Handlers? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-handlers Description: Learn what Ansible handlers are, their purpose, and how they enable efficient task execution in playbooks. With tested, real-world examples. Ansible handlers are a powerful feature that enhance efficiency and control in automation workflows. They allow tasks to trigger actions only when necessary, reducing redundancy and improving performance. This article explores what handlers are, how they work, and their best practices. ## What Are Ansible Handlers? Ansible handlers are **special tasks** that are executed only when notified by other tasks. They are typically used to perform actions like restarting services or reloading configurations after a change has been made. ### Key Features: - **Triggered Execution**: Run only when explicitly notified. - **Task Efficiency**: Avoid redundant actions, such as unnecessary service restarts. - **Reuse**: Define handlers once and use them across multiple tasks. ## How Do Handlers Work? Handlers are defined just like tasks but are listed under a dedicated `handlers` section in a playbook. A task notifies a handler to run when it changes something. ### Example: Restarting a Service [code example] ### How It Works: 1. Tasks notify the handler (`Restart Apache`) only if they make changes. 2. At the end of the play, Ansible runs the handler once, regardless of how many times it was notified. ## Key Concepts of Handlers 1. **Idempotency**: Handlers, like tasks, are idempotent, ensuring consistent results. 2. **Execution Order**: Handlers are executed after all tasks in the play are completed. 3. **Notification Frequency**: A handler is triggered only once per pla... --- ## What Are Ansible Modules? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-modules Description: Discover the purpose of Ansible modules, how they function, and why they are essential building blocks for automation with Ansible. Ansible modules are the foundation of Ansible's automation capabilities. They are small programs that perform specific tasks, enabling you to automate everything from software installation to cloud provisioning. This article explains what Ansible modules are, their types, and how to use them in playbooks. ## What Are Ansible Modules? Ansible modules are **standalone units of code** executed by Ansible to perform specific tasks on managed nodes. These tasks can range from system configuration and file manipulation to cloud infrastructure provisioning. Modules are also referred to as "task plugins" or "library plugins" and are invoked in Ansible playbooks as tasks. ### Key Features of Ansible Modules: - **Idempotence**: Modules are designed to achieve the same result regardless of how many times they are run. - **Agentless Execution**: Modules execute over SSH or WinRM without requiring agents on the target systems. - **Extensibility**: You can create custom modules to extend functionality. ## Types of Ansible Modules Ansible includes a wide variety of modules categorized by their functionality: ### 1. **Core Modules** - Maintained by the Ansible team and included in all installations. - Examples: `file`, `user`, `service`, `package`. ### 2. **Cloud Modules** - Manage resources in cloud platforms like AWS, Azure, and Google Cloud. - Examples: `amazon.aws.ec2`, `azure.azcollection.azure_rm_vm`. ### 3. **Networking Modules** - Automate network device confi... --- ## What Are Ansible Plugins? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-plugins Description: Learn what Ansible plugins are, their types, and how they extend Ansible's functionality to enhance automation workflows. Ansible plugins are modular pieces of code that extend and enhance Ansible’s core functionality. They allow users to customize and optimize workflows for specific requirements. This article explains what Ansible plugins are, their types, and how to use them effectively. ## What Are Ansible Plugins? Ansible plugins are **Python-based extensions** that modify or add capabilities to Ansible’s automation engine. They provide additional functionality without altering the core Ansible codebase, making them highly flexible and reusable. ### Key Features: - **Extensibility**: Add new behaviors to Ansible. - **Reusability**: Share plugins across projects or teams. - **Customization**: Tailor functionality to specific needs. ## Types of Ansible Plugins Ansible supports several plugin types, each serving a distinct purpose: ### 1. **Action Plugins** Modify or enhance the behavior of modules when executed. - Example: Add custom logic to module execution. ### 2. **Lookup Plugins** Fetch data from external sources and pass it into playbooks. - Example: Retrieve secrets from a vault: [code example] ### 3. **Filter Plugins** Transform data or variables in templates or playbooks. - Example: Convert text to uppercase: [code example] ### 4. **Connection Plugins** Define how Ansible connects to target nodes (e.g., SSH, WinRM). - Example: Use a custom connection method for specialized devices. ### 5. **Strategy Plugins** Control the execution flow of... --- ## What Are Ansible Variables? URL: https://www.ansiblebyexample.com/articles/what-are-ansible-variables Description: Learn about Ansible variables, their purpose, types, and how they enhance the flexibility of playbooks in automation workflows. Ansible variables are a core feature that allows users to make playbooks dynamic and reusable. By defining variables, you can simplify configurations, adapt tasks to different environments, and manage large-scale automation workflows effectively. This article explores Ansible variables, their types, and best practices for using them. ## What Are Ansible Variables? Ansible variables are **key-value pairs** that store data used during playbook execution. They make playbooks flexible by allowing you to dynamically configure tasks based on the target system or environment. ### Key Features: - **Dynamic Customization**: Modify task behavior based on variable values. - **Centralized Management**: Define variables in a single place for easier updates. - **Reusability**: Share variables across multiple playbooks. ## Types of Ansible Variables Ansible supports a variety of variable types to suit different use cases: ### 1. **Playbook Variables** Variables defined directly within a playbook. Example: [code example] ### 2. **Host Variables** Variables specific to individual hosts, defined in the inventory file or host-specific files. Example in Inventory: [code example] Example in `host_vars/host1.yml`: [code example] ### 3. **Group Variables** Variables applied to groups of hosts, defined in the inventory file or group-specific files. Example in `group_vars/webservers.yml`: [code example] ### 4. **Facts** Automatically gathered variables... --- ## What Is an Ansible Playbook? Examples & How It Works URL: https://www.ansiblebyexample.com/articles/what-are-ansible-playbooks Description: Learn Ansible playbooks: YAML automation of infrastructure. Covers structure, variables, handlers, conditionals, loops, and best practices with examples. An Ansible playbook is a YAML file that tells Ansible which hosts to manage and which tasks to run. This article explains the role of playbooks, their components, and how to use them effectively. ## What Is an Ansible Playbook? Ansible playbooks are **YAML files** that define a series of tasks to be executed on managed nodes. They describe the desired state of your infrastructure or applications and are a core part of Ansible’s Infrastructure as Code (IaC) approach. ### Why Use Playbooks? - **Readability**: Written in YAML, playbooks are easy to read and write. - **Reusability**: Modular and reusable across different projects. - **Declarative Approach**: Define the end state without specifying every step. ## Anatomy of an Ansible Playbook A playbook consists of **plays**, each targeting a group of hosts with specific tasks. Below is an example playbook: [code example] ### Key Components: 1. **`name`**: Describes the play or task for clarity. 2. **`hosts`**: Specifies the target group in the inventory. 3. **`become`**: Enables privilege escalation. 4. **`tasks`**: Contains a list of operations to perform. ## How Do Playbooks Work? 1. **Target Hosts**: Define the group of systems to manage (e.g., `webservers`). 2. **Execute Tasks**: Each task invokes an Ansible module, such as `apt` or `service`. 3. **Idempotence**: Playbooks ensure tasks are executed only if needed to achieve the desired state. ## Features of Ansible Playbooks 1. **Variables**: Use variables to ... --- ## What is Ansible AWX? — Open-Source Ansible Web UI URL: https://www.ansiblebyexample.com/articles/what-is-ansible-awx Description: Ansible AWX is the open-source web UI for managing Ansible automation. REST API, RBAC, job scheduling, credential management, and Tower comparison. ## What is Ansible AWX? **AWX** is a free, open-source web application that provides a **graphical user interface, REST API, and task engine** for Ansible. It is the upstream community project for the **Red Hat Ansible Automation Controller** (formerly Ansible Tower). AWX lets teams manage Ansible **playbooks, inventories, credentials, and schedules** through a browser instead of the command line — with role-based access control, job history, and real-time output. ## AWX vs Ansible Tower vs Automation Controller | Feature | AWX | Ansible Tower (legacy) | Automation Controller | |---------|-----|----------------------|----------------------| | **License** | Apache 2.0 (free) | Proprietary (Red Hat) | Proprietary (Red Hat) | | **Support** | Community only | Red Hat support | Red Hat support | | **Release cycle** | Every ~2 weeks | Quarterly | Part of AAP releases | | **Stability** | Cutting-edge, may break | Stable | Stable, enterprise-grade | | **Cost** | Free | Subscription | Subscription (AAP) | | **Who uses it** | Labs, small teams, learning | Deprecated → Automation Controller | Enterprise production | **Key point:** AWX is to Automation Controller what Fedora is to RHEL — the community upstream where features land first. ## AWX Architecture [code example] ### Components - **Web UI** — React-based dashboard for managing everything visually - **REST API** — Full API for automation and CI/CD integration - **Task Engine** — Celery-based workers that execute Ansible p... --- ## What Is Ansible AWX? Open-Source Automation Platform Guide URL: https://www.ansiblebyexample.com/articles/what-is-ansible-awx-ansible-awx Description: AWX is the free, open-source upstream to Ansible Automation Controller — a web UI and REST API for running Ansible playbooks at scale. Ansible AWX is the open-source upstream project for Red Hat's Ansible Automation Controller (formerly Ansible Tower). It provides a web-based user interface, REST API, and task engine for managing Ansible playbooks, inventories, credentials, and schedules across your organization. ## What Is Ansible AWX? Ansible AWX is a free, open-source web application that adds a browser-based dashboard and REST API on top of Ansible, so you can run playbooks, manage inventories and credentials, and schedule jobs without touching the command line. It gives you everything you need to run Ansible at scale through a browser: - **Web UI dashboard** — visual overview of job status, inventory health, and recent activity - **REST API** — programmatic access to every AWX feature for CI/CD integration - **Role-based access control (RBAC)** — granular permissions for teams and users - **Job scheduling** — run playbooks on a schedule (cron-like) - **Credential management** — securely store SSH keys, cloud credentials, vault passwords - **Inventory management** — static and dynamic inventories from cloud providers - **Notifications** — email, Slack, webhook alerts on job success/failure - **Workflow templates** — chain multiple playbooks into multi-step workflows ## AWX vs Ansible Tower vs Automation Controller The naming has evolved over the years: | Product | Status | Support | License | |---------|--------|---------|---------| | **AWX** | Active upstream project | Community only | Apache 2.0 ... --- ## What is FQCN in Ansible? Fully Qualified Collection Names URL: https://www.ansiblebyexample.com/articles/ansible-fqcn-fully-qualified-collection-names Description: FQCN (Fully Qualified Collection Names) in Ansible: Learn what they are, why they're essential, best practices, migration strategies, and examples. ## Introduction FQCN stands for **Fully Qualified Collection Name** — the complete namespace.collection.module path that uniquely identifies any Ansible module, plugin, or role. Since Ansible 2.10, content moved from a single package into separate collections, and FQCN became the recommended way to reference modules. Using FQCN prevents ambiguity when multiple collections provide modules with the same short name, and it's required by `ansible-lint` in production profiles. In practice, FQCN means writing `ansible.builtin.copy` instead of `copy`, or `ansible.windows.win_copy` instead of `win_copy`, so the playbook names the exact collection and module Ansible should load. ## FQCN Format [code example] [code example] ## Why FQCN Matters ### 1. Avoids Module Name Collisions [code example] ### 2. Future-Proof Your Playbooks [code example] ### 3. Required by ansible-lint [code example] ## Common FQCN Mappings ### Built-in Modules (ansible.builtin) [code example] ### POSIX Collection (ansible.posix) [code example] ### Windows Collection (ansible.windows) [code example] ### Community Collections [code example] ## How to Find a Module's FQCN [code example] ## Migrating to FQCN ### Manual Migration [code example] ### Automated Migration with ansible-lint [code example] ### Search and Replace [code example] ## FQCN for Plugins and Filters FQCN applies to everything, not just modules: [code example] ## Common Mistakes [code example] ## ansible.cfg Coll... --- ## What Is MCP in Ansible Automation Platform — Model Context Protocol URL: https://www.ansiblebyexample.com/articles/ansible-mcp-model-context-protocol-automation-platform Description: Learn what MCP (Model Context Protocol) means for Ansible Automation Platform. Understand AI-assisted automation, Lightspeed integration, and the. ## Introduction MCP (Model Context Protocol) is an open standard that lets AI models interact with external tools and data sources through a unified interface. In the Ansible ecosystem, MCP enables AI assistants to understand your infrastructure context — inventory, playbooks, execution history — and provide intelligent automation recommendations. This guide explains what MCP means for Ansible practitioners. ## What Is Model Context Protocol? MCP is a protocol (originally developed by Anthropic) that standardizes how AI models connect to external systems: [code example] **Without MCP:** AI generates generic Ansible code with no knowledge of your environment. **With MCP:** AI knows your inventory structure, installed collections, variable naming conventions, and past execution results — generating contextually accurate playbooks. ## MCP in Ansible Automation Platform ### Ansible Lightspeed + MCP Red Hat's Ansible Lightspeed (powered by IBM watsonx Code Assistant) is evolving to leverage MCP for deeper integration: [code example] ### AAP as an MCP Server Ansible Automation Platform can expose an MCP-compatible interface: [code example] ## Practical Examples ### AI-Assisted Playbook Writing [code example] ### Intelligent Troubleshooting [code example] ### Natural Language Automation [code example] ## Setting Up MCP with Ansible ### MCP Server for Ansible Projects [code example] ### IDE Integration [code example] ## MCP vs Traditional Ansible AI | Featu... --- ## What is Universal Disk Format (UDF)? Ansible Integrated Guide URL: https://www.ansiblebyexample.com/articles/what-is-universal-disk-format-udf Description: Discover Universal Disk Format (UDF) for CDs, DVDs, and Blu-ray. Learn its features, applications, versions, and benefits, plus Ansible automation. The **Universal Disk Format (UDF)** is a file system standard maintained by the Optical Storage Technology Association (OSTA). Designed for compatibility across a wide range of devices and operating systems, UDF is widely used for optical media like CDs, DVDs, and Blu-ray discs. This guide explores UDF’s features, versions, practical applications, and how **Ansible** can simplify its management for IT professionals. --- ## What is Universal Disk Format (UDF)? UDF is a platform-independent file system designed to store data on optical discs and other media. It replaces the older ISO 9660 format, offering advanced features like support for larger file sizes, long file names, and compatibility with rewritable media. With **Ansible**, you can automate UDF formatting, disc creation, and troubleshooting tasks efficiently. --- ## Key Features of UDF 1. **Cross-Platform Compatibility**: - Supported by Windows, macOS, Linux, and other major operating systems. 2. **Large File Support**: - Handles files larger than 4 GB, making it ideal for modern multimedia storage. 3. **Writability**: - Enables reading and writing to rewritable media like CD-RWs, DVD-RWs, and Blu-ray discs. 4. **Backward Compatibility**: - Newer UDF versions maintain compatibility with older ones. Using **Ansible modules** like `command` and `shell`, you can execute UDF-related tasks programmatically, saving time and minimizing errors. --- ## Automating UDF Tasks with Ansible ### 1. **Formatting O... --- ## What's New in AAP 2.5 — Ansible Automation Platform Features URL: https://www.ansiblebyexample.com/articles/ansible-aap-25-whats-new-features Description: Explore Ansible Automation Platform 2.5 features. Event-Driven Ansible enhancements, Execution Environments, Lightspeed AI, and enterprise automation. ## Introduction Ansible Automation Platform (AAP) 2.5 is the latest enterprise release from Red Hat, building on the platform's shift to a container-native, event-driven architecture. This guide covers the key features and what they mean for enterprise automation teams. ## AAP 2.5 Architecture [code example] ## Key Features ### 1. Enhanced Event-Driven Ansible (EDA) Event-Driven Ansible processes events from external systems and triggers automation in response. [code example] **What's new in 2.5:** - Improved event filtering and throttling - Better integration with ServiceNow, PagerDuty, Dynatrace - Event-driven credential rotation - Audit trail for all event-triggered actions ### 2. Ansible Lightspeed AI [code example] **Enterprise features:** - On-premises model deployment (IBM watsonx) - Custom model fine-tuning on your playbooks - RBAC for AI features - Telemetry opt-out for air-gapped environments ### 3. Execution Environments 2.0 [code example] **What's new:** - Smaller base images (minimal variants) - Multi-architecture builds (amd64 + arm64) - Built-in security scanning - Version pinning improvements ### 4. Automation Mesh Improvements [code example] [code example] ### 5. Private Automation Hub [code example] ## Migration from AAP 2.4 [code example] ## AAP 2.5 vs AWX | Feature | AAP 2.5 | AWX (Community) | |---------|---------|-----------------| | Support | ✅ Red Hat subscription | ❌ Community only | | Lightspeed AI | ✅ Included | ❌ Not availabl... --- ## Where Are Ansible Collections Installed? URL: https://www.ansiblebyexample.com/articles/where-are-ansible-collections-installed Description: Find where Ansible collections are installed, configure COLLECTIONS_PATHS, and manage multiple collection locations. Default paths for all platforms. Ansible collections are modular packages that group related content such as roles, modules, and plugins. Understanding where collections are installed is essential for managing and customizing your Ansible automation workflows. This article explains the default installation paths for Ansible collections and how to customize them. ## Where Are Ansible Collections Installed? ### Default Installation Paths By default, Ansible collections are installed in two primary locations depending on the type of user access: 1. **Global Path**: For system-wide installation, collections are stored under the **Ansible system directory**: [code example] 2. **User Path**: For user-specific installation, collections are stored in the user's home directory: [code example] This location is typically used when running `ansible-galaxy collection install` without administrative privileges. ### Verifying Installed Collections To view all installed collections, use the following command: [code example] This command outputs the collection name, version, and installation path. ## How to Customize Collection Installation Paths Ansible allows you to customize collection paths using the `ANSIBLE_COLLECTIONS_PATHS` environment variable or by modifying the `ansible.cfg` configuration file. ### Using Environment Variables Set a custom collection path using the `ANSIBLE_COLLECTIONS_PATHS` environment variable: [code example] This variable overrides the default paths during collection ... --- ## Where Are Ansible Logs Stored? URL: https://www.ansiblebyexample.com/articles/where-are-ansible-modules-stored Description: Discover where Ansible logs are stored, how to enable logging, and best practices for managing Ansible logs in automation workflows. Ansible logs are crucial for debugging, auditing, and monitoring your automation workflows. By default, Ansible does not log to a file unless explicitly configured. This article explains where Ansible logs are stored, how to enable logging, and best practices for managing log files. ## Where Are Ansible Logs Stored? ### Default Behavior By default, Ansible logs output to the terminal (stdout) during playbook execution. To capture logs in a file, you must configure the logging settings in the `ansible.cfg` file. ### Enabling Logging in Ansible To enable logging, follow these steps: 1. Open or create the `ansible.cfg` file in your project directory or system-wide configuration path (e.g., `/etc/ansible/ansible.cfg`). 2. Add or modify the following lines under the `[defaults]` section: [code example] This configuration stores logs in `/var/log/ansible/ansible.log`. 3. Ensure the directory exists and has appropriate permissions: [code example] 4. Verify the configuration by running a playbook: [code example] Logs will be written to the specified file. ## Common Log File Locations 1. **Project-Specific Logs**: If you specify a relative path in `ansible.cfg`, logs will be stored in the project directory: [code example] 2. **System-Wide Logs**: When using a global configuration file, logs are often stored under: [code example] 3. **Custom Paths**: You can define any valid file path for logs in the `log_path` setting. ## Using Environment V... --- ## Where Are Ansible Playbooks Stored? URL: https://www.ansiblebyexample.com/articles/where-are-ansible-playbooks-stored Description: Where to store Ansible playbooks, recommended directory structures, and best practices for organizing roles, inventories, and group_vars. Ansible playbooks are essential for defining automation workflows, and storing them in an organized and accessible manner is critical for efficient operations. This article explores where playbooks are typically stored, best practices for directory organization, and tips for effective management. ## Where Are Ansible Playbooks Stored? Ansible playbooks are **YAML files** that can be stored anywhere in the filesystem, as long as they are accessible to the Ansible control node. There is no mandatory default location, but best practices suggest using a structured directory layout. ### Typical Locations for Playbooks 1. **Project-Specific Directories**: Playbooks are often stored in project directories for better organization: [code example] 2. **Centralized Repository**: Teams may use a shared repository or version-controlled directory: [code example] 3. **Role-Based Directories**: When using roles, playbooks are stored alongside roles for modularity: [code example] ### Verifying Playbook Location When running a playbook, specify its path: [code example] ## Recommended Directory Structure Organizing playbooks and associated files is crucial for scalability and maintainability. Below is a common directory structure: [code example] ### Key Components: - **Playbooks**: Store the primary YAML files defining tasks. - **Inventory**: Define target systems and groupings. - **Group/Host Variables**: Organize variables for groups or individual hosts. - **Roles... --- ## Why Ansible Pilot URL: https://www.ansiblebyexample.com/articles/why-ansible-pilot Description: Behind the scene of the Ansible Pilot project and Ansible open source infrastructure as code technology. Tested, copy-paste examples included. Digital technologies have made learning faster, cheaper, and easier than before. That means that you need to embrace new digital tools in the broader culture of professional development that solves people’s real problems at work. The workplace is changing fast. And upskilling ourselves as IT professionals are more critical than ever in today’s super competitive marketplace. Today’s mantra in the professional world is to innovate, automate and accelerate. The skills needed in today’s business world aren’t the skills we needed in the past. Ansible is the best open-source infrastructure as a code tool in the market. I’ve been working for the Red Hat Ansible engineering team and learn more every day, so I’d like to share with other people more as possible. Traditional learning methodologies rely on the classroom model, where an expert teacher explains thousands of concepts to students for hours, in a typical top-down model. The problem with this methodology is that they sometimes forget three-quarters of the concepts. As humans, we are social animals that like to pick up information and ideas from other people, our peers. Mobile phones and computers connected to the internet give us unprecedented access to knowledge. We’re living in the Digital Age. Nowadays, ideas and information circles the globe in seconds and enable us to learn from the best expert worldwide. Computer languages are the same all over the world and are easy that everything to teach; there is no langua... --- ## Why Every IT Professional, Quiet Quitter or Not, Should Learn Ansible URL: https://www.ansiblebyexample.com/articles/ansible-for-quiet-quitter-and-not Description: Ansible is essential for automating IT infrastructure, saving time, and reducing errors. Whether you're a quiet quitter or not, learn how Ansible can. # Why Every IT Professional, Quiet Quitter or Not, Should Learn Ansible ## Introduction Why Every IT Professional, Quiet Quitter or Not, Should Learn Ansible. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Why Every IT Professional, Quiet Quitter or Not, Should Learn Ansible requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbook... --- ## Why Learn Ansible in 2023? URL: https://www.ansiblebyexample.com/articles/why-learn-ansible-in-2023 Description: Is it worth it to learn Ansible in 2023? How is Ansible perceived in the market? How steep is the learning curve? Ansible is a leader in the latest Q1. # Why Learn Ansible in 2023? ## Introduction Why Learn Ansible in 2023?. This guide provides practical Ansible examples, configuration patterns, and best practices for implementing this in production environments. ## Overview Effective use of Why Learn Ansible in 2023? requires understanding both the Ansible modules involved and the underlying technology. This guide covers both aspects with real-world examples. ## Prerequisites [code example] ## Basic Implementation [code example] ## Advanced Configuration [code example] ## Role Structure [code example] ## Error Handling [code example] ## Handlers [code example] ## Testing [code example] ## Troubleshooting | Issue | Solution | |-------|----------| | Variable undefined | Check `defaults/main.yml` and variable precedence | | Template error | Validate Jinja2 syntax with `ansible-playbook --syntax-check` | | Permission denied | Verify `become: true` and sudo configuration | | Handler not triggered | Ensure task reports `changed` status | | Idempotency issues | Test with `--check` to verify no unexpected changes | ## Best Practices 1. **Use roles** for reusable, modular automation 2. **Parameterize everything** — avoid hardcoded values 3. **Test in staging first** — never deploy directly to production 4. **Use check mode** for validation: `--check --diff` 5. **Document your playbooks** with comments and README files 6. **Version control** all playbooks and roles in Git 7. **Use tags** for selective task execu... --- ## YAML Multiline Strings — Folded & Literal URL: https://www.ansiblebyexample.com/articles/how-to-break-a-string-over-multiple-lines-with-ansible-and-yaml Description: Break long strings across multiple lines in Ansible YAML. Use folded (>), literal (|), chomp indicators, and Jinja2 line breaks with examples. Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll explore a handy technique in Ansible – breaking strings over multiple lines using YAML. This can be especially useful when dealing with multiline text in your Ansible playbooks. Let's dive in and explore the two operators that make this possible: the `|` (Literal Block Scalar) and the `>` (Folded Block Scalar). ## The Basics: `|` and `>` Operators In Ansible, breaking a string over multiple lines is accomplished using two main operators: - `|` (Literal Block Scalar): This operator instructs Ansible to treat the string as a literal block scalar, preserving the newlines within the string. - `>` (Folded Block Scalar): This operator tells Ansible to treat the string as a folded block scalar, collapsing all newlines into a single space. Let's illustrate these concepts with some examples. ### Example 1: Using `|` (Literal Block Scalar) [code example] In this example, `my_variable` will be a multiline string, preserving the newline characters. ### Example 2: Using `>` (Folded Block Scalar) [code example] In this case, `my_variable` will be a single-line string with spaces replacing the newlines. The key difference is that `|` preserves newlines, while `>` collapses them. ## Examples Now, let's look at some practical examples to solidify our understanding. ### Example 1: Variable Definitions #### Code: [code example] #### Output: [code example] ### Example 2: Using `>` Operator #### Cod... ---