Skip to content

How to use ansible adhoc command

How to use different Ansible variables with examples

Reading Time: 9 minutes

If you have not installed Ansible, You can read more on How to install ansible . In this tutorial, you will learn How to use ansible adhoc command. Master Ansible ad-hoc commands effortlessly with this concise guide. Learn the syntax, key parameters, and practical examples for quick and efficient tasks, from connectivity checks to system information retrieval.

  • Execute Ansible ad-hoc commands for rapid automation tasks.
  • Understand the essential parameters like inventory, user, and modules.
  • Learn through examples, including ping checks, uptime retrieval, and hostname identification.
  • Securely connect using PEM files for enhanced authentication.

Discover the simplicity of running Ansible ad-hoc commands with this guide. Explore syntax details, including inventory management, module usage, and user authentication. Examples cover ping checks, uptime retrieval, and hostname identification, providing a comprehensive overview of quick automation tasks. Learn to enhance security with PEM files for secure connections. Elevate your Ansible proficiency for streamlined infrastructure management.

How to run Ansible ad-hoc commands

How to use ansible adhoc command

$ ansible -i myinventory Allhosts -m ping -u adminuser –ask-pass

Commands Explanation:

ansible =
This is the main command to invoke ansible commands

-i = This is Inventory file which we are using to connect hosts

Allhosts = This is group name of hosts & it is mentioned inside Inventory file “myinventory

-u = Mention username which you will see to connect to destination hosts

-m = This is used for module

ping = This is module which can be used to check ping connectivity

Example :

adminuser@testertechie:~$ ansible -i myinventory Allhosts -m ping -u adminuser –ask-pass

SSH password: | SUCCESS => {

"ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3" }, "changed": false, "ping": "pong"



How to get uptime using ansible ad-hoc command

  • $ ansible -i myinventory Allhosts -a uptime -u adminuser --ask-pass


  • ansible -i myinventory Allhosts -a uptime -u adminuser --ask-pass
    SSH password: | CHANGED | rc=0 >>
    09:52:00 up 17:51, 4 users, load average: 0.23, 0.07, 0.04

How to find a hostname using ansible

Using ansible adhoc command you can find the hostname and this is a good example of How to use ansible adhoc command

  • ansible -i myinventory Allhosts -a 'uname -a' -u adminuser --ask-pass
  • Output :
    • | CHANGED | rc=0 >>
      Linux testertechie 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
    • “testertechie” is hostname 

Use Pem file with ansible

MBP ~ % ansible -i myhost all --private-key .pemfile-path -u athakur --ask-pass -a 'uname -a'

SSH password: | CHANGED | rc=0 >>

Linux flask-vm-1 4.18.0-425.13.1.el8_7.x86_64 #1 SMP Thu Feb 2 13:01:45 EST 2023 x86_64 x86_64 x86_64 GNU/Linux

What role does Ansible Vault play in securing sensitive data in playbooks?

Ansible Vault is a feature in Ansible that plays a crucial role in securing sensitive data within playbooks and other Ansible files. It provides a mechanism for encrypting and decrypting sensitive information, such as passwords, API keys, and other confidential data, ensuring that this information is not exposed in plaintext in version-controlled files. Here are the key roles and features of Ansible Vault:

1. Encryption of Sensitive Data:

  • Ansible Vault allows users to encrypt sensitive information within Ansible files, such as playbooks, variable files, or any YAML files used in the automation workflow.

2. Command-Line Interface (CLI) for Encryption:

  • Ansible Vault provides a command-line interface to encrypt files. Users can use the ansible-vault encrypt command to encrypt a file or a specific variable within a file.

bashCopy code

ansible-vault encrypt mysecrets.yml

3. Vault-Encrypted Files:

  • When a file is encrypted using Ansible Vault, it is saved in a format that includes a header indicating that it is a vault-encrypted file. Only individuals with the correct vault password can decrypt and access the contents.

4. Decryption during Playbook Execution:

  • Ansible Vault seamlessly integrates with Ansible playbooks. When a playbook is executed, Ansible automatically prompts for the vault password to decrypt the vault-encrypted files during runtime.

5. Vault Password Files:

  • Users can store the vault password in a file rather than entering it interactively each time. This password file can be specified during playbook execution using the --vault-password-file option.

6. Variable Encryption:

  • Ansible Vault allows users to encrypt specific variables within files. This selective encryption ensures that only the necessary sensitive information is protected, rather than encrypting the entire file.

