Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Adhoc

This is an example of a playbook used to issue ad hoc Linux commands to systems. The intent it to provide elevated access to set commands, without providing access to the systems, that can be run across multiple systems quickly.

Use this play with caution as running arbitrary commands can be detrimental to a system/environment. When using this play there should be guardrails that limit the options for the command variable (such as using a Survey in AWX).

ad_hoc_commands.yml

---

- name: Start ad hoc commands playbook
  hosts: "{{ manual_list | default(env, true) | lower }}"
  vars:
  gather_facts: False
  become: True
  become_flags: '-i'
  ignore_unreachable: True
  ignore_errors: True
  tasks:

    - name: Execute ad hoc commands.
      shell: "{{ command }}"
      register: output

    - name: Print output.
      debug:
        msg: "{{ command }}: {{ output.stdout }}"

...

Variables

It is designed to be used within AWX where the {{ command }} variable would be selected through a survey; however, here is an example on how to run it manually.

  • env - Specific groups from your inventory.
  • manual_list - Specific space delineated servers or groups from your inventory; meant for situations where you want to override env. For example, when you want to hard-code groups into an AWX Survey and then allow to override the group for an adhoc group of servers.
  • command - The desired shell command. Designed to be used within AWX as a drop down survey of options.

Commands

ansible-playbook ad_hoc_commands.yml -e "env='<server_list>' command='/full/path/command [arguments]' manual_list='<server1.example.com> <server2.example.com>'"