Core Idea
Ad-hoc commands are one-off
ansibleruns 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
-boption (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