What is Ansible – Advantages and Disadvantages

Back to Blog
Ansible - Automate Application Deployment

What is Ansible – Advantages and Disadvantages

85/ 100

What is Ansible?

Ansible is an automated system which made for you it needs it is a system. It has all capability to handle IT functions it is all in one. The biggest Ansible advantages is its design for multi-tier deployments. Ansible handles IT infrastructure by describing how all systems interrelate.

It uses no agents and no additional custom security infrastructure. It’s easy to deploy – and most importantly, it uses a very simple language (YAML).

Initial release: February 20, 2012
Stable release: 2.18.2 / January, 27 2025

Ansible Advantages

Ansible - Advantages and Disadvantages
Ansible – Advantages and Disadvantages

Ansible is an open-source automation tool, offers several advantages:

1. Agentless

An agentless architecture is one of top Ansible advantages. It refers to the absence of software agents that need to be installed and running on remote systems or nodes. Ansible communicates with remote systems using standard network protocols such as SSH for Unix/Linux or WinRM for Windows.

In an agent-based automation tool, a software agent typically runs on each managed node, facilitating communication and executing commands or scripts sent by a central controller.

In an agentless model like Ansible’s, the control machine remotely manages target systems without requiring additional software components on managed nodes.

Why agentless is the main ansible advantages? Share on X

2. Simplicity

Using YAML syntax has one of key ansible advantages, which is human-readable and easy to understand. Its simple architecture and intuitive language make it accessible even to those without extensive programming knowledge.

What are Ansible Advantages and Disadvantages in DevOps? Share on X

3. Flexibility

Ansible is known for its flexibility, which refers to its ability to adapt to various environments, systems, and use cases. Here are some key ansible advantages aspects:

  • Ansible can manage a diverse range of systems and platforms, including Unix/Linux, Windows, network devices, cloud services (AWS, Azure, GCP), containers (Docker, Kubernetes), and more. This broad support allows users to automate tasks across heterogeneous environments using a single tool.
  • Ansible’s modular design facilitates extensibility and customization. It provides built-in modules for tasks like package management, file manipulation, and user management. Users can also develop custom modules to extend Ansible’s functionality.
  • Ansible promotes role-based organization of tasks and configurations through roles. Roles encapsulate reusable sets of tasks, handlers, templates, and variables, allowing users to modularize and share common configurations across projects and environments. This promotes code reusability and maintainability.
  • Ansible supports dynamic inventory, generating inventory files from external sources like cloud providers, virtualization platforms, and databases. This enables dynamic management of infrastructure without the need to maintain static inventory files manually.
Why flexibility is the main ansible advantages in large enterprise infrastructure? Share on X

4. Idempotency

Ansible maintains consistent system configuration with idempotency, preventing unintended side effects when applying playbooks multiple times.

5. Scalability

Ansible can scale from managing a handful of nodes to thousands of them with ease. Its push-based model allows simultaneous configuration of multiple machines, making it suitable for large-scale deployments.

6. Community and Ecosystem

Ansible benefits from a vibrant community that contributes modules, playbooks, and plugins. The extensive ecosystem provides pre-built solutions for various use cases, saving time and effort in development.

7. Integration

Ansible integrates seamlessly with other tools and platforms, including version control systems (e.g., Git), CI/CD pipelines, monitoring solutions, and configuration management databases (CMDBs). This integration enables end-to-end automation workflows.

8. Declarative Nature

Ansible playbooks describe the desired state of a system rather than the steps to achieve it. This declarative approach simplifies configuration management and promotes better understanding and collaboration among teams.

9. Security

Ansible emphasizes security by using SSH encryption for communication and offering credential management options, including vaults for sensitive data.

Ansible includes modules and playbooks for automating security tasks like system hardening, compliance checks, vulnerability scanning, and patch management. By automating these tasks, organizations can ensure that security measures are consistently applied across their infrastructure and systems, reducing the risk of misconfiguration and vulnerabilities.

what are the key ansible advantages in high cpu usage application? Share on X

10. Cost-Effective

