To capture command output in Ansible, you can use the command or shell module along with the register keyword. This allows you to store the output of a command in a variable for further processing. Here’s a step-by-step guide:
Step-by-Step Example
Create a Playbook: Start by creating a new YAML file for your playbook. For example,
capture_output.yml.nano capture_output.ymlDefine the Playbook Structure: Add the following content to your playbook:
--- - name: Capture command output example hosts: localhost tasks: - name: Get disk usage information command: df -h register: df_output - name: Display captured output debug: msg: "{{ df_output.stdout }}"
Explanation of the Playbook
command: df -h: This line runs thedf -hcommand, which displays disk usage in a human-readable format.register: df_output: This captures the output of the command and stores it in the variabledf_output.debugmodule: This is used to print the captured output.{{ df_output.stdout }}accesses the standard output of the command.
Running the Playbook
To execute the playbook, run the following command in your terminal:
ansible-playbook capture_output.yml
Output
You should see output similar to this:
TASK [Display captured output] ****************************************************
ok: [localhost] => {
"msg": "Filesystem Size Used Avail Use% Mounted on\n/dev/sda1 50G 20G 28G 42% /\n..."
}
Additional Notes
Using
shellModule: If you need to run a command that requires shell features (like pipes or redirection), use theshellmodule instead ofcommand.Accessing Different Output Parts: You can access different parts of the captured output:
df_output.stdout: Standard output.df_output.stderr: Standard error (if any).df_output.rc: Return code of the command.
This method allows you to effectively capture and utilize command output in your Ansible playbooks. If you have any further questions or need more examples, feel free to ask!
