Executing a Simple Command Locally
In this step, you will learn how to use the Ansible Local Action module to execute a simple command on the control machine. This will help you understand the basic usage and syntax of the module.
First, complete /home/labex/project/execute_local_command.yml
file.
Add the following content to the playbook file:
- name: Executing a Simple Command Locally
gather_facts: false
hosts: localhost
tasks:
- name: Print a message locally
local_action:
module: command
cmd: echo "Hello, World!"
register: result
- name: Debug the output
debug:
var: result.stdout
gather_facts
: This specifies whether Ansible should gather facts about the target hosts. In this case, it's set to false
, meaning facts won't be gathered.
hosts
: This specifies the target host on which to run the playbook. In this case, the playbook will run on the local host because the target host is localhost
.
tasks
: This is a list of tasks to be executed.
local_action
: This indicates that the action should be performed locally on the control machine where Ansible is being run.
module
: This specifies the Ansible module to use for the action. In this case, it's the command
module.
cmd
: This is the actual command to be executed. In this case, it's the shell command echo "Hello, World!"
, which will print the message "Hello, World!" to the console.
register
: This registers the output of the command in the result
variable for later use in the playbook.
debug
: This is the Ansible module used to print debugging information.
var
: This is a parameter for the debug
module that specifies the variable to be debugged. In this case, it's result.stdout
, which contains the standard output of the command executed in the previous task.
In summary, this playbook executes a simple command echo "Hello, World!"
locally on the control machine, registers the output, and then prints the output using the debug
module.
Then, display the output of the command in the Ansible playbook.
ansible-playbook /home/labex/project/execute_local_command.yml
Example output:
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'
PLAY [Local Action Module Challenge] *******************************************
TASK [Print a message locally] *************************************************
changed: [localhost]
TASK [Debug the output] ********************************************************
ok: [localhost] => {
"result.stdout": "Hello, World!"
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Here "result.stdout": "Hello, World!"
is the output of echo "Hello, World!"
command.