Being open-source, Ansible eliminates licensing costs associated with proprietary automation tools. It also reduces operational expenses by streamlining repetitive tasks and improving efficiency. This is one of the core ansible advantages for it’s popularity.

Ansible Disadvantages

While Ansible offers many advantages, it’s important to consider potential disadvantages or limitations:

1. Learning Curve

Although Ansible’s YAML syntax is relatively straightforward, mastering advanced features and best practices may require some learning. Understanding concepts such as Jinja templating, roles, and playbooks’ intricacies might take time for beginners.

2. Statelessness

Ansible doesn’t inherently track the state of managed systems beyond the execution of tasks. This can be a disadvantage for scenarios requiring detailed state tracking and management, which are better addressed by tools like Terraform.

3. Scalability

Ansible is designed to scale, managing very large infrastructures with thousands of nodes can become challenging. The lack of built-in state tracking and the inherent overhead of SSH connections might lead to performance issues in large-scale deployments.

4. Limited Parallelism

Ansible allows parallel execution of tasks, it may not fully leverage the available resources on very large infrastructures. This limitation can impact performance in scenarios where rapid execution is critical.

5. Complexity of Tasks

Ansible simplifies automation, complex tasks might require writing intricate playbooks or using external tools and scripts. Managing such complexity can become challenging, especially for users with limited programming experience.

6. Limited Windows Support

Ansible can manage Windows systems, its support is not as extensive as for Unix/Linux environments. Some tasks or modules may have limited functionality or compatibility with Windows, which could pose challenges in heterogeneous environments.

7. Dependencies on External Tools

Ansible relies on external tools for certain tasks, such as version control systems (e.g., Git) for managing playbooks and SSH for communication with managed nodes. Dependency management and integration with these external tools can introduce additional complexity.

8. Community Modules Quality

Ansible’s community provides a vast array of modules, the quality and reliability of these modules can vary. Users might encounter issues with community-contributed modules, necessitating careful evaluation and testing before production use.

9. Performance Overhead

Ansible’s agentless architecture relies on SSH connections for communication, which can introduce overhead, especially in environments with strict security policies or high-latency networks.

Ansible vs Terraform
Ansible Advantages and Disadvantages – Ansible vs Terraform

10. Enterprise Features

Ansible Tower (or AWX, the open-source upstream project) provides enterprise features such as RBAC, job scheduling, and GUI-based management, these features come with additional costs or setup complexities.

Ansible is a powerful and widely adopted automation tool for configuration management, application deployment, and infrastructure automation. Understanding its limitations helps organizations make informed decisions when selecting automation tools.

Ansible vs Terraform

Ansible and Terraform are both popular infrastructure automation tools, but they serve different purposes and have distinct characteristics.
Here’s a comparison between Ansible and Terraform:

Ansible

Terraform

Purpose
Ansible is primarily a configuration management and automation tool. It focuses on ensuring the desired state of systems by automating tasks such as software installation, configuration file management, service management, and application deployment.Terraform is an infrastructure as code (IaC) tool designed for provisioning and managing infrastructure resources.

 

It enables users to define infrastructure configurations declarative using a high-level configuration language.

Language
Ansible uses YAML syntax for defining tasks and playbooks. YAML is human-readable and easy to understand, making Ansible accessible to users.Terraform uses HashiCorp Configuration Language (HCL) or JSON syntax for defining infrastructure configurations.

 

HCL is specifically designed for defining infrastructure as code and includes features such as variables, expressions, and modules.

Agentless
Ansible operates in an agentless mode, meaning it does not require any software agents to be installed on managed nodes.

 

Instead, it communicates with managed nodes over SSH or WinRM.

Terraform supports a wide range of cloud providers, infrastructure platforms, and services through provider plugins.

 

This enables users to provision resources across heterogeneous environments using a single configuration language and tool.

State Management
Ansible does not maintain state information about infrastructure. Each task in Ansible playbooks is idempotent, meaning it can be run multiple times without causing unintended side effects.

 

However, Ansible itself does not track or manage the state of infrastructure resources.

Terraform maintains a state file that tracks the current state of infrastructure resources managed by Terraform.

 

