Ansible

GitHub Actions in Ansible

Ansible is a popular, free, and open-source automation tool that allows us to automate the DevOps tasks such as config management, app deployment,  etc.

Combining Ansible with GitHub Actions allows us to automate the execution of Ansible playbooks whenever a specific event occurs in a repository, like a push to the main branch.

This tutorial teaches you how to set up a GitHub Action to run an Ansible playbook which is useful for automating the deployment in response to code changes.

Prerequisites:

Before proceeding, ensure that you have the following:

  • A GitHub account
  • An existing GitHub repository
  • Basic knowledge of Ansible playbooks
  • A target machine where Ansible can run the tasks. Ensure that Ansible can connect to these machines from a GitHub runner.

Step 1: Setup the Ansible Environment

Create and store the Ansible playbook and all related files in the GitHub repository. This should include files such as the roles templates, variables, etc.

An example playbook is as follows:

---
- name: Ensure Nginx is installed on web servers
hosts: webserver
become: yes
tasks:
    - name: Update apt cache
      apt:
        update_cache: yes

    - name: Install Nginx
      apt:
        name: nginx
        state: present

Ensure that you have an inventory file specifying the target machines for Ansible.

Step 2: Setup the Secrets in GitHub Repository

Given that the playbook needs sensitive information like SSH keys or passwords, GitHub provides a way to store the secrets securely:

Navigate to your GitHub repository.

Go to Settings > Secrets and Variables -> Actions  -> New Repository secret.

Step 3: Create the GitHub Action Workflow

In the repository, create a “.github/workflows” directory. Inside this directory, create a YAML file for your workflow.

Add the workflow as follows:

name: Run Ansible Playbook
on:
  push:
    branches:
      - master
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
      uses: actions/checkout@v2
    - name: Setting up SSH key
      run: |
        echo "${{ secrets.SSH_PRIVATE_KEY }}" > private_key.pem
        chmod 600 private_key.pem
    - name: Run Ansible Playbook
      run: |
        sudo apt update
        sudo apt install -y ansible
        ansible-playbook -i hosts.ini my-playbook.yml --private-key=private_key.pem --user=${{ secrets.REMOTE_USER }}

Step 4: Trigger the Workflow

Whenever you push to the master branch, GitHub will automatically run this workflow and thus executes the playbook.

Conclusion

That’s it for this one. We covered how to run an Ansible playbook using the Github actions.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list