ansible cli

Core Idea

Ad-hoc commands are one-off ansible runs straight from the command line: target, module, args, done, with no playbook file needed.

  • The general syntax: ansible <target> -m <module> -a "<module_args>".
  • Worked examples: manage users, manage packages.
  • Running operations in the background and Ansible’s parallelism.

ad-hoc commands are one-off commands that you run directly from the command line without needing to create a playbook.

ansible <target> -m <module> -a "<module_args>" [options]
  • <target>: Specifies the hosts or groups from the inventory.
  • -m <module>: Specifies the Ansible module to use (e.g.,Ā ping,Ā copy,Ā shell).
  • -a "<module_args>": Passes arguments to the module.

All modules — Ansible Documentation

Tip

The -b option (alias for --become) tells Ansible to run the command with become (basically, run commands with ā€˜sudo’).
This will work fine with our Vagrant VMs, but if you’re running commands against a server where your user account requires a password for privilege escalation, you should also pass in -K (alias for --ask-become-pass), so you can enter your password when Ansible needs it.

Manage Users using ansible

CH-3 ā€˜Manage users and groups’
—Jeff Geerling, ā€œAnsible for DevOpsā€

šŸ‘‰ ansible.builtin.user module – Manage user accounts
šŸ‘‰ User Management

Manage Packages

Ansible has a variety of package management modules for any flavor of Linux, but there’s also a generic package module that can be used for easier cross-platform Ansible usage.

ansible app -b -m package -a "name=git state=present"

Run Operations in the Background

You can tell Ansible to run the commands asynchronously, and poll the servers to see when the commands finish.

  • -B <seconds>: the maximum amount of time (in seconds) to let the job run.
  • -P <seconds>: the amount of time (in seconds) to wait between polling the servers for an updated job status.
$ ansible multi -b -B 3600 -P 0 -a "dnf -y update"

While the background task is running, you can check on the status elsewhere using Ansible’s async_status module, as long as you have the ansible_job_id value to pass in as jid:

$ ansible multi -b -m async_status -a "jid=169825235950.3572"

Ansible Parallelism

$ ansible multi -a "hostname"

Ansible will run this command against all three of the servers, and return the results (if Ansible can’t reach one server, it will show an error for that server, but continue running the command on the others)

Ansible will run commands in parallel, using multiple process forks.

$ ansible multi -a "hostname" -f 1 —> Run only 1 fork


Chrony