This state file is used to plan and apply changes to infrastructure, ensuring that Terraform can track and manage the lifecycle of resources.

Extensibility
Ansible’s modular architecture allows users to extend its functionality by developing custom modules and plugins.

 

This enables integration with external tools, APIs, and services to automate a wide range of tasks.

Terraform generates an execution plan before applying changes to infrastructure. This plan provides a preview of the actions.

 

Terraform allows users to preview the time required to create, modify, or delete resources, enabling them to review and validate changes before applying them.

Why Ansible is better than Terraform? Share on X

Ansible vs Jenkins

Ansible vs Jenkins
Ansible vs Jenkins

Ansible

Jenkins

Purpose
Ansible is a configuration management and automation tool.

 

It’s designed to automate the provisioning, configuration, and deployment of software and infrastructure.

Jenkins is an automation server primarily used for continuous integration (CI) and continuous delivery (CD).
It automates the build, test, and deployment phases of software development.
How it works
Ansible uses YAML-based playbooks to describe automation tasks.Jenkins runs jobs or pipelines defined by users. Jobs can be triggered by events such as code commits or scheduled intervals.

 

Jenkins provides a web-based interface for managing jobs and viewing build status.

Key features
Agentless: Ansible communicates with remote machines over SSH, so no agent installation is required on the managed nodes.

 

Idempotent: Tasks can be run multiple times without causing unintended side effects, ensuring consistency.

 

Extensible: Ansible has a large ecosystem of modules and plugins that extend its functionality.

Extensive plugin ecosystem: Jenkins has a vast array of plugins available to integrate with various tools and technologies.

 

Distributed builds: Jenkins can distribute build tasks across multiple nodes, allowing for scalability and parallelism.

 

Pipeline as code: Jenkins Pipeline allows defining build processes in code, enabling version control and code review for CI/CD workflows.

  • Ansible focuses on infrastructure automation and configuration management, while Jenkins specializes in CI/CD.
  • Ansible can be used to provision infrastructure and deploy applications, while Jenkins can be used to automate the build and test processes for those applications.
  • Jenkins has more integrations with CI/CD-related tools and services, while Ansible’s integrations are more focused on infrastructure management and cloud platforms.
Jenkins vs Ansible : Which one to choose? Share on X

Ansible vs Puppet vs Chef vs SaltStack

Ansible

Puppet

Chef

SaltStack

Architecture
Ansible follows a push-based architecture, where the control node pushes configurations and tasks to the managed nodes using SSH.

 

It doesn’t require a separate agent to be installed on managed nodes.

Puppet follows a pull-based architecture, where the managed nodes pull configurations from a central Puppet master server.

 

Puppet requires an agent (Puppet agent) to be installed on managed nodes to communicate with the master.

Chef follows a pull-based architecture, where the managed nodes periodically pull configurations from a central Chef server.

 

Managed nodes require the Chef client agent to be installed, which communicates with the Chef server.

SaltStack follows a hybrid push-pull architecture. It can operate in both push and pull modes.

 

In push mode, the Salt master pushes configurations and commands to the Salt minions using ZeroMQ or other transport mechanisms.

 

In pull mode, minions periodically pull configurations from the Salt master.

Language
Ansible uses YAML-based playbooks to describe automation tasks in a human-readable format.Puppet uses its own domain-specific language (DSL) called Puppet DSL to define configurations.

 

Puppet DSL allows for expressing configurations in a more procedural manner, focusing on the steps needed to achieve the desired state.

Chef uses a Ruby-based DSL (Domain Specific Language) to define configurations.

 

Cookbooks, which contain recipes written in the DSL, describe the desired state of the system and the steps needed to achieve it.

SaltStack uses its own language called Salt state files (SLS) to define configurations.

 

SLS files are written in a YAML-like format and allow for expressing configurations and states in a declarative manner.

Ease of Use
Ansible is easier to learn and use than Puppet, especially for beginners.Puppet has a steeper learning curve due to its DSL and concepts like manifests, modules, and classes.

 

Puppet’s model can offer more power and flexibility in managing complex configurations once mastered.

Chef has a steeper learning curve due to its Ruby-based DSL and concepts like cookbooks, recipes, and resources.

 