bashCopy code

ansible-vault encrypt_string --name 'mysecret' 'secretpassword'

7. Integration with Playbook and Role Variables:

  • Vault-encrypted variables can be seamlessly integrated into playbooks and roles. Ansible automatically handles the decryption process, making it transparent during playbook execution.

8. Editing Encrypted Files:

  • Ansible Vault provides commands for editing vault-encrypted files. Users can use ansible-vault edit to open and edit encrypted files in a specified editor.

bashCopy code

ansible-vault edit mysecrets.yml

9. Multiple Vault Passwords:

  • Ansible supports using multiple vault passwords, allowing for flexibility in managing different levels of sensitive information. Users can specify different passwords for different vault-encrypted files.

10. Roles and Ansible Galaxy Integration:

  • Ansible roles created with sensitive data can be encrypted using Ansible Vault. This ensures that roles containing sensitive information can be securely shared via Ansible Galaxy or other distribution channels.

11. Encryption of Entire Playbooks:

  • Ansible Vault can encrypt entire playbooks, providing a comprehensive solution for protecting sensitive data within the entire automation workflow.

bashCopy code

ansible-vault encrypt myplaybook.yml

12. Ansible Tower and AWX Integration:

  • Ansible Tower and AWX, the web-based automation platform, seamlessly integrate with Ansible Vault. Users can manage and use vault-encrypted files directly within Tower and AWX workflows.

By using Ansible Vault, users can adhere to security best practices by safeguarding sensitive information, preventing inadvertent exposure of credentials, and ensuring that confidential data is kept secure throughout the automation workflow. It enhances the overall security posture of Ansible automation environments.

How does Ansible compare to other automation tools in terms of performance and scalability?

Comparing automation tools in terms of performance and scalability can be subjective and highly dependent on specific use cases, environments, and requirements. Ansible is a popular automation tool known for its simplicity, agentless architecture, and flexibility. Here’s a brief comparison with other automation tools, keeping in mind that the landscape may evolve, and newer versions of tools might introduce performance improvements.


  • Architecture: Ansible follows an agentless architecture, relying on SSH for communication with remote hosts. This eliminates the need for installing agents on managed nodes, simplifying deployment and reducing potential security vulnerabilities.
  • Ease of Use: Ansible’s declarative syntax (YAML) is human-readable, making it accessible to both system administrators and developers. Its simplicity accelerates adoption and reduces the learning curve.
  • Performance: While Ansible is performant for many use cases, it may have higher latency compared to agent-based solutions due to its over-the-network execution model. Parallel execution and optimizations introduced in newer versions contribute to improved performance.
  • Scalability: Ansible’s scalability is generally good, and it supports orchestration across large numbers of hosts. Users can scale horizontally by distributing workloads across multiple Ansible control nodes.


  • Architecture: Chef follows a client-server architecture, where Chef clients run on managed nodes, communicating with a central Chef server. This approach may require deploying and maintaining agents on managed nodes.
  • Ease of Use: Chef uses a domain-specific language (DSL) for defining configurations, which might have a steeper learning curve for those unfamiliar with Ruby-based DSLs.
  • Performance: Chef’s performance is influenced by the need to maintain a persistent connection between clients and the Chef server. It may introduce higher latency compared to Ansible’s agentless model.
  • Scalability: Chef’s scalability is generally good, with the ability to scale vertically by adding resources to the Chef server. For very large environments, considerations for server performance and architecture are crucial.


  • Architecture: Puppet follows a client-server architecture, similar to Chef, where Puppet agents run on managed nodes and communicate with a central Puppet master.
  • Ease of Use: Puppet uses a declarative language for defining configurations, which may be more accessible to users with a background in system administration. However, it might have a steeper learning curve for those unfamiliar with the Puppet DSL.
  • Performance: Puppet’s performance is influenced by the need for a persistent connection between agents and the Puppet master. It may have higher latency compared to Ansible’s agentless approach.
  • Scalability: Puppet scales well and supports vertical scalability by enhancing the performance of the Puppet master. Horizontal scalability can be achieved by distributing workloads across multiple Puppet masters.


  • Architecture: SaltStack follows a master-minion architecture, where Salt minions run on managed nodes and communicate with a central Salt master. It utilizes ZeroMQ for communication.
  • Ease of Use: SaltStack uses a YAML-based syntax for configurations, similar to Ansible, making it relatively accessible. Its remote execution and orchestration capabilities add to its flexibility.
  • Performance: SaltStack is known for its speed and low latency due to the use of ZeroMQ. Parallel and asynchronous execution contributes to its overall performance.
  • Scalability: SaltStack scales well and supports both vertical and horizontal scalability. Its architecture and communication model contribute to efficient scalability.

In summary, the choice between Ansible and other automation tools depends on factors such as the specific use case, team skillset, existing infrastructure, and preferences. Each tool has its strengths, and the best choice often depends on the unique requirements of the organization or project.

What troubleshooting techniques and best practices does Ansible offer?

Troubleshooting in Ansible involves identifying and resolving issues that may arise during playbook execution, task execution, or other automation processes. Here are some troubleshooting techniques and best practices in Ansible:

1. Enable Verbose Output:

  • Use the -v, -vv, or -vvv options with the ansible-playbook command to increase verbosity. This provides more detailed information about playbook execution, making it easier to identify the point of failure.

bashCopy code

ansible-playbook -vv playbook.yml

2. Check Syntax:

  • Use the ansible-playbook command with the --syntax-check option to check the syntax of your playbook without executing it. This helps catch syntax errors before running the playbook.

bashCopy code

ansible-playbook --syntax-check playbook.yml

3. Debugging Tasks:

  • Include debug statements within your tasks to print variable values or other information during playbook execution. Use the debug module to display information at specific points in your playbook.

yamlCopy code

- name: Debug Task debug: var: my_variable

4. Dry Run:

  • Use the --check option with ansible-playbook to perform a dry run. This simulates playbook execution without making changes to the target systems, allowing you to preview the changes that would be applied.

bashCopy code

ansible-playbook --check playbook.yml

5. Ansible Facts:

  • Leverage Ansible facts to gather information about target systems during playbook execution. Facts can provide insights into system details that may be relevant to troubleshooting.

yamlCopy code

- name: Display Facts debug: var: ansible_facts

6. Retry Failed Tasks:

  • Use the until loop or the retries and delay parameters in tasks to automatically retry failed tasks. This can be useful for transient issues.

yamlCopy code

- name: Retry Task command: /path/to/command retries: 3 delay: 5

7. Logging:

  • Enable logging to capture detailed information about playbook execution. You can configure logging in the ansible.cfg file or use the -e ANSIBLE_LOG_PATH option to specify a log file.

8. Check System Requirements:

  • Ensure that Ansible control node and managed nodes meet the system requirements. Check the version compatibility between Ansible versions, Python versions, and system libraries.

9. Validate Connections:

  • Confirm that Ansible can establish connections to managed nodes. Use the ping module or the ansible -m ping command to verify connectivity.

bashCopy code

ansible -m ping all

10. Check Inventory and Variables:

  • Review your inventory file to ensure that hosts are defined correctly. Check variable values in playbooks and roles to ensure they are set as expected.

11. Use Debugging Tools:

  • Utilize external tools like pdb (Python Debugger) for debugging. Insert breakpoints within your Python code to pause execution and inspect variables.

12. Community Support:

  • Leverage the Ansible community for assistance. Forums, mailing lists, and online communities are valuable resources for troubleshooting and getting help from experienced Ansible users.

13. Review Ansible Documentation:

  • Consult the official Ansible documentation for troubleshooting tips and solutions. The documentation covers common issues and provides insights into best practices.

14. Keep Ansible and Modules Updated:

  • Ensure that you are using the latest version of Ansible and modules. Updates may include bug fixes, performance improvements, and new features.

15. Understand Idempotency:

  • Familiarize yourself with idempotency concepts in Ansible. Tasks and playbooks should be designed to be idempotent, allowing them to be run multiple times without changing the result.

These troubleshooting techniques and best practices can help you effectively identify and resolve issues in your Ansible automation workflows. It’s essential to approach troubleshooting systematically, starting with basic checks and progressively diving deeper into specific areas as needed.

How to use ansible adhoc command

We hope you know How to use the ansible adhoc command however let us know if any queries.

Ansible ad-hoc official website

You can find all Ansible tutorials on this page.

You can find Jenkins Tutorials on this page

You can also find all Video Tutorial on Youtube


Follow us on Facebook Twitter X Reddit Quora Linkedin Tubmblr Youtube


Leave a Reply

Your email address will not be published. Required fields are marked *