Storing Command Output as Variables in Ansible and Using Them in Templates

Nov 21, 2025 · Programming · 15 views · 7.8

Keywords: Ansible | Variable Storage | set_fact Module | Command Output | Template Usage

Abstract: This article details methods for storing the standard output of external commands as variables in Ansible playbooks. By utilizing the set_fact module, the content of command_output.stdout can be assigned to new variables, enabling reuse across multiple templates and enhancing code readability and maintainability. The article also discusses differences between registered variables and set_fact, with practical examples demonstrating variable application in system service configuration templates.

Introduction

In Ansible automation configuration management, it is often necessary to execute external commands and use their output in subsequent tasks. For instance, when deploying applications, one might need to retrieve status information of a service or generate random keys, and inject these into configuration files. Ansible provides robust variable management capabilities to handle and pass such data efficiently.

Capturing Command Output with Register

In Ansible, when using the shell or command modules, the register keyword can save command output to a variable. This variable is a dictionary containing detailed execution information, such as standard output (stdout), standard error (stderr), return code (rc), etc. For example:

- name: Execute command and register output
  command: echo Hello
  register: command_output

- name: Debug output
  debug:
    msg: "{{ command_output.stdout }}"

In this example, command_output.stdout contains the standard output of the command, i.e., the string "Hello". However, directly using command_output.stdout in templates can lead to verbose and hard-to-maintain code, especially when reused across multiple templates.

Creating New Variables with Set_Fact

To improve code readability, the set_fact module can assign the value of command_output.stdout to a new variable. This allows direct use of the new variable in subsequent tasks and templates without repeatedly referencing the .stdout attribute. For example:

- name: Store command output as new variable
  set_fact:
    string_to_echo: "{{ command_output.stdout }}"

With this approach, the string_to_echo variable holds the command output and can be used directly in templates, as shown below:

[Service]
ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c "while true; do echo {{ string_to_echo }}; sleep 1; done"

This significantly simplifies template writing and enhances code readability.

Practical Application Example

Suppose we need to use the output of a command in multiple system service configuration templates, such as generating a random key. Here is a complete playbook example:

- name: Generate random key
  shell: openssl rand -base64 48
  register: psk
  delegate_to: 127.0.0.1
  run_once: true

- name: Store key as fact variable
  set_fact:
    psk: "{{ psk.stdout }}"

- name: Copy service configuration file
  template:
    src: templates/service.conf.j2
    dest: /etc/systemd/system/my_service.service

In the template file service.conf.j2, the {{ psk }} variable can be used directly without referencing .stdout. This method not only makes templates cleaner but also facilitates future maintenance and debugging.

Comparison with Other Methods

Besides the set_fact module, Ansible offers other ways to handle command output. For example, registered variable attributes can be used directly in conditional checks:

- name: Check file content
  shell: cat hello
  register: cat_contents

- name: Perform action based on content
  shell: echo "I cat hello"
  when: cat_contents.stdout == "hello"

However, this approach is limited to simple conditional checks and is not suitable for reusing command output across multiple templates. Thus, set_fact is the preferred choice for sharing data across tasks.

Important Considerations

When using the set_fact module, keep the following in mind:

Conclusion

By leveraging the set_fact module, Ansible command output can be effectively stored as variables and reused in multiple templates. This method enhances code readability and maintainability while simplifying the implementation of complex automation tasks. In practice, selecting appropriate variable management strategies based on specific requirements can significantly improve the efficiency and reliability of Ansible playbooks.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.