Chef’s model can offer more power and flexibility once mastered.

SaltStack has a steeper learning curve due to its unique architecture and concepts like states, pillars, grains, and reactors.

 

SaltStack’s model can offer more power and flexibility once mastered.

Scalability
Ansible manages large-scale infrastructures with its agentless architecture and lightweight nature.

 

This is key ansible advantages that it can handle thousands of nodes efficiently.

Puppet is scalable, though its pull-based architecture can create challenges in large environments with increased network traffic and load on the Puppet master.Chef is scalable, though its pull-based architecture can create challenges in large environments with increased network traffic and load on the Chef server.SaltStack is scalable, and its hybrid architecture provides flexible scaling options.

 

It can handle large deployments with tens of thousands of minions.

Community and Ecosystem
Ansible has a large and active community, with extensive documentation, modules, and roles available on Ansible Galaxy.

 

It integrates well with other tools and services.

Puppet also has a strong community and ecosystem with a wide range of modules available on Puppet Forge.Chef has a strong community and ecosystem with a wide range of cookbooks available on the Chef Supermarket.SaltStack also has a strong community and ecosystem, with a wide range of formulas available on the SaltStack formula repository.

 

It has been adopted by enterprises with complex infrastructures and has a dedicated user base.

Ansible vs Docker vs Kubernetes

Ansible vs Docker vs Kubernetes
Ansible vs Docker vs Kubernetes

Ansible

Docker

Kubernetes

Purpose
Ansible is a configuration management tool for automating IT infrastructure tasks like provisioning, configuration, deployment, and orchestration.

 

It focuses on managing servers, networking devices, and other infrastructure components.

Docker is a containerization platform used for packaging, distributing, and running applications in lightweight, portable containers.

 

It allows developers to encapsulate their applications and all dependencies into a single unit, making it easy to deploy and manage applications across different environments.

Kubernetes is a container orchestration platform used for automating the deployment, scaling, and management of containerized applications.

 

It focuses on managing containers across a cluster of nodes.

Scope
Ansible manages infrastructure components: servers, virtual machines, network devices, and cloud instances.

 

It provides a versatile platform for automating various IT operations tasks.

Docker is designed for containerization, focusing on packaging and running applications inside containers.

 

It abstracts away the underlying infrastructure and provides a consistent environment for running applications across different platforms.

Kubernetes is designed for managing containerized applications.

 

It abstracts away the underlying infrastructure and provides a platform-agnostic way to deploy and manage containers at scale.

Abstraction Level
Ansible operates at a higher level than Kubernetes, using playbooks written in YAML to define the desired infrastructure state, focusing on tasks and configurations.Docker operates at a lower level of abstraction, focusing on containers and the components needed to run applications.

 

It includes tools for building, managing, and running containers, along with orchestrating containerized applications across a cluster of nodes.

Kubernetes operates at a lower level of abstraction, focusing on containers and microservices.

 

It uses declarative YAML manifests to define the desired state of applications, pods, services, and other Kubernetes objects.

Deployment Model
Ansible typically follows a push-based deployment model, where the control node pushes configurations and tasks to the managed nodes using SSH or other protocols.Docker containers can be deployed using various methods:

 

Docker Compose for defining multi-container applications.

 

Swarm for orchestrating containers across multiple hosts.

 

Kubernetes for container orchestration at scale.

Kubernetes follows a declarative, self-healing deployment model.

 

Users define the desired state of their applications and infrastructure using YAML manifests, and Kubernetes ensures that the actual state matches the desired state.

Integration
Ansible is a configuration management tool for automating IT infrastructure tasks like provisioning, configuration, deployment, and orchestration.

 

It focuses on managing servers, networking devices, and other infrastructure components using playbooks written in YAML.

Docker is a containerization platform used for packaging, distributing, and running applications in lightweight, portable containers.

 

It allows developers to encapsulate their applications and all dependencies into a single unit, making it easy to deploy and manage applications across different environments.

Kubernetes can be integrated with Ansible to automate tasks outside the scope of Kubernetes.

 

