How to capture command output?

QuestionsQuestions4 SkillsProAnsible Command ModuleNov, 14 2025
0103

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

  1. Create a Playbook: Start by creating a new YAML file for your playbook. For example, capture_output.yml.

    nano capture_output.yml
    
  2. Define 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 the df -h command, which displays disk usage in a human-readable format.
  • register: df_output: This captures the output of the command and stores it in the variable df_output.
  • debug module: 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 shell Module: If you need to run a command that requires shell features (like pipes or redirection), use the shell module instead of command.

  • 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!

0 Comments

no data
Be the first to share your comment!