Skip to content

Instantly share code, notes, and snippets.

@thenets
Last active January 30, 2024 05:54
Show Gist options
  • Save thenets/aeda4fde1c7675829fdee62cf37ce039 to your computer and use it in GitHub Desktop.
Save thenets/aeda4fde1c7675829fdee62cf37ce039 to your computer and use it in GitHub Desktop.
Playbook example of how to run an arbitrary command and retrieve it's output

How to run an arbitrary command on Ansible

The following example describe how to use the ansible.builtin.shell with Ansible to retrieve a system information and then set it to a variable using ansible.builtin.set_fact.

Requirements

  • Ansible CLI

How to run

ansible-playbook ./play-run-cmd-example.yml

# You can also enable the verbose mode
ansible-playbook -vvv ./play-run-cmd-example.yml
---
- name: Playbook example of how to run an arbitrary command and retrieve it's output
hosts: localhost
# Disable the facts retrieval
# Learn more:
# https://www.redhat.com/sysadmin/playing-ansible-facts
# List of all variables to be populated when `gather_facts` is enabled:
# https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html
gather_facts: false
tasks:
- name: Run an arbitrary command, like 'uname --kernel-release'
# The `shell` module parameters:
# https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html#parameters
ansible.builtin.shell:
cmd: |
# You can run multiple shell commands here
uname --kernel-release | cut -d'-' -f 1
# If you are running a command that will not change the system state,
# like retrieving information, then you should set `changed_when: false`.
#
# This will allow some tests, for example, identify immutable playbooks.
changed_when: false
register: _cmd_kernel_version
- name: Debug _cmd_kernel_version
ansible.builtin.debug:
var: _cmd_kernel_version
- name: Set "kernel_version" variable
ansible.builtin.set_fact:
# The command above will return a dictionary with multiple values,
# you can check them here:
# https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html#return-values
#
# In this case, we want the `<registered_output>.stdout`:
kernel_version: "{{ _cmd_kernel_version.stdout }}"
- name: Debug kernel_version
ansible.builtin.debug:
var: kernel_version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment