How Use the Same Task Again in Playbook Ansible

One of the core components of Ansible is a playbook file. Ansible uses playbook files to define complex tasks that are executed confronting managed nodes with limited user involvement.

In this guide, you will learn how to create and use Ansible playbook files to execute tasks on managed nodes.

What is Ansible Playbook?

A playbook is essentially a YAML file that comprises ane or multiple plays. A play is a set of ordered tasks to be executed against managed hosts that are specified in the /etc/ansible/hosts file. Each play in a playbook represents a unique task with surround-specific parameters for the target hosts.

Playbooks are quite flexible and can be reused indefinitely with multiple servers to perform the same tasks. Ansible playbooks are often used for server configuration, network device management and application deployment tasks.

Prerequisites

To follow this guide, you should have:

  • A control node with Ubuntu xx.04 operating system and Ansible installed. If you haven't installed Ansible before, follow our guide on How to Install and Configure Ansible on Ubuntu 20.04.
  • A single managed node configured in the command node's hosts file that volition exist used to run the playbook tasks.

Create Ansible Playbook

Let's start by making and running our first Ansible playbook. On the command node create a simple YAML file in the /etc/ansible/ directory as follows:

          sudo vim /etc/ansible/playbook-01.yml                  

At present populate the playbook file with the following code:

          --- - name: A simple playbook file   hosts: all   tasks:   	- name: Print a sample message       debug:        	msg: How-do-you-do World. Welcome to Ansible playbooks!                  

The --- marks the starting time of the YAML file.

The offset instance of the name directive specifies the name of the play. The 2nd example specifies the name of the task.

The hosts directive specifies the target hosts on which the playbook will be executed. In this case, the playbook will run on all the hosts specified in the inventory file. To target a specific host, provide the host's IP accost or domain proper name.

The tasks directive is a listing of tasks to exist executed on the target host. In this playbook, nosotros have one chore which prints a statement to stdout.

The debug keyword is a built-in module that comes with Ansible and prints statements during Playbook runtime. In addition, information technology comes in handy when debugging statements and variables without halting a playbook. The debug module comes with some options such equally msg and var. The msg pick specifies the string to the printed to stdout.

Execute Ansible Playbook

To run the playbook, apply the ansible-playbook command equally shown below:

          ansible-playbook /path/to/playbook_file                  

In our case, you lot should run the post-obit command:

          ansible-playbook /etc/ansible/playbook-01.yml                  

During playbook execution, yous should see the following output:

Run Ansible playbook

Notice that two tasks were carried out, even though we divers only ane in the Playbook file.

The first chore gathers facts well-nigh the managed node. Ansible facts refer to host-specific system data that is presented in JSON format such as BIOS information, system date and fourth dimension, OS type and version and IP address. It as well includes hardware information such equally the block devices, CPU, RAM, and swap infinite to name a few.

The 2nd task prints a simple message to stdout as specified in the playbook file. The ok=2 indicates that two tasks were successfully executed.

If yous are curious to get a list of all the Ansible facts, execute the following command:

          ansible -m setup all                  

List all Ansible facts

Ansible Playbook Modules

Ansible modules are standalone reusable Python scripts that are referenced in Playbooks to help execute specific tasks on managed nodes. Ansible modules can automate a wide option of tasks on managed nodes including packet direction, service management, file management and and then much more.

In this department, we will demonstrate how y'all tin can reach various arrangement administration tasks by incorporating modules in Playbooks.

Package Management Modules

Managing software packages is an essential system administration task. It specifically deals with installing and removing software packages in Linux servers. Ansible provides built-in package management modules for major Linux distributions as shown.

Module Linux Distribution
apt Debian / Ubuntu variants
yum / dnf RHEL variants such equally CentOS / Rocky
pacman Arch Linux and Arch variants
zypper OpenSUSE

The following playbook file installs the Apache webserver on the remote target defined nether the webserver sub-group in the inventory file. The apt module provides two options: the proper name option which specifies the name of the package ( apache2 ) and the state pick which instructs Ansible to install the latest version of Apache.

          --- - name: install Apache   hosts: webserver   tasks:   	- proper name: install Apache webserver on Ubuntu       apt:       	proper name: apache2         country: latest                  

Upon running the playbook file, you should get like output to what nosotros accept:

          ansible-playbook /etc/ansible/playbook-02-install-apache.yml                  

On RHEL 8 and CentOS 8, the same task can be accomplished using the dnf module. Here, the Apache package for RedHat derivatives is defined by httpd.

Service Module

You can also use modules to outset, stop and restart running services on managed nodes. For example, to restart the Apache webserver, we volition use the service module in the playbook shown.

          --- - name: Restart Apache   hosts: webserver   tasks:   	- name: Restart Apachce webserver       service:       	proper noun: apache2         state: restarted                  

Hither is the output of the Playbook execution:

Run Ansible playbook

Hither's a playbook showing how you can cease the webserver. Notation the change of the country parameter from restarted to stop.

          --- - name: Stop Apache   hosts: webserver   tasks:   	- proper name: Stop Apache webserver       service:       	proper noun: apache2         land: stopped                  

From the output of the playbook execution, you can see that the task was successful:

Run Ansible playbook

To showtime the webserver, set the state parameter to started.

          --- - name: Commencement Apache   hosts: webserver   tasks:   	- name: Start Apache webserver       service:       	name: apache2         state: started                  

Once again, here is the output of the playbook execution:

Run Ansible playbook

Copy Module

Another useful module is the copy module. As the proper name suggests, the module is used for copying files from one location to another. You tin copy files from the Ansible controller to the remote node or re-create files from one location to another inside the remote node.

In the Playbook file below, we are copying the sales_report.txt file from the Ansible control node to the remote server in the /tmp/reports/ directory. In addition, nosotros take assigned the possessor and group ownership to the red user using the owner and group options. The fashion option assigns the octal file permissions 0644 to the file.

          --- - name: Ansible re-create module example   hosts: webserver   tasks:   	- name: Re-create files from command node to remote node       copy:       	src: /home/user/Documents/sales_report.txt         dest: /tmp/reports/         owner: reddish         group: cherry         mode 0644                  

The consequence of the Playbook execution is printed equally shown:

Run Ansible playbook

To copy files within the remote node, use the remote_src option and prepare it to aye. In the example beneath we are making a backup re-create of apache2.conf configuration file on the remote node. Merely put, nosotros are making a copy of the file and renaming it to apache2.conf.back.

          --- - name: Ansible copy module case   hosts: webserver   tasks:   	- name: Copy files within the remote node       copy:       	src: /etc/apache2/apache2.conf         dest: /etc/apache2/apache2.conf.bak         remote_src: yes                  

The playbook runs successfully as shown:

Run Ansible playbook

Lineinfile Module

The lineinfile module is a module that is used for performing a wide selection of tasks on a line such as modifying, replacing, or calculation a single line to a file. It can be used in conjunction with regex expressions to match specific lines and make changes.

To demonstrate its functionality, let us take a few examples. The playbook modifies the SSH service configuration on the remote target past changing 2 parameters. The get-go task sets the ClientAliveInterval directive to
15 while the 2d task sets the ClientAliveCountMax directive to 4. The regexp pick matches the lines that contain the parameters we are trying to change.

          --- - name: Configure SSH   hosts: webserver   tasks:   	- proper noun: Ensure ClientAliveInterval is set to fifteen       lineinfile:       	path: /etc/ssh/sshd_config         regexp: "^ClientAliveInterval"         line: ClientAliveInterval=15     - name: Ensure ClientAliveCountMax is set to 4       lineinfile:       	path: /etc/ssh/sshd_config         regexp: "^ClientAliveCountMax"         line: ClientAliveCountMax=four                  

The playbook executes both tasks in order of appearance - from the commencement to the last:

Run Ansible playbook

