Monday 28 August 2023

Automate Linux SysAdmin tasks with Ansible in 95+ examples - part 2


Ansible is a powerful open-source automation tool that allows you to manage and configure your infrastructure as code. Whether you're a beginner looking to install Ansible or an experienced user diving into advanced playbooks, this comprehensive guide has you covered. We'll walk you through various aspects of Ansible, from basic installations on different Linux distributions to executing complex automation tasks.



1. How to Install Ansible in Ubuntu 22.04 LTS

$ sudo apt update
$ sudo apt install ansible

Once installed, you can verify the installation:

$ ansible --version

Now, you're ready to use Ansible for automation tasks on your Ubuntu 22.04 system.

2. Ansible Ad-Hoc Commands: 

Example: Using the Ping Module and Retrieving Ansible Facts

$ ansible all -m ping

$ ansible all -m command -a "hostname"

$ ansible all -m setup

using the "ping" module, we executing commands, and retrieving Ansible facts from target node

3. Understanding Ansible Terminology: The Ansible Playbook Anatomy

Example: Creating and Running an Ansible Playbook

---
- name: Example Playbook
  hosts: web_servers
  tasks:
    - name: Ensure Nginx is installed
      apt:
        name: nginx
        state: present
      become: yes
    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started
      become: yes


This section delves into Ansible terminology, breaking down the key components of an Ansible playbook, including plays, tasks, modules, conditionals, loops, handlers, variables, and lists.

4.Practical Ansible Module Usage

Examples: Printing "Hello World!", Text, Variables, and Combinations


---
- name: Print Examples
  hosts: localhost
  tasks:
    - name: Print "Hello World!"
      debug:
        msg: "Hello World!"

    - name: Print a Text
      debug:
        msg: "This is a text."

    - name: Print a Variable
      debug:
        var: my_variable

    - name: Print Text and Variable Combination
      debug:
        msg: "Value of my_variable is {{ my_variable }}"


5. Edit Files with Ansible Modules

Example: Customizing the "sshd_config" File


---
- name: Edit SSH Configuration
  hosts: target_host
  tasks:
    - name: Customize sshd_config
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^#?PermitRootLogin'
        line: 'PermitRootLogin no'
        state: present
      become: yes


Here, we explore the Ansible "lineinfile" module to edit a single-line text in a file, focusing on customizing the "sshd_config" file.

6. Edit Multi-Line Text with Ansible Modules

---
- name: Edit Multi-Line Text
  hosts: target_host
  tasks:
    - name: Customize a configuration file
      ansible.builtin.blockinfile:
        path: /etc/myapp/myapp.conf
        block: |
          option1 = value1
          option2 = value2
        insertafter: EOF
      become: yes

This section covers the Ansible "blockinfile" module, allowing you to edit multi-line text in files.

7. Scheduling Tasks with Ansible Modules

---
- name: Schedule a Daily Backup
  hosts: target_host
  tasks:
    - name: Schedule a daily backup
      ansible.builtin.cron:
        name: "Daily Backup"
        minute: 0
        hour: 2
        job: "/usr/local/bin/backup.sh"


This section covers how to automate the scheduling of tasks using the Ansible "cron" module, allowing you to schedule commands to run at specific times.

8. Working with Ansible Vault

$ ansible-vault create secret.yml
$ ansible-vault view secret.yml
$ ansible-playbook --ask-vault-pass playbook.yml


This section introduces Ansible Vault for securely storing variables and files. We cover how to create, decrypt, and use Ansible Vaults in your playbooks.

9. Ansible Troubleshooting

$ ansible-playbook -i inventory.ini playbook.yml --limit target_host


10. Ansible Modules: Command vs. Shell
When it comes to executing commands on remote Linux hosts, Ansible provides two essential modules: command and shell.

Command Module: Use this when you need to execute a single command without shell processing. It's suitable for running simple, non-shell tasks like "ls" or "pwd."

Example:

---
- name: Using the Command Module
  hosts: target_host
  tasks:
    - name: Run a command
      ansible.builtin.command:
        cmd: ls /etc

Shell Module: This is more powerful and allows shell processing, meaning you can use pipes, redirections, and other shell features. It's suitable for running complex commands.

Example:

---
- name: Using the Shell Module
  hosts: target_host
  tasks:
    - name: Run a shell command
      ansible.builtin.shell:
        cmd: ls /etc | grep ssh


Choose the module that best suits your task, keeping simplicity and security in mind.


11. Ansible Modules for System Management
Ansible provides various modules for managing systems. Let's look at some practical examples:

Pause Module: Sometimes you need to introduce delays between tasks. The pause module helps in such cases.

---
- name: Pause for a while
  hosts: localhost
  tasks:
    - name: Pause for 5 seconds
      ansible.builtin.pause:
        seconds: 5


Reboot Module: Rebooting remote hosts can be managed gracefully with the reboot module.

---
- name: Reboot a server
  hosts: target_host
  tasks:
    - name: Reboot the system
      ansible.builtin.reboot:


Git Module: If your infrastructure includes code repositories, Ansible can handle Git operations.

---
- name: Clone a Git repository
  hosts: target_host
  tasks:
    - name: Clone a Git repository
      ansible.builtin.git:
        repo: https://github.com/your/repo.git
        dest: /path/to/destination


These modules streamline system management tasks, making Ansible a versatile automation tool.

12. File Operations with Ansible Modules
Copying files to and from remote hosts is a common automation task. Ansible provides two modules for this:

Copy Module: Use it to copy files and directories to remote hosts.

---
- name: Copy files to a server
  hosts: target_host
  tasks:
    - name: Copy a file
      ansible.builtin.copy:
        src: /path/to/local/file
        dest: /path/to/remote/destination


Fetch Module: Retrieve files from remote hosts.

---
- name: Fetch files from a server
  hosts: target_host
  tasks:
    - name: Fetch a file
      ansible.builtin.fetch:
        src: /path/to/remote/file
        dest: /path/to/local/destination


These modules make managing files a breeze.

13. Managing Services with Ansible Modules
Managing services on remote hosts is crucial for system administrators. Ansible simplifies this with the service_facts and service modules:

Service Facts Module: Retrieve information about services on remote hosts.

---
- name: Get service facts
  hosts: target_host
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

Service Module: Control services by starting, stopping, or restarting them.

---
- name: Manage a service
  hosts: target_host
  tasks:
    - name: Ensure a service is running
      ansible.builtin.service:
        name: service_name
        state: started

These modules simplify the management of services, ensuring they are running as expected.

14. Templating in Ansible Playbooks

Using templates in Ansible playbooks enables dynamic configurations. Here's an example of applying an HTML template for an Nginx web server:

---
- name: Configure Nginx
  hosts: web_servers
  tasks:
    - name: Create Nginx config file
      ansible.builtin.template:
        src: /path/to/nginx.conf.j2
        dest: /etc/nginx/nginx.conf


In this example, Ansible fills in the template variables defined in the Jinja2 template file (nginx.conf.j2) and deploys it to the Nginx configuration directory.

15. Managing Files and Directories with Ansible Modules
File and directory operations are fundamental in automation. Ansible modules like file, assemble, and unarchive can help:

File Module: Create, delete, or modify files and directories.

---
- name: Create a directory
  hosts: target_host
  tasks:
    - name: Create a directory
      ansible.builtin.file:
        path: /path/to/directory
        state: directory


Unarchive Module: Extract files from archives like ZIP or TAR.

---
- name: Extract an archive
  hosts: target_host
  tasks:
    - name: Unarchive a ZIP file
      ansible.builtin.unarchive:
        src: /path/to/archive.zip
        dest: /path/to/extract/location


These modules provide precise control over file and directory operations.

16. Ansible Module: Kernel Modules, Kernel Parameters, and Kernel Configuration

Managing Linux kernel modules and parameters is vital for system optimization. Ansible simplifies this with modules like modprobe and sysctl:

Modprobe Module: Load or remove kernel modules.

---
- name: Load a kernel module
  hosts: target_host
  tasks:
    - name: Load a kernel module
      ansible.builtin.modprobe:
        name: module_name


Sysctl Module: Configure kernel parameters.


---
- name: Configure a kernel parameter
  hosts: target_host
  tasks:
    - name: Configure a kernel parameter
      ansible.builtin.sysctl:
        name: parameter_name
        value: parameter_value

These modules empower you to optimize your system's performance.

17. Advanced Ansible Playbook Techniques
Finally, let's explore advanced playbook techniques. Here are two examples:

Safely Limiting Playbook Execution
You have a playbook that should only be executed on a specific machine within your inventory. You want to ensure it doesn't accidentally run on other hosts.

Suppose you have an inventory file (inventory.ini) like this:

[web]
server1 ansible_host=192.168.1.10
server2 ansible_host=192.168.1.11
server3 ansible_host=192.168.1.12

Your playbook (my_playbook.yml) looks like this:


---
- name: My Playbook
  hosts: web
  tasks:
    - name: Task to run on all web servers
      ansible.builtin.command: echo "This task runs on all web servers."


To limit playbook execution to a single machine, use the --limit flag with the specific host or group name:

$ ansible-playbook -i inventory.ini my_playbook.yml --limit server1

This command ensures that the playbook runs only on server1. Adjust the host name as needed.

18.Selecting Specific Tasks with Tags

You have a complex playbook with multiple tasks, and you want to run only specific tasks during execution. Tags help you achieve this.

Suppose your playbook (complex_playbook.yml) contains various tasks with assigned tags:

---
- name: Complex Playbook
  hosts: web
  tasks:
    - name: Task 1
      ansible.builtin.command: echo "This is Task 1."
      tags: task1

    - name: Task 2
      ansible.builtin.command: echo "This is Task 2."
      tags: task2

    - name: Task 3
      ansible.builtin.command: echo "This is Task 3."
      tags: task3


To run tasks with specific tags, use the --tags flag:


$ ansible-playbook complex_playbook.yml --tags task1,task2


This command executes only tasks tagged as task1 and task2. You can comma-separate multiple tags to run tasks belonging to those tags.

These advanced playbook techniques provide granular control over Ansible's execution, ensuring that your automation runs efficiently and effectively in various scenarios.

Selecting Specific Tasks with Tags: Assign tags to tasks in your playbook and execute only tagged tasks.

---
- name: My Playbook
  hosts: target_host
  tasks:
    - name: Task 1
      ansible.builtin.command: echo "Task 1"
      tags: task1

    - name: Task 2
      ansible.builtin.command: echo "Task 2"
      tags: task2


Run specific tasks with tags:

$ ansible-playbook playbook.yml --tags task1


19.Ansible Playbook Components: Plays and Tasks: 
Ansible playbooks are made up of plays, which are a set of tasks that run on a specific set of hosts. Tasks are the individual steps that make up a play. 

Here is an example playbook that installs Apache on a group of web servers:

- name: Install Apache
  hosts: webservers
  become: true
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present


20.Conditional Statements in Ansible Playbooks: 
Conditional statements can be used to control the flow of an Ansible playbook. Here is an example playbook that installs Apache only if it is not already installed:

- name: Install Apache if not installed
  hosts: webservers
  become: true
  tasks:
    - name: Check if Apache is installed
      stat:
        path: /etc/apache2/apache2.conf
      register: apache_installed

    - name: Install Apache
      apt:
        name: apache2
        state: present
      when: apache_installed.stat.exists == false

21.Using Loops in Ansible Playbooks: 

Loops can be used to iterate over a list of items in an Ansible playbook. Here is an example playbook that installs multiple packages using a loop:

- name: Install packages with loop
  hosts: webservers
  become: true
  vars:
    packages:
      - apache2
      - mysql-server
      - php7.0

  tasks:
    - name: Install packages with loop
      apt:
        name: "{{ item }}"
        state: present
      loop: "{{ packages }}"

22.Error Handling with Handlers in Ansible: 

Handlers are used to respond to events triggered by tasks in an Ansible playbook. Here is an example playbook that restarts Apache if its configuration file is changed:

- name: Update Apache config file and restart service if needed.
  hosts: webservers
  become: true

  tasks:
    - name: Update Apache config file.
      template:
        src: /path/to/apache.conf.j2
        dest: /etc/apache2/apache2.conf

    - name: Restart Apache service.
      service:
        name: apache2
        state: restarted

      notify:
        - Restart Apache service.
  
  handlers:
    - name: Restart Apache service.
      service:
        name: apache2
        state: restarted


23.Managing Variables in Ansible: 

Variables can be used to store data that can be used throughout an Ansible playbook. Here is an example playbook that uses variables to install different packages on different types of servers:

- name: Install packages based on server type.
  hosts:
    - webservers
    - databaseservers

  vars:
    webserver_packages:
      - apache2

    database_packages:
      - mysql-server

  tasks:
    - name: Install packages based on server type.
      apt:
        name: "{{ webserver_packages if 'web' in group_names else database_packages }}"
        state: present


 24. Working with Lists in Ansible: 

Lists can be used to store multiple values in a single variable in an Ansible playbook. Here is an example playbook that uses lists to install multiple packages:

- name: Install multiple packages.
  hosts:
    - webservers

  vars:
    packages_to_install:
      - apache2
      - mysql-server

  tasks:
    - name: Install multiple packages.
      apt:
        name: "{{ item }}"
        state: present

      loop_control:
        loop_var: item


25.Real-Life Examples with Ansible Printing: 

The debug module in Ansible can be used to print messages during playbook execution. Here is an example playbook that uses the debug module:

- name: Print message
  hosts: all
  tasks:
    - name: Print message
      debug:
        msg: "Hello, world!"


26.Command Module vs. Shell Module in Ansible: 

The command module in Ansible is used to execute commands on remote hosts, while the shell module is used to execute shell commands on remote hosts. Here is an example playbook that uses both modules:

- name: Execute commands
  hosts: all
  tasks:
    - name: Execute command
      command: whoami

    - name: Execute shell command
      shell: echo $HOME


27.Editing Single Line Text with Ansible lineinfile: 

The lineinfile module in Ansible can be used to edit a single line of text in a file. Here is an example playbook that uses the lineinfile module:

- name: Edit single line of text in file
  hosts: all
  tasks:
    - name: Edit single line of text in file
      lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.0\.1'
        line: '127.0.0.1 localhost'


28.Editing Multi-Line Text with Ansible blockinfile: 

The blockinfile module in Ansible can be used to edit multiple lines of text in a file. Here is an example playbook that uses the blockinfile module:

- name: Edit multiple lines of text in file
  hosts: all
  tasks:
    - name: Edit multiple lines of text in file
      blockinfile:
        path: /etc/hosts
        block: |
          # Block of text to add or modify.
          # This can be multiple lines.
          # Make sure to include a trailing newline.
        marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item }}"
        insertafter: '^#.*foo.*$'
      loop:
        - first_block_of_text_to_add_or_modify
        - second_block_of_text_to_add_or_modify


29.Pausing Execution in Ansible Playbooks: 

The pause module in Ansible can be used to pause playbook execution for a specified amount of time. Here is an example playbook that uses the pause module:

- name: Pause execution for 5 seconds
  hosts: all
  tasks:
    - name: Pause execution for 5 seconds
      pause:
        seconds: 5


30.Rebooting Remote Hosts with Ansible: 

The reboot module in Ansible can be used to reboot remote hosts. Here is an example playbook that uses the reboot module:

- name: Reboot remote host(s)
  hosts: all
  tasks:
    - name: Reboot remote host(s)
      reboot:
        reboot_timeout: 300 # Wait up to 5 minutes for host(s) to come back online.


31.Using Loops in File Templates with Ansible: 

Loops can be used to iterate over a list of items in a file template. Here is an example playbook that uses loops in a file template:

- name: Apply file template with loop
  hosts: webservers
  become: true
  vars:
    users:
      - name: alice
        uid: 1001
      - name: bob
        uid: 1002

  tasks:
    - name: Apply file template with loop
      template:
        src: /path/to/template.j2
        dest: /etc/users.conf

      loop: "{{ users }}"