Examples include provisioning cloud resources, configuring network devices, and performing system-level configurations.

AnsibleFest

AnsibleFest is an annual event dedicated to Ansible. In recent years, AnsibleFest has been integrated into the Red Hat Summit, offering attendees a comprehensive experience that combines automation insights with broader enterprise technology discussions.

AnsibleFest 2025 Details:

  • Dates: May 19 – 22, 2025
  • Location: Boston, Massachusetts, USA
  • Event Overview: AnsibleFest at Red Hat Summit 2025 will feature keynotes, breakout sessions, lightning talks, and significant Ansible announcements. Attendees will have the opportunity to explore tools addressing automation challenges and delve into topics like infrastructure, application development, edge computing, cloud services, and other essential enterprise IT areas all included with the event pass.

Registration and Pricing:

  • Earliest Bird (January 15 – February 24): US$1,099
  • Early Bird (February 25 – March 19): US$1,499
  • Regular (March 20 – May 22): US$1,999
  • Group Rate (3+ passes): US$799 per person

For more details and registration, visit the Red Hat Summit & AnsibleFest official pages.

AnsibleFest History

YearLocationEvent Overview
2024Denver, Colorado, USA
  • Integration of Policy as Code
  • Launch of Connectivity Link
  • Red Hat announced the open-sourcing of IBM’s Granite AI models and the launch of InstructLab
2023Boston, Massachusetts, USA
  • Event-Driven Ansible (EDA) Official Announcement
  • Ansible Lightspeed
2022Chicago, Illinois, USA
  • Introduction of Event-Driven Ansible (EDA)
  • Project Wisdom (Red Hat collaboration with IBM Research for an AI-driven initiative aimed at simplifying the creation of Ansible Playbooks.)
2021Virtual (Due to COVID-19 pandemic)
  • Automation Platform 2
  • Automation Controller (Ansible Tower)
  • Execution Environments Introduction
2020Virtual (Due to COVID-19 pandemic)
  • Integration with IBM Z Platform
  • Adoption by NTT DoCoMo
2019Atlanta, Georgia, USA
  • Launch of Red Hat Ansible Automation Platform
  • Content Collections Introduction
  • Security Automation: Collaborations with CyberArk, F5, IBM, and Check Point for Ansible’s role in security operations
2018Austin, Texas, USA
  • Community Project Discussions (Ansible-lint, Molecule, Zuul)
  • “Make Your Ansible Playbooks Flexible, Maintainable, and Stable” Presentations by Jeff Geerling)
  • Networking Opportunities with Professionals
2017London, UK
  • Contributor Summit
  • Network Automation Focus
2017San Francisco, California, USA
  • Interview with Red Hat CEO Jim Whitehurst
  • Demonstration of Community Contribution Projects
  • Infrastructure Testing with Molecule
2016London, UK
  • Focus on Network Automation
2016San Francisco, California, USA
  • Ansible’s Roles Presentation by Jeff Geerling
2016Brooklyn, New York, USA
  • Contributor Summit
2015London, UK
  • Introduction of Ansible 2.0
2015New York, USA
  • Network Automation Panel: Jason Edelman, Nathan Sowatskey (Cisco), Joel King (World Wide Technology), and Stanley Karunditu (Cumulus Networks), moderated by Tim Gerla (Ansible CTO).
2015San Francisco, California, USA
  • Diverse Sessions
2014New York, USA
  • Tower 2.0 Announcement
2014San Francisco, California, USA
  • What’s New in Ansible 1.7/1.8
2013New York, USA
  • Twitter’s Use of Ansible
2013San Francisco, California, USA
  • Call for Participation (CFP)

FAQs

Yes, Ansible is an open-source tool. However, Ansible Automation Platform (AAP) by Red Hat provides enterprise-level features and support.
Ansible is written in Python. It also supports modules written in Python, Bash, PowerShell, etc.
On Linux (Ubuntu/Debian):
sudo apt update && sudo apt install ansible -y
On RHEL/CentOS:
sudo yum install ansible -y
On MacOS:
brew install ansible
The inventory is a file (default: /etc/ansible/hosts) listing managed nodes (hosts). Example:
[webservers]
server1.example.com
server2.example.com
A Playbook is a YAML file that defines tasks to be executed on remote hosts.
- name: Install Nginx
  hosts: webservers
  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