💡 Pro Tip: In the example to a higher place, nosotros are trying to match a line that starts with ClientAliveInterval string. Some lines in Linux configuration files may be commented out (i.eastward. # ClientActiveInterval). In such case, the regex won't match, so the lineinfile module will create a new line with the specified string for you.

To add a line to a file, specify the full path of the file, the line to exist added to the file, and set the create choice to aye.

The playbook shown adds a new line 173.82.120.115 cherry.localdomain to the /etc/hosts file on the remote node.

          --- - name: Add a new line to a file   hosts: webserver   tasks:   	- proper name: Add together a new line to a file       lineinfile:       	path: /etc/hosts         line: 173.82.120.115 ruby-red.localdomain         create: yes                  

Here is the Playbook execution:

Run Ansible playbook

Control Module

The Command module takes a command proper noun followed by a list of arguments. The control is executed on target nodes, but the output is not displayed to stdout.

The playbook shown runs the "uptime" and "date" commands on the target modes.

          --- - name: Execute commands on remote targets   hosts: webserver   tasks:   	- name: Execute the uptime command       control: "uptime"            - name: Execute the date command       command: "date"                  

The playbook runs successfully, however, no output from the commands is printed out.

Run Ansible playbook

To print the result to stdout, use the shell module. The output of both commands is captured past the register pick using our defined uptime_var and date_var variables. These variables are eventually referenced by the msg selection, and the values printed to stdout.

          --- - name: Execute commands on remote targets   hosts: webserver   tasks:     - name: Execute the uptime command       shell: "uptime"       annals: uptime_var            - debug:       	msg: "{{uptime_var.stdout}}"              - name: Execute the date command       shell: "date"       register: date_var            - debug:       	msg: "{{date_var.stdout}}"                  

In the playbook execution output, you tin run across the output of both commands printed:

Run Ansible playbook

And then far, we have demonstrated only a handful of modules. There are hundreds upon hundreds of Ansible modules for performing unlike tasks. For a more than comprehensive listing of Ansible modules, visit the Ansible Modules documentation page.

Ansible Playbook Variables

If you are a developer or a programmer, chances are that you lot take used variables countless times in your code. Like in many programming languages, variables are used in Playbooks to store values. Y'all can assign a value to a variable and reference it anywhere within the playbook.

Variables can also come from external sources, such as variable files, and then be referenced in a Playbook. Special precedence rules utilise when working with variables from multiple sources that bear the same name.

To demonstrate how variables are used in exercise, let'due south create a playbook file that will print out the value of ii variables: greetings and topic.

          --- - proper noun: Ansible variables in practice   hosts: webserver   vars:   	greetings: Hello World!     topic: Ansible Playbooks        tasks:   - proper name: Ansible basic variable example     debug:     	msg: "{{ greetings }}, let's learn {{ topic }}."                  

The vars department defines the listing of variables that will be referenced by the debug module in the scope of the play. These variables are attainable to all the tasks and files specified within the playbook file.

In the output, the values assigned to the variables have been printed to stdout in the identify of the variable names.

Run Ansible playbook

Alternatively, you tin can accept a list of variable items. In the playbook beneath, permit'southward define a variable chosen oceans with a list of 5 values that stand for the five oceans.

          --- - name: Ansible list variable example   hosts: webserver   vars:   	oceans:   	  - Indian       - Atlantic       - Pacific       - Artic       - Southern Antarctic      tasks:     - name: Ansible list variables case       debug:       	msg: "The five oceans in the earth are {{ oceans }}"                  

The playbook iterates through the listing of values under the vars section and prints them to stdout using the msg option.

Run Ansible playbook

In addition, you tin can admission each of the values in the variable using the index [ x ] aspect in the msg directive where ten is the value of the item in the list. The showtime item is denoted by index[0]. For example, to access the tertiary item on the list, nosotros will alter the referencing as

Ansible Playbook Conditionals

Provisional statements are used when you need to execute a gear up of tasks based on certain criteria. In Ansible Playbooks when is a widely used conditional statement that is used with OR and AND operators.

To meliorate elaborate how conditional statements work, we will take a simple setup with two managed nodes of different OS families:

Server IP: 173.82.120.115 Ubuntu 20.04

Server IP: 173.82.255.207 CentOS 8.three

Using 'when' Argument

Consider the Playbook beneath. The when statement instructs the Playbook to install Nginx webserver on all the servers that belong to the Debian OS family. Nosotros are using the ansible_os_family variable here that belongs to the Ansible facts object, and then you don't need to ascertain information technology in your playbook.

          --- - name: Ansible when conditional argument   hosts: all   tasks:   	- name: install nginx webserver       apt:       	name: nginx         state: latest                when: ansible_os_family == "Debian"                  

From the output of the playbook execution, we can see that the CentOS host has been excluded since information technology does not satisfy our condition.

Run Ansible playbook

Using 'AND' Operator with 'when' Statement

When using the and operator, both conditions MUST be satisfied. In this example, the playbook will run the task successfully if the managed nodes belong to the Debian Linux family unit and whose release number is 20.04.

          --- - name: Ansible when-and conditional argument   hosts: all   tasks:   	- name: install nginx webserver       apt:       	proper noun: nginx         state: latest                when: ansible_os_family == "Debian" and ansible_distribution_version == "20.04"                  

Since the Ubuntu node matches the criteria, the playbook volition successfully run and install Nginx on information technology simply skip the CentOS 8 server.

Run Ansible playbook

Using 'OR' Operator with 'when' Argument

With or operator a task volition be executed if either condition is met. In the following Playbook, a new directory called data is created in the habitation directories of managed nodes that belong to either Debian or RedHat Linux families.

          --- - proper name: Ansible when-or conditional statement   hosts: all   tasks:   	- name: "create a directory if it doesn't exist"       file:       	path: $Dwelling house/data         country: directory         mode: "0777"                when: ansible_os_family == "Debian" or ansible_os_family == "RedHat"                  

Predictably, the directory is created on both managed nodes since both belong to either of the two OS families.

And just to confirm this, we will listing the contents of the abode directories on both nodes.

          ssh root@173.82.255.207 "ls -l" ssh root@173.82.120.115 "ls -fifty"                  

Run Ansible playbook

Ansible Playbook Loops

Occasionally, you lot will find yourself performing repetitive tasks that require you to write multiple tasks performing the aforementioned functioning. Take, for example, a playbook that creates new users on a target organization as shown.

          --- - name: Create new usersr on remote machine   hosts: 173.82.120.115   tasks:   	- name: Create new user Alice       user:       	name: alice         state: present     - proper noun: Create new user Patric       user:       	name: patric         country: present     - name: Create new user Tom       user:       	proper name: tom         land: present                  

Obviously, there is a lot of duplication here. It can be daunting and time consuming when dealing with multiple tasks of a similar nature. This is where loops come in handy.

Loops provide a simplified way of executing repetitive tasks with fewer lines of code. They iterate through a list of values specified using the loop or with_* directives.

The loop directive lists the values which are referenced past a variable chosen particular enclosed in double curly braces. During runtime, the playbook iterates through the list of users divers by the loop directive. Each of the users is and so passed to the item variable and all the users are created in a simple, still efficient manner. Information technology'southward apparent that the playbook looks neater with fewer lines of code achieving the same goal.

          --- - name: Create new users in remote machine   hosts: 173.82.120.115   tasks:   	- name: Create new user Alice       user:       	name: '{{ item }}'         country: present       loop:       	- alice         - patric         - tom                  

Here is the output of the Playbook execution to confirm the creation of the users:

Run Ansible playbook

Conclusion

In this guide, you have learned how to create and run Ansible playbooks. You take delved into diverse Playbook elements such every bit modules, variables, conditional statements, and loops.

Still, nosotros have barely scratched the surface and there'due south a lot you can achieve with Playbooks. For more data near Ansible Playbooks, check out the official Ansible Documentation portal.

lusktheingly1992.blogspot.com

Source: https://blog.cherryservers.com/how-to-create-and-use-ansible-playbooks

0 Response to "How Use the Same Task Again in Playbook Ansible"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel