Wednesday, October 23, 2024

How to Install and Use Ansible on Docker Container

These lightweight, portable units of software package applications and their dependencies, offering flexibility and scalability. But managing multiple containers, each with its own configuration needs, can quickly become overwhelming. This is where Ansible steps in, providing a powerful and user-friendly solution for container automation.


Imagine deploying a complex application across multiple servers, each running its own set of containers. You need to tackle tasks like:

  • Configuration: Installing packages, managing user accounts, and configuring services on each server.

  • Deployment: Copying files, starting and stopping services, and configuring networking for the application.

  • Orchestration: Defining dependencies between containers, managing their lifecycles, and ensuring smooth collaboration within a multi-container environment.

Performing these tasks manually for each container is a recipe for disaster. It's tedious, error-prone, and prone to inconsistencies.

Ansible emerges as a savior, offering a simple and efficient way to automate container management tasks. Here's how it shines:

  • Simplified Complexities: Ansible uses intuitive YAML playbooks to define automation tasks. These playbooks are human-readable, making it easy to understand and maintain the automation logic.

  • Idempotency for Reliability: Ansible ensures that tasks are executed only when necessary. This idempotency feature prevents unintended side effects from repeated executions, ensuring consistent results every time.

  • Consistency Across the Board: Ansible guarantees consistent configuration across all your containers, regardless of the environment they are running in. This uniformity is crucial for maintaining application stability and reducing errors.

Ansible Container Workflow

Let's break down the typical Ansible container workflow:

  1. Create an Ansible Playbook: The first step involves defining the desired state of your container environment in a YAML playbook. This playbook outlines tasks like installing packages, configuring services, and deploying applications.

    ---
    - name: remote server
      hosts: all
      tasks:
        - name: Update packages on the remote server
          become: yes
          yum:
            name: "*"
            state: latest
    
        - name: create file 
          file:
            path: /tmp/ansible_test.txt
            state: touch
        

  2. Build a Docker Image with Ansible: Next, you create a Dockerfile that includes Ansible and your playbook. This Dockerfile forms the foundation for an image that will run Ansible commands inside your containers.

    FROM ubuntu:20.04
    
    ENV DEBIAN_FRONTEND=noninteractive
    
    # Install package and ansible 
    RUN apt-get update && \
        apt-get install -y software-properties-common && \
        apt-add-repository --yes --update ppa:ansible/ansible && \
        apt-get install -y ansible sshpass bash && \
        apt-get clean && \
        rm -rf /var/lib/apt/lists/*
    
    # dir ansible
    WORKDIR /ansible
    COPY ./playbooks /ansible/playbooks
        

  3. Run the Container and Execute Ansible: Finally, you launch a container from your image, mounting necessary volumes (like SSH keys for remote access). Ansible, running inside the container, executes the playbook, configuring your target environment as defined.

    # Inventory file for Ansible
    [all]
    192.168.215.2 ansible_user=remoteuser ansible_ssh_pass=password ansible_ssh_common_args='-o StrictHostKeyChecking=no'
    
    # Run Ansible
    docker run --rm -v $(pwd)/playbooks:/ansible/playbooks ansible-container ansible-playbook -i /ansible/playbooks/inventory.ini /ansible/playbooks/playbook.yml
       

    For example, if you need a container with a specific configuration for a Red Hat (UBI) environment, you could use this Dockerfile:

    
    FROM registry.access.redhat.com/ubi8/ubi:latest
    
    RUN yum -y update && \
        yum install -y openssh-server \
        sudo \
        which \
        && yum clean all
    
    RUN useradd -ms /bin/bash remoteuser && \
        echo 'remoteuser ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
    
    # Habilita SSH
    RUN mkdir /var/run/sshd
    RUN ssh-keygen -A
    
    RUN echo "PermitRootLogin yes" >> /etc/ssh/sshd_config && \
        echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config
    
    RUN echo 'remoteuser:password' | chpasswd
    
    EXPOSE 22
    
    CMD ["/usr/sbin/sshd", "-D"]
        

Benefits of Using Ansible in Containers

The combination of Ansible and Docker brings numerous advantages to the table:

  • Streamlined Development Workflow: Developers can leverage familiar Ansible playbooks to manage their development environments, ensuring consistency between development and production setups. This minimizes discrepancies and accelerates the development process.

  • Simplified CI/CD Pipelines: Ansible integrates seamlessly into CI/CD pipelines, automating container provisioning, deployment, and configuration. This automation streamlines the entire software delivery cycle, making it more efficient and reliable.

  • Enhanced Infrastructure as Code: Manage your entire container infrastructure, including container orchestration tools like Kubernetes, using Ansible playbooks. This "Infrastructure as Code" approach brings increased control, reproducibility, and transparency to your containerized environment.

Conclusion

Ansible and Docker form a powerful partnership for automating containerized environments. By harnessing Ansible's simplicity and power within Docker containers, you can streamline your workflows, improve consistency, and free up valuable resources to focus on developing innovative applications. Embrace the power of automation and unlock a new level of efficiency in your containerized world.

0 comments:

Post a Comment