Modules are pre-built scripts for specific automation tasks (e.g., copy, file, service, yum, apt).
- name: Create a file
  file:
    path: /tmp/testfile.txt
    state: touch
Ansible Vault is a tool for encrypting sensitive data (passwords, API keys) inside playbooks.
ansible-vault encrypt secret.yml
 
Handlers are tasks triggered only if notified.
- name: Restart Apache
  service:
    name: apache2
    state: restarted
  listen: "restart_apache"
ansible-playbook playbook.yml
Ansible Galaxy is a community repository for sharing Ansible roles.
ansible-galaxy install geerlingguy.nginx
Use dry-run mode:
ansible-playbook playbook.yml --check
Debug Ansible errors:
ansible-playbook playbook.yml -vvv
  • Use Terraform to create cloud resources (VMs, networks, databases).
  • Use Terraform output variables to store resource details (IP addresses, SSH keys).
  • Use Ansible to configure and manage the provisioned infrastructure.
Write a Terraform script to create resources:
resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
output "public_ip" {
  value = aws_instance.web.public_ip
}
Export the output for Ansible:
terraform output -json > terraform_outputs.json
Use Ansible to configure the instance:
ansible-playbook -i inventory.ini playbook.yml
Terraform remote state can be accessed in Ansible using the terraform_state module:
- name: Fetch Terraform state
  terraform_state:
    state: path/to/terraform.tfstate
  register: tf_state
Yes, using the remote-exec or local-exec provisioner:
provisioner "remote-exec" {
  inline = [
    "sudo apt update",
    "sudo apt install nginx -y"
  ]
}
Jenkins can trigger Ansible in multiple ways:
  • Using the "Ansible" plugin.
  • Running Ansible as a shell command (ansible-playbook playbook.yml).
  • Using a Jenkins Pipeline Script (sh 'ansible-playbook playbook.yml').
On the Jenkins server, install Ansible:
sudo apt install ansible  # Ubuntu/Debian
sudo yum install ansible  # RHEL/CentOS
brew install ansible      # macOS

Method 1: Using the "Ansible" Plugin

  1. In Jenkins, create a Freestyle Project.
  2. Under Build Steps, select Invoke Ansible Playbook.
  3. Provide the playbook path (/path/to/playbook.yml).
  4. Add any extra parameters (e.g., -i inventory.ini).

Method 2: Using a Shell Command

  1. Create a Freestyle Project.
  2. Add a Build Step → Execute Shell and run:
ansible-playbook -i inventory.ini playbook.yml

Method 3: Using a Jenkins Pipeline Script

pipeline {
    agent any
    stages {
        stage('Run Ansible') {
            steps {
                sh 'ansible-playbook -i inventory.ini playbook.yml'
            }
        }
    }
}
You can use extra-vars (-e) in Ansible to pass Jenkins variables:
ansible-playbook -i inventory.ini playbook.yml -e "version=${BUILD_NUMBER}"
Or inside a Jenkins pipeline:
sh 'ansible-playbook -i inventory.ini playbook.yml -e "branch=${GIT_BRANCH}"'
Use Post-Build Actions in a Freestyle Job:
  • Select "Run Ansible Playbook" after a successful build.
Or, in a Pipeline Script, add:
post {
    success {
        sh 'ansible-playbook -i inventory.ini deploy.yml'
    }
}
  • Install the "Ansible Tower Plugin" in Jenkins.
  • Configure Tower URL and credentials under Manage Jenkins → Configure System.
  • In a Pipeline, trigger an Ansible Tower job:
    ansibleTower(
        towerServer: 'AnsibleTower',
        jobTemplate: 'Deploy App',
        inventory: 'Production'
    )
Yes! Ansible can complement Puppet by handling ad-hoc tasks, orchestration, and agent bootstrapping, while Puppet continues managing configurations consistently.
  • Use Puppet for long-term configuration enforcement.
  • Use Ansible for orchestration, on-demand tasks, and server provisioning.
  • Combine both for robust automation (e.g., use Ansible to deploy Puppet agents).
