Ansible tasks are defined as fundamental units of work that define what the automation tool does. Tasks are defined as discrete actions that execute on a defined host. Ansible tasks are usually defined as a YAML file inside a playbook, and have a list of tasks. In this Answer, we’ll explore a sample Ansible task.
The table below contains a few of the key features of Ansible tasks:
Features | Description |
Name | The title of the task |
Handlers | Tasks that run only when another task triggers them |
Hosts | The target hosts on which the tasks should be executed. Could be web servers or localhost |
Description | A string that usually displays the intention of each task and what it does for the user |
Now, let’s take a look at an example Ansible task.
In this example, we’ll use an Ansible task to create a file in the same directory as our main.yml
file. The code for this task is given below:
--- - name: Ansible task example hosts: localhost gather_facts: false connection: local tasks: - name: The file 'HelloWorld.txt' is created. copy: content: hello world dest: HelloWorld.txt
This code can be explained as follows:
Line 2: This is the name of the playbook, which provides a description of the task.
Line 3: We specify that the host runs on the local machine.
Line 4: We enable Ansible to not gather system facts and information from the host.
Line 5: We Specify a local connection as it is running on the local machine.
Line 6: This is the section where the task is defined.
Line 7: We specify the name of the task; in this case, its The file 'HelloWorld.txt' is created.
.
Line 9: We ensure that the content of the file contains hello world
.
Line 10: We specify the directory of the task. In this case, it’ll be in the same directory as the main.yml
file.
After running the widget above, type the following command to see that the HelloWorld.txt
file is created:
ls
Now, type this command to see the contents of this file:
cat HelloWorld.txt
Free Resources