These modules streamline system management tasks, making Ansible a versatile automation tool.
Using templates in Ansible playbooks enables dynamic configurations. Here's an example of applying an HTML template for an Nginx web server:
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.
---
- 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.
ansible-playbook your_playbook.yml
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home