Ad hoc commands 22
Command What it does
ansible [pattern] -m [module] -a "[module options]"Ad hoc command form The host pattern comes first, then the module name and its arguments as one quoted string.
ansible atlanta -a "/sbin/reboot"Run a command on a group With no -m given, the command module runs the quoted line on every host in the atlanta group.
ansible atlanta -a "/sbin/reboot" -f 10Run with ten parallel forks Raises the number of simultaneous processes above the default of five for this one run.
ansible raleigh -m ansible.builtin.shell -a 'echo $TERM'Run a shell command Single quotes keep the local shell from expanding the variable, so it is evaluated on the remote hosts.
ansible atlanta -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"Copy a file to hosts Sends the local file to every server in the group in parallel.
ansible webservers -m ansible.builtin.file -a "dest=/srv/foo/a.txt mode=600"Set file permissions The file module changes the mode of an existing path; owner= and group= change its ownership.
ansible webservers -m ansible.builtin.file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"Create a directory Works like mkdir -p on each host, with the mode and owner given.
ansible webservers -m ansible.builtin.file -a "dest=/path/to/c state=absent"Delete a file or directory A directory given as dest is removed together with everything inside it.
ansible webservers -m ansible.builtin.yum -a "name=acme state=present"Install a package Leaves the package alone when it is already there; no update is done.
ansible webservers -m ansible.builtin.yum -a "name=acme-1.5 state=present"Install a specific package version The wanted version is written as part of the package name.
ansible webservers -m ansible.builtin.yum -a "name=acme state=latest"Update a package Brings the package up to the newest available version on every web server.
ansible webservers -m ansible.builtin.yum -a "name=acme state=absent"Remove a package After the run the package is absent from all hosts in the group.
ansible all -m ansible.builtin.user -a "name=foo state=absent"Remove a user account Deletes the account named foo from every host in the inventory.
ansible webservers -m ansible.builtin.service -a "name=httpd state=started"Start a service Like other modules it acts only where the current state differs, so running hosts are left alone.
ansible webservers -m ansible.builtin.service -a "name=httpd state=restarted"Restart a service Restarts httpd on each host in the webservers group.
ansible webservers -m ansible.builtin.service -a "name=httpd state=stopped"Stop a service
ansible all -m ansible.builtin.setupShow all facts Prints the variables Ansible discovers about each system; the setup module can also filter them.
ansible all -m copy -a "content=foo dest=/root/bar.txt" -CDry-run an ad hoc task In check mode the file is neither created nor updated on any remote system.
ansible myhosts -m ping -i inventory.iniPing an inventory group Runs the ping module against the hosts listed under myhosts in inventory.ini.
ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"Run a job in the background Starts the command with a 3600-second limit and returns without polling; a job ID is returned.
ansible web1.example.com -m async_status -a "jid=488359678239.2844"Check a background job Give it the job ID that the earlier background run returned.
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"Run async with polling Lets the job run for up to 30 minutes and looks at its status every 60 seconds.
Ad hoc command options 16
Command What it does
ansible -m MODULE_NAMEChoose the module Names the action to run; without it the command module is used.
ansible -a MODULE_ARGSPass module arguments Takes key=value pairs separated by spaces, or a JSON string for more complex structures.
ansible -f FORKSSet parallel forks Sets how many hosts are worked on at once; five when the option is absent.
ansible -B SECONDSRun asynchronously The task goes to the background and is failed if it has not finished after this many seconds.
ansible -P POLL_INTERVALSet the async poll interval Only matters together with -B; 15 is used when it is left out.
ansible -oCondense output Long form --one-line; each result is printed in a compact form.
ansible -t TREELog output to a directory Long form --tree; results are written under the directory you name.
ansible -e EXTRA_VARSSet extra variables Accepts key=value pairs, YAML or JSON, or a file name with @ in front; repeatable.
ansible -CRun in check mode Nothing is changed on the hosts; Ansible tries to predict what would change.
ansible -DShow file differences Prints what changed in small files and templates; pairs well with -C.
ansible --task-timeout TASK_TIMEOUTSet a task time limit The limit is given in seconds and has to be a positive integer.
ansible --playbook-dir BASEDIRSet a substitute playbook directory Gives relative lookups such as roles/ and group_vars/ a base path, since ad hoc runs have no playbook.
ansible -M MODULE_PATHAdd module search paths Paths are separated by colons and placed in front of the default module library; repeatable.
ansible -vIncrease verbosity Repeat the letter for more detail: -vvv is a sensible start and -vvvv helps with connection problems.
ansible --flush-cacheClear the fact cache Cached facts are discarded for all inventory hosts.
ansible -hShow help Lists every option of the ansible command and exits.
Running playbooks 24
Handlers can also be forced without the flag: force_handlers: True in a play, or force_handlers = True in ansible.cfg.
Command What it does
ansible-playbook -i inventory.ini playbook.yamlRun a playbook with an inventory The -i option names the inventory file the plays draw their hosts from.
ansible-playbook playbook.yml -f 10Run a playbook with ten forks Works on up to ten hosts in parallel where the default would be five.
ansible-playbook --check playbook.yamlDry-run a playbook Produces a report of would-be changes and leaves the systems untouched.
ansible-playbook foo.yml --check --diff --limit foo.example.comPreview diffs on one host Diff mode prints a lot, so the guide pairs it with a limit to a single host.
ansible-playbook -CRun in check mode Short for --check; modules that support it report what they would change.
ansible-playbook -DShow file differences Short for --diff; usable alone or with -C, mostly with modules that manage files.
ansible-playbook --syntax-checkCheck playbook syntax Parses the playbook and stops; no task is executed.
ansible-playbook --list-tasksList tasks without running Shows the tasks a run would execute; add --tags or --skip-tags to preview a selection.
ansible-playbook --stepConfirm each task Stops before every task and asks whether to run it.
ansible-playbook playbook.yml --stepRun in step mode Answer y to run the task, n to skip it, or c to carry on without further questions.
ansible-playbook --start-at-task START_AT_TASKStart at a named task Execution begins at the task whose name matches; play-level fact gathering still runs first.
ansible-playbook playbook.yml --start-at-task="install packages"Resume from a failed task Handy after a failure; it does not find tasks inside dynamically included roles or task files.
ansible-playbook --force-handlersRun handlers after failures Notified handlers then run on all hosts, including those with failed tasks.
ansible-playbook --flush-cacheClear the fact cache
ansible-playbook -e EXTRA_VARSSet extra variables Variables passed this way take precedence over those from every other source.
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"Pass variables as key=value Values given in this form are always read as strings.
ansible-playbook release.yml --extra-vars '{"version":"1.23.45","other_variable":"foo"}'Pass variables as JSON JSON keeps Booleans, integers, floats and lists as their real types.
ansible-playbook release.yml --extra-vars "@some_file.json"Load variables from a file The @ prefix marks a JSON or YAML file of variable definitions.
ansible-playbook -f FORKSSet parallel forks Without it Ansible uses five parallel processes.
ansible-playbook -vIncrease verbosity The built-in plugins react to as many as six v letters; --verbose is the long form.
ansible-playbook -M MODULE_PATHAdd module search paths Loads local modules from the directories given, separated by colons.
ansible-playbook -i /path/to/my_inventory_file -u my_connection_user -k -f 3 -T 30 -t my_tag -M /path/to/my_modules -b -K my_playbook.ymlCombine common playbook flags The cheat sheet example: inventory, SSH user and password prompt, forks, timeout, tag, module path and become.
ansible-playbook -hShow help Prints all ansible-playbook options and exits.
ansible-playbook --versionShow version and paths Prints the same version, config file and path details as ansible --version.
Privilege escalation 12
-K only asks for a password and --become-user only names the account; become itself is switched on with -b.
Command What it does
ansible -bRun with become Escalates privileges on the target, with sudo unless another method is set; it does not prompt for a password.
ansible -KAsk for the become password The password you enter is used for all hosts.
ansible --become-user BECOME_USERChoose the become user Root is the default; on its own this option does not switch become on.
ansible --become-method BECOME_METHODChoose the become method Sudo is the default; ansible-doc -t become -l lists the alternatives.
ansible --become-password-file BECOME_PASSWORD_FILERead become password from file --become-pass-file is an alias of this option.
ansible atlanta -a "/sbin/reboot" -f 10 -u username --become [--ask-become-pass]Connect as user, run as root Logs in as username and runs the command as root; the bracketed flag adds a password prompt.
ansible localhost -m ansible.builtin.apt -a "name=apache2 state=present" -b -KInstall a package with become Runs on the local system and prompts for the privilege escalation password.
ansible-playbook -bRun with become Like every command-line option it yields to a become keyword set in the playbook.
ansible-playbook -KAsk for the become password Long form --ask-become-pass; asking for the password does not by itself enable become.
ansible-playbook --become-user BECOME_USERChoose the become user Sets which account tasks run as after escalation; root when omitted.
ansible-playbook --become-method BECOME_METHODChoose the become method The guide lists sudo, su, pbrun, pfexec, doas, dzdo, ksu, runas and machinectl.
ansible-playbook --become-password-file BECOME_PASSWORD_FILERead become password from file Takes the place of the -K prompt; the usage line shows the two as alternatives.
Connection options 23
Command-line options override configuration only. Playbook keywords and variables from inventory or playbooks take precedence over them, while -e extra vars outrank every other variable source.
Command What it does
ansible -u REMOTE_USERSet the remote user Without it the ansible command connects as your own user account.
ansible atlanta -a "/sbin/reboot" -f 10 -u usernameConnect as another user Logs in to each host as username, not as the account you are working in.
ansible -u mike -m ping myhost -u carolRepeat a single-value option When such an option is given twice the last value wins, so this connects as carol.
ansible -u carol -e 'ansible_user=brian' -a whoami allOverride the user with extra vars The -e variable outranks -u, so the connection is made as brian.
ansible -kAsk for connection password Prompts for the password used for SSH authentication; lowercase, unlike -K for become.
ansible --connection-password-file CONNECTION_PASSWORD_FILERead connection password from file An alternative to the -k prompt; --conn-pass-file is an alias.
ansible -c CONNECTIONChoose the connection type Ssh is the default; ansible-doc -t connection -l lists the plugins that can be named here.
ansible -T TIMEOUTSet the connection timeout Given in seconds; what applies otherwise depends on the connection plugin.
ansible --private-key PRIVATE_KEY_FILEUse a private key file Authenticates the connection with this key; --key-file is the same option.
ansible --ssh-common-args SSH_COMMON_ARGSAdd shared SSH arguments Handed to ssh, scp and sftp alike; ProxyCommand is the example the help gives.
ansible --ssh-extra-args SSH_EXTRA_ARGSAdd ssh-only arguments Reaches ssh but not scp or sftp; the help gives -R as an example.
ansible --scp-extra-args SCP_EXTRA_ARGSAdd scp-only arguments Handed to scp alone; the help gives -l as an example.
ansible --sftp-extra-args SFTP_EXTRA_ARGSAdd sftp-only arguments Handed to sftp alone, for instance -f or -l.
ansible-playbook -u REMOTE_USERSet the remote user Overrides configuration only; a user set by a playbook keyword or an inventory variable still wins.
ansible-playbook -kAsk for connection password Long form --ask-pass; the usage line shows it as an alternative to --connection-password-file.
ansible-playbook --connection-password-file CONNECTION_PASSWORD_FILERead connection password from file
ansible-playbook -c CONNECTIONChoose the connection type When the option is absent the ssh connection plugin is used.
ansible-playbook -T TIMEOUTSet the connection timeout The cheat sheet uses -T 30 for a thirty-second timeout.
ansible-playbook --private-key PRIVATE_KEY_FILEUse a private key file
ansible-playbook --ssh-common-args SSH_COMMON_ARGSAdd shared SSH arguments
ansible-playbook --ssh-extra-args SSH_EXTRA_ARGSAdd ssh-only arguments
ansible-playbook --scp-extra-args SCP_EXTRA_ARGSAdd scp-only arguments
ansible-playbook --sftp-extra-args SFTP_EXTRA_ARGSAdd sftp-only arguments
Inventory 18
Command What it does
ansible -i INVENTORYChoose the inventory Takes a path or a comma-separated host list and may be repeated.
ansible -i /path/inventory1 -i /path/inventory2 -m ping allUse several inventories ad hoc Repeated -i values are appended, so hosts from both files are in scope.
ansible-playbook -i INVENTORYChoose the inventory A value ending in a comma, such as 127.0.0.2, is read as a host list, not as a file.
ansible-playbook get_logs.yml -i staging -i productionTarget two inventories at once Useful for one action across normally separate environments such as staging and production.
ansible-playbook example.yml -i inventoryUse an inventory directory Every source inside the directory is merged into one inventory, read in alphabetical order.
ansible-inventory -i inventory.ini --listVerify an inventory file Dumps everything Ansible reads from the file, in JSON unless another format is asked for.
ansible-inventory --listDump the whole inventory One of three actions, exactly one of which has to be given; the others are --graph and --host.
ansible-inventory --graphShow the inventory as a graph A group name may follow to graph only that group; --limit is ignored.
ansible-inventory --host HOSTShow info for one host Prints the data for that host alone, as an inventory script would; --limit is ignored.
ansible-inventory --list --yamlList the inventory as YAML The FAQ gives this command for seeing the inventory variables defined for a host.
ansible-inventory -yUse YAML output Replaces the default JSON; it has no effect on --graph.
ansible-inventory --tomlUse TOML output Like -y, it is ignored when graphing.
ansible-inventory --varsAdd variables to the graph Only has an effect together with --graph.
ansible-inventory --exportExport-friendly listing With --list, arranges the output for export, which is not how Ansible itself processed the inventory.
ansible-inventory --output OUTPUT_FILEWrite the listing to a file Applies to --list; nothing is printed on screen.
ansible-inventory -i demo.aws_ec2.yml --graphGraph a plugin inventory Shows what an inventory plugin returns once the options in its config file are filled in.
ansible-inventory --playbook-dir BASEDIRSet a substitute playbook directory Needed to test an inventory plugin that lives in a collection next to a playbook.
ansible-inventory -l SUBSETLimit the hosts shown Filters the listing by a pattern; --graph and --host ignore it.
Vault files and strings 32
Command What it does
ansible-vault createCreate an encrypted file Opens your editor on a new file, which is stored encrypted once the editor is closed.
ansible-vault create --vault-id test@multi_password_file foo.ymlCreate with a labelled password Encrypts foo.yml under the label test, using the matching password in multi_password_file.
ansible-vault create --vault-id my_new_password@prompt foo.ymlCreate and prompt for a password The part before @ is the vault ID label; prompt makes the tool ask for the password.
ansible-vault create --skip-tty-checkSkip the TTY check Lets the editor open even though no terminal is attached.
ansible-vault encrypt foo.yml bar.yml baz.ymlEncrypt existing files Several files can be handled in one command.
ansible-vault encrypt --vault-id project@prompt foo.yml bar.yml baz.ymlEncrypt with a vault ID Labels the files project and asks which password to encrypt them with.
ansible-vault encrypt --vault-id VAULT_IDSGive a vault identity Every ansible-vault subcommand accepts it, and it can be repeated.
ansible-vault encrypt --vault-password-file VAULT_PASSWORD_FILESGive a vault password file --vault-pass-file is an alias; the usage line shows it as an alternative to -J.
ansible-vault encrypt -JAsk for the vault password The long spellings are --ask-vault-password and --ask-vault-pass.
ansible-vault encrypt --encrypt-vault-id ENCRYPT_VAULT_IDChoose the encrypting vault ID Needed once several --vault-id values are supplied; create, edit, rekey and encrypt_string take it too.
ansible-vault view foo.yml bar.yml baz.ymlView encrypted files Shows the contents of the files without editing them.
ansible-vault edit foo.ymlEdit an encrypted file Decrypts to a temporary file for editing, then re-encrypts it and deletes the temporary copy.
ansible-vault edit --vault-id pass2@vault2 foo.ymlEdit with a specific vault ID For a file whose password lives in vault2 and whose label is pass2.
ansible-vault rekey foo.yml bar.yml baz.ymlChange the vault password Asks for the original password and then for the new one.
ansible-vault rekey --vault-id preprod1@ppold --new-vault-id preprod2@prompt foo.yml bar.yml baz.ymlRekey to a new vault ID Moves the files from the preprod1 label to preprod2 and prompts for the new password.
ansible-vault rekey --new-vault-id NEW_VAULT_IDSet the new vault ID The identity the files carry after they are re-encrypted.
ansible-vault rekey --new-vault-password-file NEW_VAULT_PASSWORD_FILERead the new password from file Takes the replacement password from a file.
ansible-vault decrypt foo.yml bar.yml baz.ymlDecrypt files permanently Writes the files back to disk unencrypted; use edit when you only want to change something.
ansible-vault decryptDecrypt a pasted string With no file name it reads ciphertext from standard input; end the input with Ctrl+D twice.
ansible-vault decrypt --output OUTPUT_FILEWrite output to another file A dash sends the result to stdout; encrypt and encrypt_string accept the option as well.
ansible-vault encrypt_stringEncrypt a single string The result is formatted for pasting into a playbook, role or variables file.
ansible-vault encrypt_string --vault-password-file a_password_file 'foobar' --name 'the_secret'Encrypt a named variable Prints a the_secret: !vault block encrypted with the password kept in a_password_file.
ansible-vault encrypt_string --vault-id dev@a_password_file 'foooodev' --name 'the_dev_secret'Encrypt a string with vault ID Same as above, with the dev label recorded in the encrypted value.
echo -n 'letmein' | ansible-vault encrypt_string --vault-id dev@a_password_file --stdin-name 'db_password'Encrypt a string from a pipe A secret typed straight into a command stays in your shell history, so the guide limits this to testing.
ansible-vault encrypt_string --vault-id dev@a_password_file --stdin-name 'new_user_password'Encrypt a string you type in Without piped input the tool waits for you to enter the secret, keeping it out of the command line.
ansible-vault encrypt_string -pPrompt for the string Asks for the value interactively; typing is hidden unless --show-input is added.
ansible-vault encrypt_string --show-inputShow the string as typed Turns off the hidden typing used at the prompt.
ansible-vault encrypt_string -n ENCRYPT_STRING_NAMESName the variable Long form --name; it can be given more than once.
ansible-vault encrypt_string --stdin-name ENCRYPT_STRING_STDIN_NAMEName the stdin variable Sets what the variable is called when the value arrives on standard input.
ansible-vault -hShow help Lists the subcommands; put --help after a subcommand to see its own options.
ansible-vault --versionShow version and paths
ansible-vault -vIncrease verbosity
Vault passwords at run time 15
Command What it does
ansible-playbook --ask-vault-pass site.ymlPrompt for the vault password Enough when all encrypted content in the run shares a single password.
ansible-playbook -JAsk for vault password Short for --ask-vault-pass and --ask-vault-password.
ansible-playbook --vault-password-file /path/to/my/vault-password-file site.ymlUse a vault password file The file holds the password as one line of text.
ansible-playbook --vault-password-file VAULT_PASSWORD_FILESGive a vault password file May also point to a client script that supplies the password.
ansible-playbook --vault-id VAULT_IDSGive a vault identity Written as label@source, where the source is prompt, a file or a script; repeatable.
ansible-playbook --vault-id dev@prompt site.ymlPrompt for a labelled password Asks for the password that belongs to the dev vault ID.
ansible-playbook --vault-id dev@dev-password site.ymlRead a labelled password file Takes the dev password from the file named dev-password.
ansible-playbook --vault-id dev@dev-password --vault-id prod@prompt site.ymlSupply several vault passwords Labels are only hints by default: the matching password is tried first, then the rest in the order given.
ansible-playbook --vault-id @prompt site.ymlPrompt without a vault ID Behaves like --ask-vault-pass, so it is rarely needed.
ansible-playbook --extra-vars @secrets.enc --vault-password-file secrets.passLoad an encrypted vars file Loads secrets.enc as extra vars and reads the vault password from secrets.pass.
ansible-playbook --vault-id dev@path/to/vault-keyring-client.pyUse a password client script Ansible runs the script with a --vault-id option so it can return the right password.
ansible --vault-id VAULT_IDSGive a vault identity Ad hoc tasks that use encrypted variables or files need the password as well.
ansible --vault-password-file VAULT_PASSWORD_FILESGive a vault password file --vault-pass-file is an alias; the usage line pairs it with -J as alternatives.
ansible -JAsk for vault password Prompts for the vault password; the long forms are --ask-vault-pass and --ask-vault-password.
ansible localhost -m ansible.builtin.debug -a var="new_user_password" -e "@vars.yml" --vault-id dev@a_password_fileView an encrypted variable The debug module prints the original value of a variable stored encrypted in vars.yml.
Installing collections 24
Command What it does
ansible-galaxy collection install my_namespace.my_collectionInstall a collection Fetches it from the configured Galaxy server into ~/.ansible/collections unless told otherwise.
ansible-galaxy collection install my_namespace.my_collection --upgradeUpgrade a collection Moves an installed collection to the newest version the Galaxy server offers.
ansible-galaxy collection install -UUpgrade installed collections Short for --upgrade; dependencies are updated too unless --no-deps is added.
ansible-galaxy collection install -r requirements.ymlInstall from a requirements file Installs every collection named in requirements.yml.
ansible-galaxy install -r requirements.ymlInstall roles and collections together One command for both kinds; the collection and role forms of install -r handle only their own kind.
ansible-galaxy collection install my_namespace.my_collection:==1.0.0-beta.1Install an exact version Pre-releases are ignored unless requested explicitly with == like this.
ansible-galaxy collection install 'my_namespace.my_collection:>=1.0.0,<2.0.0'Install within a version range The newest version inside the range is chosen; the quotes protect the operators from the shell.
ansible-galaxy collection install my_namespace-my_collection-1.0.0.tar.gz -p ./collectionsInstall from a tarball ansible_collections is appended to the -p path unless the parent directory already has that name.
ansible-galaxy collection install /path/to/collection -p ./collectionsInstall from a source directory The collection is built from galaxy.yml or MANIFEST.json in that directory and then installed.
ansible-galaxy collection install git+https://github.com/organization/repo_name.git,develInstall from a Git repository The text after the comma picks a branch, commit or tag; the repository needs galaxy.yml or MANIFEST.json.
ansible-galaxy collection install -p COLLECTIONS_PATHChoose the install path Replaces the first COLLECTIONS_PATH entry from the configuration as the destination.
ansible-galaxy collection install -fReinstall over an existing copy Forces the collection to be overwritten when it is already installed.
ansible-galaxy collection install --force-with-depsForce reinstall with dependencies Overwrites the collection together with everything it depends on.
ansible-galaxy collection install -nSkip dependencies Long form --no-deps; the usage line shows it as an alternative to --force-with-deps.
ansible-galaxy collection install -iContinue after errors Moves on to the next collection when one fails; dependency conflicts still stop the run.
ansible-galaxy collection install --preAllow pre-release versions Semantic-versioning pre-releases are skipped unless this is set.
ansible-galaxy collection install --offlineInstall without contacting servers Works for local tarballs only, not for Git repositories or URLs of remote tarballs.
ansible-galaxy collection install my_namespace.my_collection --keyring ~/.ansible/pubring.kbxVerify signatures on install The option can be left out when a GnuPG keyring is already configured.
ansible-galaxy collection install --keyring KEYRINGSet the verification keyring Names the keyring that signatures are checked against.
ansible-galaxy collection install --signature SIGNATURESAdd a signature source Checks MANIFEST.json against an extra signature; only with a collection name, never with a requirements file.
ansible-galaxy collection install --required-valid-signature-count REQUIRED_VALID_SIGNATURE_COUNTRequire a number of signatures One good signature is enough unless this raises the bar; a leading + also fails when none is found.
ansible-galaxy collection install my_namespace.my_collection --ignore-signature-status-code NO_PUBKEYIgnore one GnuPG status code Signatures that fail only for a missing public key no longer block the install; repeatable.
ansible-galaxy collection install --ignore-signature-status-codesIgnore several status codes Takes a list separated by spaces, such as NO_PUBKEY FAILURE; place it after the collection names.
ansible-galaxy collection install --disable-gpg-verifyDisable GPG verification Skips signature checks for collections that come from a Galaxy server.
Listing, verifying and downloading collections 14
Command What it does
ansible-galaxy collection listList installed collections Covers every configured collections path, including collections under development that have a galaxy.yml.
ansible-galaxy collection list fortinet.fortiosList one collection Give a fully qualified collection name; every installed copy of it is shown.
ansible-galaxy collection list -p '/opt/ansible/collections:/etc/ansible/collections'Search extra collection paths Paths separated by colons are searched ahead of the configured ones.
ansible-galaxy collection list --format jsonChoose the list format The accepted values are human, yaml and json.
ansible-galaxy collection verify my_namespace.my_collectionVerify an installed collection Compares the installed files with the server copy; silent on success, otherwise the altered files are named.
ansible-galaxy collection verify my_namespace.my_collection -vvvVerify with details Adds the installed path, the remote URL and a success message to the output.
ansible-galaxy collection verify my_namespace.my_collection:1.0.0Verify a specific version With no version the comparison is made against the latest release on the server.
ansible-galaxy collection verify -r requirements.ymlVerify from a requirements file Dependencies named in the file are not covered and need their own verify run.
ansible-galaxy collection verify my_namespace.my_collection --offline --keyring ~/.ansible/pubring.kbxVerify without the server Uses the signature data saved at install time to check the collection locally.
ansible-galaxy collection download my_namespace.my_collectionDownload a collection Fetches the collection and its dependencies as tarballs, by default into ./collections, for an offline install.
ansible-galaxy collection download my_namespace.my_collection:1.0.0Download a specific version
ansible-galaxy collection download -r requirements.ymlDownload from a requirements file The download folder also receives a requirements.yml that install -r can use offline.
ansible-galaxy collection download -p DOWNLOAD_PATHChoose the download directory Tarballs go to ./collections unless another directory is named here.
ansible-galaxy collection download -nDownload without dependencies Only the collections you name are fetched.
Creating and publishing collections 11
Command What it does
ansible-galaxy collection init my_namespace.my_collectionCreate a collection skeleton Run it in a path that contains ansible_collections; it creates the namespace and collection directories.
ansible-galaxy collection init --init-path INIT_PATHChoose where to create it The skeleton lands in the current working directory unless a path is given.
ansible-galaxy collection init --collection-skeleton COLLECTION_SKELETONUse a custom skeleton Bases the new collection on a template directory of your own.
ansible-galaxy collection init -e EXTRA_VARSSet extra variables Uses the same key=value, YAML/JSON or @file forms as on the other tools.
ansible-galaxy collection init -fOverwrite an existing collection Forces init to replace a collection that is already there.
ansible-galaxy collection buildBuild a collection tarball Builds from the directory that holds galaxy.yml, the current one by default; the artifact is what you publish.
ansible-galaxy collection build --output-path OUTPUT_PATHChoose the build output path The tarball is written to the current directory unless this is set.
ansible-galaxy collection publish path/to/my_namespace-my_collection-1.0.0.tar.gzPublish a collection Uploads the built tarball to the Galaxy server from the command line.
ansible-galaxy collection publish --token API_KEYAuthenticate with an API token The key comes from the token page of galaxy.ansible.com; --api-key is an alias.
ansible-galaxy collection publish --no-waitReturn without waiting Does not hold on for the validation results of the import.
ansible-galaxy collection publish --import-timeout IMPORT_TIMEOUTLimit the import wait How long the command waits for the server-side import to finish.
Galaxy roles 26
Command What it does
ansible-galaxy role install namespace.role_nameInstall a role Downloads it to the first writable directory of the roles path, normally ~/.ansible/roles.
ansible-galaxy role install --roles-path . geerlingguy.apacheInstall into a chosen directory Here the role lands in the current working directory.
ansible-galaxy role install geerlingguy.apache,3.2.0Install a specific role version The value after the comma is a GitHub release tag that Galaxy imported as a version.
ansible-galaxy role install git+https://github.com/geerlingguy/ansible-role-apache.git,0b7cd353c0250e87a26e0499e59e7fd265cc2f25Install a role from Git Points straight at the repository; a branch name or commit hash follows the comma.
ansible-galaxy role install -r requirements.ymlInstall roles from a file Roles from requirement files that the root file includes are installed as well.
ansible-galaxy role install -fReinstall over an existing role Forces the role to be overwritten when it is already installed.
ansible-galaxy role install -nSkip role dependencies Roles listed as dependencies are not downloaded; long form --no-deps.
ansible-galaxy role install -gKeep SCM metadata Long form --keep-scm-meta; the role is packaged with tar, not with the archive command of the SCM.
ansible-galaxy role listList installed roles Prints each role found in the roles path with its version.
ansible-galaxy role remove namespace.role_nameRemove an installed role Deletes the role from the local roles path.
ansible-galaxy role search elasticsearch --author geerlingguySearch Galaxy for roles Returns at most the first 1000 matches for the keyword, filtered here by author.
ansible-galaxy role search --author AUTHORFilter by author Takes the GitHub username of the role author.
ansible-galaxy role search --galaxy-tags GALAXY_TAGSFilter by Galaxy tags
ansible-galaxy role search --platforms PLATFORMSFilter by platform
ansible-galaxy role info username.role_nameShow role details Returns everything Galaxy has recorded about the role.
ansible-galaxy role init role_nameCreate a role skeleton Creates the directories and main.yml files a role needs in the current working directory.
ansible-galaxy role init --role-skeleton ROLE_SKELETONUse a custom role skeleton The new role is based on a template directory of your own.
ansible-galaxy role init --type ROLE_TYPEChoose an alternate role type The accepted types are container, apb and network.
ansible-galaxy role import github_user github_repoImport a role into Galaxy Needs an API token; unless told otherwise it waits and shows the import as it progresses.
ansible-galaxy role import --branch REFERENCEImport a specific branch Otherwise the default branch of the repository is imported.
ansible-galaxy role import --role-name ROLE_NAMERename the imported role For a role that should not carry the name of its repository.
ansible-galaxy role import --statusCheck the last import Reports on the latest import request for that user and repository.
ansible-galaxy role delete github_user github_repoDelete a role from Galaxy The GitHub repository itself is left untouched.
ansible-galaxy role setup travis github_user github_repo xxx-travis-token-xxxSet up a Travis integration A Travis build then triggers an import in Galaxy; the token itself is not stored there.
ansible-galaxy role setup --listList integrations Shows each integration with the ID that --remove needs.
ansible-galaxy role setup --remove REMOVE_IDRemove an integration Disables and removes the integration that has this ID.
Galaxy server and general options 8
Command What it does
ansible-galaxy collection install -s API_SERVERUse another Galaxy server Takes the API URL of the server; --server is the long form.
ansible-galaxy collection install -cIgnore certificate errors Long form --ignore-certs; SSL validation failures no longer stop the command.
ansible-galaxy collection install --timeout TIMEOUTSet the server timeout Applies to requests sent to the Galaxy server; 60 seconds unless changed.
ansible-galaxy collection install --no-cacheBypass the response cache The cached server responses are not consulted for this run.
ansible-galaxy collection install --clear-response-cacheClear the response cache
ansible-galaxy -hShow help Help exists at each level: the tool, collection or role, and every action below them.
ansible-galaxy --versionShow version and paths
ansible-galaxy -vIncrease verbosity The collection guides use -vvv on list and verify for more detail.
Documentation and configuration lookups 23
Command What it does
ansible --versionShow version and paths Reports the installed ansible-core version with the config file and module search path in use.
ansible-doc yumRead a module's documentation Give the name of a module to print its documentation in the terminal.
ansible-doc -lList available plugins Modules are listed unless -t picks another type; a namespace or collection name filters the list.
ansible-doc -FList plugins with source files Shows names and file locations without the summaries.
ansible-doc -t module -lList plugins of one type The -t value selects the plugin type; module is what applies when it is left out.
ansible-doc -t become -lList become plugins These are the names --become-method accepts.
ansible-doc -t connection -lList connection plugins Shows the connection types that can be given to -c.
ansible-doc -t inventory -lList inventory plugins
ansible-doc -t keyword NAMELook up a playbook keyword Shows, among other things, whether the keyword supports templating.
ansible-doc -sShow a playbook snippet Available for inventory, lookup and module plugins.
ansible-doc -jOutput JSON
ansible-doc -e ENTRY_POINTSelect a role entry point Applies when documenting roles, which is plugin type role.
ansible-doc -r ROLES_PATHSet the roles path Tells ansible-doc which directory holds your roles; repeatable.
ansible-config listList available settings The output can be switched to JSON or YAML with --format.
ansible-config list -t allList plugin settings too The -t value filters by plugin type: all, base, become, connection and others.
ansible-config dumpShow current settings Prints the settings in effect, with ansible.cfg merged in when one is specified.
ansible-config dump --only-changedShow only changed settings Hides everything still at its default value; --changed-only is an alias.
ansible-config dump --format jsonDump settings as JSON The dump formats are json, yaml and display.
ansible-config dump -c CONFIG_FILEUse a specific config file Otherwise the first file found in the precedence order is read.
ansible-config viewDisplay the config file Shows the contents of the configuration file currently in use.
ansible-config init --disabled > ansible.cfgGenerate a commented ansible.cfg Writes every default setting to the file, each entry commented out so that nothing changes yet.
ansible-config init --disabled -t all > ansible.cfgGenerate ansible.cfg with plugins Adds the settings of the available plugins for a fuller file.
ansible-config validateValidate the configuration Checks the config file and environment variables; only base settings unless -t names plugins.
Pull mode 17
ansible-pull reuses two letters: -C is --checkout (check mode is spelled --check) and -f is --force, not forks.
Command What it does
ansible-pull -U URL playbook.ymlPull and run a playbook Checks out the repository and runs the named playbook from it on the host.
ansible-pull -U URLSet the repository URL Names the VCS repository that holds the playbooks.
ansible-pull -C CHECKOUTChoose the revision to check out Accepts a branch, tag or commit; in this tool -C is not check mode.
ansible-pull -d DESTSet the checkout directory The repository is checked out into this path.
ansible-pull -m MODULE_NAMEChoose the repository module One of git, subversion, hg or bzr; git when omitted.
ansible-pull -i INVENTORYChoose the inventory
ansible-pull -oRun only when the repo changed Skips the playbook when the checkout brought no update; long form --only-if-changed.
ansible-pull -fRun even if the update fails The playbook still runs when the repository could not be refreshed; here -f means --force, not forks.
ansible-pull -s SLEEPWait a random interval first Sleeps between 0 and the given number of seconds, which spreads out git requests from many hosts.
ansible-pull --purgeDelete the checkout afterwards Removes the working copy once the playbook run is over.
ansible-pull --cleanDiscard local modifications Files changed in the working repository are thrown away.
ansible-pull --fullClone the full history Without it the checkout is a shallow clone.
ansible-pull --accept-host-keyAccept the repository host key Adds the key for the repository URL when it is not known yet.
ansible-pull --verify-commitVerify the commit signature Aborts the run when the GPG signature of the checked-out commit does not verify.
ansible-pull --track-subsTrack submodule updates Has the effect of the --remote flag of git submodule update.
ansible-pull --checkRun in check mode Written out in full because -C belongs to --checkout in this tool.
ansible-pull --diffShow file differences
Interactive console 18
Command What it does
ansible-consoleStart the interactive console Opens a REPL for running ad hoc tasks against the inventory, with tab completion.
ansible-console -i INVENTORYOpen the console on an inventory
ansible-console -l SUBSETLimit the console to a subset
ansible-console -bStart with become on Become can also be toggled later with the become command inside the console.
ansible-console -u REMOTE_USERSet the remote user
ansible-console --stepConfirm each task Asks before every task typed into the console is run.
cd [pattern]Change the host or group Typed inside the console; host patterns such as app*.dc*:!app01* are allowed.
listList available hosts
list groupsList groups in the current path
becomeToggle become Console command that flips privilege escalation on or off for the tasks that follow.
!yum update -yRun a shell command A leading ! sends the line to the shell module, not to the module of that name.
forks [num]Change the fork count
verbosity [num]Set the verbosity level
check [bool]Toggle check mode
diff [bool]Toggle diff mode
timeout [integer]Set the task timeout Given in seconds; 0 disables the timeout.
help [command/module]Show console help Displays documentation for a console command or for a module.
exitLeave the console
No row on this page matches that filter.
Notes
The flags that prevent accidents ansible-playbook -C is check mode: modules that support it report what they would change without changing it, and adding ansible-playbook -D shows the differences in files and templates. Diff output is long, so the check mode guide limits it to one host, as in ansible-playbook foo.yml --check --diff --limit foo.example.com. ansible-playbook --syntax-check parses the playbook without executing it, and ansible-playbook --list-hosts and ansible-playbook --list-tasks confirm the host selection and the task list before a run. ansible-playbook --step asks for confirmation at every task, which is slow but suits a playbook you have never run. Check mode is a simulation: tasks whose conditions depend on results registered by earlier tasks produce no output in it.
Targeting and privilege ansible -i INVENTORY points at an inventory path or a comma-separated host list. A value with a trailing comma, as in -i 127.0.0.2, , is read as a host list, so a host that is in no inventory file can be targeted, but no inventory variables are read for it. ansible -l SUBSET narrows the pattern further, and ansible -m MODULE_NAME with ansible -a MODULE_ARGS is the ad hoc form: ansible myhosts -m ping -i inventory.ini pings a group, and with no -m the command module runs whatever -a holds. ansible -b escalates with become (sudo by default) and ansible -K prompts for the become password; neither implies the other. ansible -u REMOTE_USER sets the login user when it differs from your local one.
Vault and Galaxy Secrets go through ansible-vault, and every subcommand takes the same password options: ansible-vault encrypt -J prompts for the vault password, ansible-vault encrypt --vault-password-file VAULT_PASSWORD_FILES reads it from a file, and ansible-vault encrypt --vault-id VAULT_IDS adds a label, written label@source. ansible-vault encrypt_string -p prompts for a single value and prints it encrypted, ready to paste into a vars file. At run time the same options go on the playbook command, as in ansible-playbook --vault-id dev@prompt site.yml. For dependencies, ansible-galaxy collection install -r requirements.yml installs the collections listed in a requirements file, ansible-galaxy collection install -p COLLECTIONS_PATH chooses where, and ansible-galaxy collection install -U upgrades what is already installed. ansible-galaxy install -r requirements.yml, without the word collection or role, installs both kinds from one file.
Questions
Why is the same flag listed under several commands? The tools accept largely the same connection, become, inventory and vault options, so a flag such as -i exists on ansible, ansible-playbook, ansible-console and ansible-pull alike. They are listed per tool because a few letters change meaning: on ansible-pull, -C is --checkout and -f is --force.
How do I dry-run a playbook? ansible-playbook -C runs in check mode. Add -D to see the differences in files that would change, and limit the run to one host, because diff output is long.
How do I target one host without editing the inventory? Use -i with a trailing comma: ansible-playbook -i myhost, site.yml. The host does not have to be in any inventory file, but inventory variables are not read for it.
Do command-line options override what the playbook sets? No. Command-line options override configuration only; playbook keywords and variables from inventory or playbooks win over them. Extra vars are the exception: ansible -u carol -e 'ansible_user=brian' -a whoami all connects as brian.
What is the difference between -k and -K? Lowercase -k asks for the connection (SSH) password; uppercase -K asks for the become password used for privilege escalation. Asking for a become password does not switch become on; that takes -b.
Which Ansible version do these options come from? ansible-core 2.21.5. Option rows were checked against the --help output of that release, and example rows against the stable-2.21 branch of the Ansible documentation.
Sources and checks
ansible-core 2.21.5: --help output of the nine command-line tools and their subcommands ansible-core 2.21.5: command-line reference pages built with the release's own generator (packaging/cli-doc) Synopsis and description text of each tool and subcommand Ansible documentation, stable-2.21 branch: Introduction to ad hoc commands Printed ad hoc command lines: reboot, files, packages, users, services, facts, check mode Ansible documentation, stable-2.21 branch: Ansible CLI cheatsheet Example lines for ansible-playbook, ansible-galaxy, ansible and ansible-doc with each flag explained Ansible documentation, stable-2.21 branch: Encrypting content with Ansible Vault ansible-vault create, encrypt, view, edit, rekey, decrypt and encrypt_string examples Ansible documentation, stable-2.21 branch: Managing vault passwords Password files and client scripts
31 more source pages Ansible documentation, stable-2.21 branch: Using encrypted variables and files Passing vault passwords and vault IDs to ansible-playbook Ansible documentation, stable-2.21 branch: Installing collections ansible-galaxy collection install examples, signatures and keyrings Ansible documentation, stable-2.21 branch: Listing collections ansible-galaxy collection list examples Ansible documentation, stable-2.21 branch: Verifying collections ansible-galaxy collection verify examples Ansible documentation, stable-2.21 branch: Downloading collections ansible-galaxy collection download examples Ansible documentation, stable-2.21 branch: Galaxy User Guide Searching, installing, listing and removing roles Ansible documentation, stable-2.21 branch: Validating tasks: check mode and diff mode --check and --diff examples Ansible documentation, stable-2.21 branch: Tags --tags, --skip-tags, --list-tags and --list-tasks examples and special tags Ansible documentation, stable-2.21 branch: Executing playbooks for troubleshooting --start-at-task and --step Ansible documentation, stable-2.21 branch: Understanding privilege escalation: become Become command-line options Ansible documentation, stable-2.21 branch: Ansible playbooks Running playbooks, check mode, ansible-pull Ansible documentation, stable-2.21 branch: Patterns: targeting hosts and groups Patterns, --limit examples and the trailing-comma host list Ansible documentation, stable-2.21 branch: How to build your inventory Multiple inventory sources and inventory directories Ansible documentation, stable-2.21 branch: Building an inventory (getting started) Verifying an inventory and pinging a group Ansible documentation, stable-2.21 branch: Creating a playbook (getting started) Running a first playbook Ansible documentation, stable-2.21 branch: Configuring Ansible Generating ansible.cfg with ansible-config init Ansible documentation, stable-2.21 branch: Installing roles and collections from the same requirements.yml file ansible-galaxy install -r Ansible documentation, stable-2.21 branch: Installing an older version of a collection Version range identifiers Ansible documentation, stable-2.21 branch: Installing a collection from a Git repository git+ URIs on the install command line Ansible documentation, stable-2.21 branch: Introduction to modules ansible-doc examples Ansible documentation, stable-2.21 branch: Become plugins Listing become plugins with ansible-doc Ansible documentation, stable-2.21 branch: Inventory plugins ansible-inventory --graph with a plugin config, listing inventory plugins Ansible documentation, stable-2.21 branch: Controlling how Ansible behaves: precedence rules How command-line options rank against keywords, variables and extra vars Ansible documentation, stable-2.21 branch: Using variables --extra-vars formats Ansible documentation, stable-2.21 branch: Error handling in playbooks Forced handlers Ansible documentation, stable-2.21 branch: Distributing collections Building and publishing a collection Ansible documentation, stable-2.21 branch: Creating collections ansible-galaxy collection init Ansible documentation, stable-2.21 branch: Galaxy Developer Guide Role init, import, delete and Travis setup Ansible documentation, stable-2.21 branch: Connection plugins Listing connection plugins with ansible-doc Ansible documentation, stable-2.21 branch: Asynchronous actions and polling Background ad hoc tasks with -B and -P Ansible documentation, stable-2.21 branch: Frequently Asked Questions Inventory variables and keyword documentation
Every row on this page was matched to a line in the documentation above on 6 October 2026 . A binding that could not be found there is not listed.
Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.