You can use Ansible to install and configure the Puppet agent on multiple servers. Example playbook:
- name: Install Puppet Agent
  hosts: all
  tasks:
    - name: Install Puppet
      apt:
        name: puppet-agent
        state: present

    - name: Start Puppet Agent
      service:
        name: puppet
        state: started
        enabled: yes
  • Avoid overlapping responsibilities (e.g., don’t let both manage the same config files).
  • Define clear roles (Ansible for provisioning, Puppet for enforcement).
You can use Ansible to install the Chef client and configure it on multiple servers. Example playbook:
- name: Install Chef Client
  hosts: all
  tasks:
    - name: Download Chef installer
      get_url:
        url: //packages.chef.io/files/stable/chef/17.10.0/el/7/chef-17.10.0-1.el7.x86_64.rpm
        dest: /tmp/chef.rpm

    - name: Install Chef
      yum:
        name: /tmp/chef.rpm
        state: present

    - name: Create Chef client configuration
      copy:
        dest: /etc/chef/client.rb
        content: |
          chef_server_url "//chef-server.example.com"
          validation_client_name "my-validator"
Run with:
ansible-playbook -i inventory.ini install_chef.yml
You can use Ansible to install and configure Salt Minion on multiple servers:
- name: Install Salt Minion
  hosts: all
  tasks:
    - name: Install Salt Minion
      apt:
        name: salt-minion
        state: present

    - name: Configure Salt Minion
      copy:
        dest: /etc/salt/minion
        content: |
          master: salt-master.example.com
          id: {{ inventory_hostname }}

    - name: Start Salt Minion
      service:
        name: salt-minion
        state: started
        enabled: yes
Ansible simplifies Docker container management by automating:
  • Container deployment
  • Image building
  • Networking and volume management
  • Container orchestration
No. The control node doesn’t need Docker, but managed nodes should have Docker installed if you want to manage containers.
Create a playbook to install Docker on a remote machine:
- name: Install Docker
  hosts: all
  tasks:
    - name: Install dependencies
      apt:
        name: ['apt-transport-https', 'ca-certificates', 'curl', 'software-properties-common']
        state: present

    - name: Add Docker GPG key
      shell: curl -fsSL //download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

    - name: Add Docker repository
      shell: add-apt-repository "deb [arch=amd64] //download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

    - name: Install Docker
      apt:
        name: docker-ce
        state: present
Run it with:
ansible-playbook -i inventory.ini install_docker.yml
Example playbook to run an Nginx container:
- name: Run Nginx container
  hosts: all
  tasks:
    - name: Start a Docker container
      community.docker.docker_container:
        name: nginx_server
        image: nginx:latest
        state: started
        ports:
          - "80:80"
Run it with:
ansible-playbook -i inventory.ini deploy_nginx.yml
- name: Stop and remove a Docker container
  hosts: all
  tasks:
    - name: Stop container
      community.docker.docker_container:
        name: nginx_server
        state: stopped

    - name: Remove container
      community.docker.docker_container:
        name: nginx_server
        state: absent
- name: Pull Docker Image
  hosts: all
  tasks:
    - name: Pull Nginx image
      community.docker.docker_image:
        name: nginx
        source: pull
- name: Build Docker Image
  hosts: all
  tasks:
    - name: Build an image from a Dockerfile
      community.docker.docker_image:
        name: my_app
        tag: latest
        build:
          path: /path/to/dockerfile
- name: Push Docker Image
  hosts: all
  tasks:
    - name: Push image to Docker Hub
      community.docker.docker_image:
        name: my_dockerhub_user/my_app
        push: yes
        source: local
        repository: my_dockerhub_user/my_app
- name: Create Docker network
  hosts: all
  tasks:
    - name: Create custom network
      community.docker.docker_network:
        name: my_network
        state: present
- name: Create and mount Docker volume
  hosts: all
  tasks:
    - name: Create a Docker volume
      community.docker.docker_volume:
        name: my_volume

    - name: Run container with volume
      community.docker.docker_container:
        name: app_container
        image: my_app
        volumes:
          - my_volume:/app/data