32.Scheduling Cron Jobs with Ansible: 

The cron module in Ansible can be used to schedule cron jobs on remote hosts. Here is an example playbook that uses the cron module:

- name: Schedule cron job
  hosts: all
  tasks:
    - name: Schedule cron job
      cron:
        name: "My Cron Job"
        minute: "0"
        hour: "0"
        job: "/path/to/script.sh"


33.Making GET Requests to REST APIs with Ansible: 

The uri module in Ansible can be used to make GET requests to REST APIs. Here is an example playbook that uses the uri module:

- name: Make GET request to REST API
  hosts: all
  tasks:
    - name: Make GET request to REST API
      uri:
        url: "https://api.example.com/data"
        method: GET

      register: api_response

    - name: Print API response
      debug:
        var: api_response.json


34.Token-Based Authentication in REST APIs with Ansible: 

Token-based authentication can be used to authenticate requests to REST APIs. Here is an example playbook that uses token-based authentication:

- name: Make authenticated GET request to REST API
  hosts: all
  tasks:
    - name: Get authentication token
      uri:
        url: "https://auth.example.com/token"
        method: POST
        body_format: json
        body:
          username: "myusername"
          password: "mypassword"

      register: auth_token

    - name: Make authenticated GET request to REST API
      uri:
        url: "https://api.example.com/data"
        method: GET
        headers:
          Authorization: "Bearer {{ auth_token.json.access_token }}"

      register: api_response

    - name: Print API response
      debug:
        var: api_response.json


35.Breaking Strings Over Multiple Lines in Ansible: 

Strings can be broken over multiple lines in an Ansible playbook using the > character. Here is an example playbook that uses this feature:

- name: Break string over multiple lines.
  hosts:
    - webservers

  vars:
    my_string: >
      This is a very long string that needs to be broken over multiple lines.
      Fortunately, Ansible makes this easy using the > character.

  tasks:
    - name: Print string.
      debug:
        var: my_string


36.Copying Files to Remote Hosts with Ansible: 

The copy module in Ansible can be used to copy files to remote hosts. Here is an example playbook that uses the copy module:

- name: Copy file to remote host
  hosts: all
  tasks:
    - name: Copy file to remote host
      copy:
        src: /path/to/local/file
        dest: /path/to/remote/file


37.Copying Files from Remote Hosts with Ansible: 

The fetch module in Ansible can be used to copy files from remote hosts. Here is an example playbook that uses the fetch module:

- name: Copy file from remote host
  hosts: all
  tasks:
    - name: Copy file from remote host
      fetch:
        src: /path/to/remote/file
        dest: /path/to/local/file


38.Managing Services on Remote Hosts with Ansible: 

The service module in Ansible can be used to manage services on remote hosts. Here is an example playbook that uses the service module:

- name: Manage service on remote host
  hosts: all
  tasks:
    - name: Manage service on remote host
      service:
        name: apache2
        state: started


39.Restarting Services with Ansible: 

The service module in Ansible can also be used to restart services on remote hosts. Here is an example playbook that uses the service module to restart Apache:

- name: Restart Apache service on remote host
  hosts: all
  tasks:
    - name: Restart Apache service on remote host
      service:
        name: apache2
        state: restarted


40.Applying File Templates with Ansible: 

File templates can be used to generate configuration files from templates. Here is an example playbook that uses a file template:

- name: Apply file template to generate configuration file.
  hosts:
    - webservers

  vars:
    server_name: myserver.example.com

  tasks:
    - name: Apply file template.
      template:
        src: /path/to/template.j2
        dest: /etc/apache2/sites-available/myserver.conf

      vars:
        server_name: "{{ server_name }}"


41.Scheduling Cron Jobs with Ansible: 

The cron module in Ansible can be used to schedule cron jobs on remote hosts. Here is an example playbook that uses the cron module:

- name: Schedule cron job on remote host.
  hosts:
    - webservers

  tasks:
    - name: Schedule cron job.
      cron:
        minute: "0"
        hour: "0"
        job: "/path/to/script.sh"