Add the user to the Docker group:
- name: Add user to Docker group
  hosts: all
  tasks:
    - name: Add user to Docker group
      user:
        name: ansible
        groups: docker
        append: yes
- name: Login to a private registry
  hosts: all
  tasks:
    - name: Authenticate Docker
      community.docker.docker_login:
        registry_url: "//registry.example.com"
        username: my_user
        password: my_password
- name: Deploy Docker Compose Stack
  hosts: all
  tasks:
    - name: Copy docker-compose file
      copy:
        src: ./docker-compose.yml
        dest: /home/user/docker-compose.yml

    - name: Run Docker Compose
      community.docker.docker_compose:
        project_src: /home/user/
You can use Ansible to install a Kubernetes cluster on remote nodes. Example playbook to install Kubernetes on Ubuntu:
- name: Install Kubernetes Cluster
  hosts: all
  tasks:
    - name: Install dependencies
      apt:
        name: ['apt-transport-https', 'ca-certificates', 'curl']
        state: present

    - name: Add Kubernetes GPG key
      shell: curl -fsSL //packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -

    - name: Add Kubernetes repository
      shell: echo "deb //apt.kubernetes.io/ kubernetes-xenial main" | tee /etc/apt/sources.list.d/kubernetes.list

    - name: Install Kubernetes packages
      apt:
        name: ['kubelet', 'kubeadm', 'kubectl']
        state: present
Run with:
ansible-playbook -i inventory.ini install_k8s.yml
Use the k8s module to deploy a pod:
- name: Deploy a Kubernetes pod
  hosts: localhost
  tasks:
    - name: Create a pod
      community.kubernetes.k8s:
        api_version: v1
        kind: Pod
        namespace: default
        name: nginx-pod
        definition:
          metadata:
            labels:
              app: nginx
          spec:
            containers:
              - name: nginx
                image: nginx:latest
- name: Deploy a Kubernetes Service
  hosts: localhost
  tasks:
    - name: Create a Service
      community.kubernetes.k8s:
        api_version: v1
        kind: Service
        name: nginx-service
        namespace: default
        definition:
          metadata:
            labels:
              app: nginx
          spec:
            selector:
              app: nginx
            ports:
              - protocol: TCP
                port: 80
                targetPort: 80
- name: Scale a Kubernetes Deployment
  hosts: localhost
  tasks:
    - name: Scale deployment to 5 replicas
      community.kubernetes.k8s:
        api_version: apps/v1
        kind: Deployment
        name: nginx-deployment
        namespace: default
        definition:
          spec:
            replicas: 5
- name: Update Kubernetes Deployment Image
  hosts: localhost
  tasks:
    - name: Update deployment image
      community.kubernetes.k8s:
        api_version: apps/v1
        kind: Deployment
        name: nginx-deployment
        namespace: default
        definition:
          spec:
            template:
              spec:
                containers:
                  - name: nginx
                    image: nginx:1.21.6
Use Ansible to create a Kubernetes role and role binding:
- name: Create Kubernetes Role
  hosts: localhost
  tasks:
    - name: Create Role
      community.kubernetes.k8s:
        api_version: rbac.authorization.k8s.io/v1
        kind: Role
        name: pod-reader
        namespace: default
        definition:
          rules:
            - apiGroups: [""]
              resources: ["pods"]
              verbs: ["get", "watch", "list"]

    - name: Create RoleBinding
      community.kubernetes.k8s:
        api_version: rbac.authorization.k8s.io/v1
        kind: RoleBinding
        name: pod-reader-binding
        namespace: default
        definition:
          subjects:
            - kind: User
              name: ansible-user
              apiGroup: rbac.authorization.k8s.io
          roleRef:
            kind: Role
            name: pod-reader
            apiGroup: rbac.authorization.k8s.io

 

Share this post

Comment (1)

  • MahipalSinh Rana Reply

    It’s easy to understand, As for newbie in automation application deployment, it found really good and much-needed details for me. Thanks for sharing.

    April 20, 2018 at 3:48 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Blog