42.Making GET Requests to REST APIs with Ansible: 

The uri module in Ansible can be used to make GET requests to REST APIs. Here is an example playbook that uses the uri module:

- name: Make GET request to REST API.
  hosts:
    - webservers

  tasks:
    - name: Make GET request to REST API.
      uri:
        url: "https://api.example.com/data"
        method: GET

      register: api_response

    - name: Print API response.
      debug:
        var: api_response.json


43.Running a Single Task in an Ansible Playbook: 

The --start-at-task option in Ansible can be used to run a single task in a playbook. Here is an example command that uses this option:

ansible-playbook playbook.yml --start-at-task="Task Name"


44.Deploying Apache Web Server in a Docker Container on Debian-like Systems: 

Docker can be used to deploy Apache web server in a container on Debian-like systems. Here is an example playbook that uses Docker to deploy Apache:


- name: Deploy Apache web server in a Docker container on Debian-like systems.
  hosts:
    - webservers

  tasks:
    - name: Install Docker.
      apt:
        name: docker.io
        state: present

    - name: Start Docker service.
      service:
        name: docker
        state: started

    - name: Deploy Apache web server in a Docker container.
      docker_container:
        name: apache
        image: httpd
        ports:
          - "80:80"


45.Deploying Apache Web Server in a Podman Container on RedHat-like Systems: 

Podman can be used to deploy Apache web server in a container on RedHat-like systems. Here is an example playbook that uses Podman to deploy Apache:


- name: Deploy Apache web server in a Podman container on RedHat-like systems.
  hosts:
    - webservers

  tasks:
    - name: Install Podman.
      yum:
        name: podman
        state: present

    - name: Deploy Apache web server in a Podman container.
      podman_container:
        name: apache
        image: httpd
        ports:
          - "80:80"


46.Reducing Intel Laptop CPU Temperature in Linux with Ansible: 

The cpufreq module in Ansible can be used to reduce the CPU frequency of an Intel laptop CPU, which can help reduce the temperature of the CPU. 

Here is an example playbook that uses the cpufreq module:

- name: Reduce Intel laptop CPU temperature in Linux with Ansible.
  hosts:
    - laptops

  tasks:
    - name: Reduce CPU frequency.
      cpufreq:
        governor: powersave


47.Running a Python Script on Remote Machines with Ansible: 

The script module in Ansible can be used to run a Python script on remote machines. Here is an example playbook that uses the script module:

- name: Run Python script on remote machines.
  hosts:
    - all

  tasks:
    - name: Run Python script on remote machines.
      script:
        src: /path/to/script.py


48.Reading a JSON File into a Variable with Ansible: 

The lookup module in Ansible can be used to read the contents of a JSON file into a variable. Here is an example playbook that uses the lookup module:

- name: Read JSON file into variable.
  hosts:
    - all

  tasks:
    - name: Read JSON file into variable.
      set_fact:
        my_variable: "{{ lookup('file', '/path/to/file.json') | from_json }}"


49.Understanding Ansible Vault: 

Ansible Vault is a feature of Ansible that allows you to encrypt sensitive data such as passwords and API keys. 

ansible-vault encrypt /path/to/file.yml

50.Decrypting an Ansible Vault

You have an Ansible Vault-encrypted file and need to decrypt it to access the secrets.

ansible-vault decrypt secret_file.yml

Ansible will prompt you for the Vault password used to encrypt the file.

You can now access the decrypted data in secret_file.yml.

51.Using Ansible Vault in Ansible Playbooks

You can to use Ansible Vault to encrypt sensitive variables in your Ansible playbooks.


---
- name: Example Playbook
  hosts: localhost
  vars:
    sensitive_data: !vault |
      $ANSIBLE_VAULT;1.1;AES256
      66366232396135343865393765653837646562306361623863343535333563373362393865393338

You can create this encrypted variable using ansible-vault encrypt_string.

Run Playbook

ansible-playbook your_playbook.yml

Labels: , ,

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home