Ansible commands

Command lines and options of the nine ansible-core tools, checked against ansible-core 2.21.5: the --help text of every tool and subcommand, plus example lines from the Ansible documentation. Rows are grouped by task, from ad hoc commands and playbook runs to vault, Galaxy, inventory, ansible-pull and the console. Capitals such as INVENTORY are placeholders. Many options are shared: ansible-playbook -i INVENTORY is also accepted by ansible, ansible-inventory, ansible-console and ansible-pull. Modules and ansible-test are left out.

321 commands in 17 sections. Checked row by row against ansible-core 2.21.5: --help output of the nine command-line tools and their subcommands on . Edited by Jay.

Ad hoc commands 22

CommandWhat it does
ansible [pattern] -m [module] -a "[module options]"Ad hoc command formThe 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 groupWith 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 forksRaises 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 commandSingle 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 hostsSends 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 permissionsThe 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 directoryWorks 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 directoryA directory given as dest is removed together with everything inside it.
ansible webservers -m ansible.builtin.yum -a "name=acme state=present"Install a packageLeaves 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 versionThe wanted version is written as part of the package name.
ansible webservers -m ansible.builtin.yum -a "name=acme state=latest"Update a packageBrings 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 packageAfter 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 accountDeletes the account named foo from every host in the inventory.
ansible webservers -m ansible.builtin.service -a "name=httpd state=started"Start a serviceLike 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 serviceRestarts 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 factsPrints 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 taskIn check mode the file is neither created nor updated on any remote system.
ansible myhosts -m ping -i inventory.iniPing an inventory groupRuns 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 backgroundStarts 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 jobGive 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 pollingLets the job run for up to 30 minutes and looks at its status every 60 seconds.

Ad hoc command options 16

CommandWhat it does
ansible -m MODULE_NAMEChoose the moduleNames the action to run; without it the command module is used.
ansible -a MODULE_ARGSPass module argumentsTakes key=value pairs separated by spaces, or a JSON string for more complex structures.
ansible -f FORKSSet parallel forksSets how many hosts are worked on at once; five when the option is absent.
ansible -B SECONDSRun asynchronouslyThe task goes to the background and is failed if it has not finished after this many seconds.
ansible -P POLL_INTERVALSet the async poll intervalOnly matters together with -B; 15 is used when it is left out.
ansible -oCondense outputLong form --one-line; each result is printed in a compact form.
ansible -t TREELog output to a directoryLong form --tree; results are written under the directory you name.
ansible -e EXTRA_VARSSet extra variablesAccepts key=value pairs, YAML or JSON, or a file name with @ in front; repeatable.
ansible -CRun in check modeNothing is changed on the hosts; Ansible tries to predict what would change.
ansible -DShow file differencesPrints what changed in small files and templates; pairs well with -C.
ansible --task-timeout TASK_TIMEOUTSet a task time limitThe limit is given in seconds and has to be a positive integer.
ansible --playbook-dir BASEDIRSet a substitute playbook directoryGives relative lookups such as roles/ and group_vars/ a base path, since ad hoc runs have no playbook.
ansible -M MODULE_PATHAdd module search pathsPaths are separated by colons and placed in front of the default module library; repeatable.
ansible -vIncrease verbosityRepeat the letter for more detail: -vvv is a sensible start and -vvvv helps with connection problems.
ansible --flush-cacheClear the fact cacheCached facts are discarded for all inventory hosts.
ansible -hShow helpLists 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.

CommandWhat it does
ansible-playbook -i inventory.ini playbook.yamlRun a playbook with an inventoryThe -i option names the inventory file the plays draw their hosts from.
ansible-playbook playbook.yml -f 10Run a playbook with ten forksWorks on up to ten hosts in parallel where the default would be five.
ansible-playbook --check playbook.yamlDry-run a playbookProduces a report of would-be changes and leaves the systems untouched.
ansible-playbook foo.yml --check --diff --limit foo.example.comPreview diffs on one hostDiff mode prints a lot, so the guide pairs it with a limit to a single host.
ansible-playbook -CRun in check modeShort for --check; modules that support it report what they would change.
ansible-playbook -DShow file differencesShort for --diff; usable alone or with -C, mostly with modules that manage files.
ansible-playbook --syntax-checkCheck playbook syntaxParses the playbook and stops; no task is executed.
ansible-playbook --list-tasksList tasks without runningShows the tasks a run would execute; add --tags or --skip-tags to preview a selection.
ansible-playbook --stepConfirm each taskStops before every task and asks whether to run it.
ansible-playbook playbook.yml --stepRun in step modeAnswer 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 taskExecution 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 taskHandy after a failure; it does not find tasks inside dynamically included roles or task files.
ansible-playbook --force-handlersRun handlers after failuresNotified handlers then run on all hosts, including those with failed tasks.
ansible-playbook --flush-cacheClear the fact cache
ansible-playbook -e EXTRA_VARSSet extra variablesVariables 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=valueValues 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 JSONJSON keeps Booleans, integers, floats and lists as their real types.
ansible-playbook release.yml --extra-vars "@some_file.json"Load variables from a fileThe @ prefix marks a JSON or YAML file of variable definitions.
ansible-playbook -f FORKSSet parallel forksWithout it Ansible uses five parallel processes.
ansible-playbook -vIncrease verbosityThe built-in plugins react to as many as six v letters; --verbose is the long form.
ansible-playbook -M MODULE_PATHAdd module search pathsLoads 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 flagsThe cheat sheet example: inventory, SSH user and password prompt, forks, timeout, tag, module path and become.
ansible-playbook -hShow helpPrints all ansible-playbook options and exits.
ansible-playbook --versionShow version and pathsPrints the same version, config file and path details as ansible --version.

Limiting hosts and tags 18

CommandWhat it does
ansible -l SUBSETLimit to a host subsetNarrows the hosts chosen by the pattern with a second pattern.
ansible-playbook -l SUBSETLimit to a host subsetShort for --limit; takes a host, a group or any other pattern.
ansible-playbook site.yml --limit datacenter2Limit a run to a groupRestricts this run to datacenter2 without editing the hosts line of the playbook.
ansible-playbook site.yml --limit @retry_hosts.txtLimit to hosts from a fileAn @ in front of the name makes --limit read the host list from that file.
ansible-playbook site.yml --limit @site.retryRerun failed hostsUses the .retry file written after a run when RETRY_FILES_ENABLED is on.
ansible-playbook -i inventory_test -l appservers site.ymlRun on one inventory groupApplies site.yml only to the appservers group of the test inventory.
ansible --list-hostsList matching hostsPrints the hosts the pattern selects and runs nothing.
ansible-playbook --list-hostsList matching hostsPrints the selected hosts and exits before any task runs.
ansible-playbook -t TAGSSelect tasks by tagShort for --tags; plays and tasks without a matching tag are left out, and the option can be repeated.
ansible-playbook example.yml --tags "configuration,packages"Run tasks with given tagsRuns tasks and blocks carrying either tag, plus anything tagged always.
ansible-playbook --tags taggedRun tasks that have any tagTasks carrying the never tag stay excluded even so.
ansible-playbook --tags untaggedRun only untagged tasksAnything tagged always runs as well, despite having a tag.
ansible-playbook --skip-tags SKIP_TAGSSkip tagged tasksWins over --tags when a task matches both.
ansible-playbook example.yml --skip-tags "packages"Run all but one tagEverything else in the playbook runs, apart from tasks tagged never.
ansible-playbook example.yml --tags "all,never"Include never-tagged tasksAdds the tasks that the never tag normally keeps out of a run.
ansible-playbook example.yml --tags "tag1,tag3" --skip-tags "tag4"Combine tags and skip-tagsA task with tag1 or tag3 is left out when it carries tag4 as well.
ansible-playbook --list-tagsList available tagsShows the tags in the playbook without running tasks; tags inside dynamic includes are not shown.
ansible-playbook example.yml --tags "configuration,packages" --list-tasksPreview tasks for tagsLists the tasks those two tags select and executes none of them.

Privilege escalation 12

-K only asks for a password and --become-user only names the account; become itself is switched on with -b.

CommandWhat it does
ansible -bRun with becomeEscalates privileges on the target, with sudo unless another method is set; it does not prompt for a password.
ansible -KAsk for the become passwordThe password you enter is used for all hosts.
ansible --become-user BECOME_USERChoose the become userRoot is the default; on its own this option does not switch become on.
ansible --become-method BECOME_METHODChoose the become methodSudo 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 rootLogs 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 becomeRuns on the local system and prompts for the privilege escalation password.
ansible-playbook -bRun with becomeLike every command-line option it yields to a become keyword set in the playbook.
ansible-playbook -KAsk for the become passwordLong form --ask-become-pass; asking for the password does not by itself enable become.
ansible-playbook --become-user BECOME_USERChoose the become userSets which account tasks run as after escalation; root when omitted.
ansible-playbook --become-method BECOME_METHODChoose the become methodThe guide lists sudo, su, pbrun, pfexec, doas, dzdo, ksu, runas and machinectl.
ansible-playbook --become-password-file BECOME_PASSWORD_FILERead become password from fileTakes 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.

CommandWhat it does
ansible -u REMOTE_USERSet the remote userWithout it the ansible command connects as your own user account.
ansible atlanta -a "/sbin/reboot" -f 10 -u usernameConnect as another userLogs 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 optionWhen 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 varsThe -e variable outranks -u, so the connection is made as brian.
ansible -kAsk for connection passwordPrompts for the password used for SSH authentication; lowercase, unlike -K for become.
ansible --connection-password-file CONNECTION_PASSWORD_FILERead connection password from fileAn alternative to the -k prompt; --conn-pass-file is an alias.
ansible -c CONNECTIONChoose the connection typeSsh is the default; ansible-doc -t connection -l lists the plugins that can be named here.
ansible -T TIMEOUTSet the connection timeoutGiven in seconds; what applies otherwise depends on the connection plugin.
ansible --private-key PRIVATE_KEY_FILEUse a private key fileAuthenticates the connection with this key; --key-file is the same option.
ansible --ssh-common-args SSH_COMMON_ARGSAdd shared SSH argumentsHanded to ssh, scp and sftp alike; ProxyCommand is the example the help gives.
ansible --ssh-extra-args SSH_EXTRA_ARGSAdd ssh-only argumentsReaches ssh but not scp or sftp; the help gives -R as an example.
ansible --scp-extra-args SCP_EXTRA_ARGSAdd scp-only argumentsHanded to scp alone; the help gives -l as an example.
ansible --sftp-extra-args SFTP_EXTRA_ARGSAdd sftp-only argumentsHanded to sftp alone, for instance -f or -l.
ansible-playbook -u REMOTE_USERSet the remote userOverrides configuration only; a user set by a playbook keyword or an inventory variable still wins.
ansible-playbook -kAsk for connection passwordLong 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 typeWhen the option is absent the ssh connection plugin is used.
ansible-playbook -T TIMEOUTSet the connection timeoutThe 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

CommandWhat it does
ansible -i INVENTORYChoose the inventoryTakes 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 hocRepeated -i values are appended, so hosts from both files are in scope.
ansible-playbook -i INVENTORYChoose the inventoryA 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 onceUseful for one action across normally separate environments such as staging and production.
ansible-playbook example.yml -i inventoryUse an inventory directoryEvery source inside the directory is merged into one inventory, read in alphabetical order.
ansible-inventory -i inventory.ini --listVerify an inventory fileDumps everything Ansible reads from the file, in JSON unless another format is asked for.
ansible-inventory --listDump the whole inventoryOne of three actions, exactly one of which has to be given; the others are --graph and --host.
ansible-inventory --graphShow the inventory as a graphA group name may follow to graph only that group; --limit is ignored.
ansible-inventory --host HOSTShow info for one hostPrints the data for that host alone, as an inventory script would; --limit is ignored.
ansible-inventory --list --yamlList the inventory as YAMLThe FAQ gives this command for seeing the inventory variables defined for a host.
ansible-inventory -yUse YAML outputReplaces the default JSON; it has no effect on --graph.
ansible-inventory --tomlUse TOML outputLike -y, it is ignored when graphing.
ansible-inventory --varsAdd variables to the graphOnly has an effect together with --graph.
ansible-inventory --exportExport-friendly listingWith --list, arranges the output for export, which is not how Ansible itself processed the inventory.
ansible-inventory --output OUTPUT_FILEWrite the listing to a fileApplies to --list; nothing is printed on screen.
ansible-inventory -i demo.aws_ec2.yml --graphGraph a plugin inventoryShows what an inventory plugin returns once the options in its config file are filled in.
ansible-inventory --playbook-dir BASEDIRSet a substitute playbook directoryNeeded to test an inventory plugin that lives in a collection next to a playbook.
ansible-inventory -l SUBSETLimit the hosts shownFilters the listing by a pattern; --graph and --host ignore it.

Vault files and strings 32

CommandWhat it does
ansible-vault createCreate an encrypted fileOpens 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 passwordEncrypts 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 passwordThe part before @ is the vault ID label; prompt makes the tool ask for the password.
ansible-vault create --skip-tty-checkSkip the TTY checkLets the editor open even though no terminal is attached.
ansible-vault encrypt foo.yml bar.yml baz.ymlEncrypt existing filesSeveral files can be handled in one command.
ansible-vault encrypt --vault-id project@prompt foo.yml bar.yml baz.ymlEncrypt with a vault IDLabels the files project and asks which password to encrypt them with.
ansible-vault encrypt --vault-id VAULT_IDSGive a vault identityEvery 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 passwordThe long spellings are --ask-vault-password and --ask-vault-pass.
ansible-vault encrypt --encrypt-vault-id ENCRYPT_VAULT_IDChoose the encrypting vault IDNeeded 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 filesShows the contents of the files without editing them.
ansible-vault edit foo.ymlEdit an encrypted fileDecrypts 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 IDFor a file whose password lives in vault2 and whose label is pass2.
ansible-vault rekey foo.yml bar.yml baz.ymlChange the vault passwordAsks 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 IDMoves 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 IDThe identity the files carry after they are re-encrypted.
ansible-vault rekey --new-vault-password-file NEW_VAULT_PASSWORD_FILERead the new password from fileTakes the replacement password from a file.
ansible-vault decrypt foo.yml bar.yml baz.ymlDecrypt files permanentlyWrites the files back to disk unencrypted; use edit when you only want to change something.
ansible-vault decryptDecrypt a pasted stringWith 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 fileA dash sends the result to stdout; encrypt and encrypt_string accept the option as well.
ansible-vault encrypt_stringEncrypt a single stringThe 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 variablePrints 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 IDSame 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 pipeA 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 inWithout 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 stringAsks for the value interactively; typing is hidden unless --show-input is added.
ansible-vault encrypt_string --show-inputShow the string as typedTurns off the hidden typing used at the prompt.
ansible-vault encrypt_string -n ENCRYPT_STRING_NAMESName the variableLong form --name; it can be given more than once.
ansible-vault encrypt_string --stdin-name ENCRYPT_STRING_STDIN_NAMEName the stdin variableSets what the variable is called when the value arrives on standard input.
ansible-vault -hShow helpLists 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

CommandWhat it does
ansible-playbook --ask-vault-pass site.ymlPrompt for the vault passwordEnough when all encrypted content in the run shares a single password.
ansible-playbook -JAsk for vault passwordShort for --ask-vault-pass and --ask-vault-password.
ansible-playbook --vault-password-file /path/to/my/vault-password-file site.ymlUse a vault password fileThe file holds the password as one line of text.
ansible-playbook --vault-password-file VAULT_PASSWORD_FILESGive a vault password fileMay also point to a client script that supplies the password.
ansible-playbook --vault-id VAULT_IDSGive a vault identityWritten 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 passwordAsks for the password that belongs to the dev vault ID.
ansible-playbook --vault-id dev@dev-password site.ymlRead a labelled password fileTakes the dev password from the file named dev-password.
ansible-playbook --vault-id dev@dev-password --vault-id prod@prompt site.ymlSupply several vault passwordsLabels 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 IDBehaves like --ask-vault-pass, so it is rarely needed.
ansible-playbook --extra-vars @secrets.enc --vault-password-file secrets.passLoad an encrypted vars fileLoads 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 scriptAnsible runs the script with a --vault-id option so it can return the right password.
ansible --vault-id VAULT_IDSGive a vault identityAd 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 passwordPrompts 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 variableThe debug module prints the original value of a variable stored encrypted in vars.yml.

Installing collections 24

CommandWhat it does
ansible-galaxy collection install my_namespace.my_collectionInstall a collectionFetches it from the configured Galaxy server into ~/.ansible/collections unless told otherwise.
ansible-galaxy collection install my_namespace.my_collection --upgradeUpgrade a collectionMoves an installed collection to the newest version the Galaxy server offers.
ansible-galaxy collection install -UUpgrade installed collectionsShort for --upgrade; dependencies are updated too unless --no-deps is added.
ansible-galaxy collection install -r requirements.ymlInstall from a requirements fileInstalls every collection named in requirements.yml.
ansible-galaxy install -r requirements.ymlInstall roles and collections togetherOne 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 versionPre-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 rangeThe 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 tarballansible_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 directoryThe 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 repositoryThe 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 pathReplaces the first COLLECTIONS_PATH entry from the configuration as the destination.
ansible-galaxy collection install -fReinstall over an existing copyForces the collection to be overwritten when it is already installed.
ansible-galaxy collection install --force-with-depsForce reinstall with dependenciesOverwrites the collection together with everything it depends on.
ansible-galaxy collection install -nSkip dependenciesLong form --no-deps; the usage line shows it as an alternative to --force-with-deps.
ansible-galaxy collection install -iContinue after errorsMoves on to the next collection when one fails; dependency conflicts still stop the run.
ansible-galaxy collection install --preAllow pre-release versionsSemantic-versioning pre-releases are skipped unless this is set.
ansible-galaxy collection install --offlineInstall without contacting serversWorks 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 installThe option can be left out when a GnuPG keyring is already configured.
ansible-galaxy collection install --keyring KEYRINGSet the verification keyringNames the keyring that signatures are checked against.
ansible-galaxy collection install --signature SIGNATURESAdd a signature sourceChecks 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 signaturesOne 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 codeSignatures that fail only for a missing public key no longer block the install; repeatable.
ansible-galaxy collection install --ignore-signature-status-codesIgnore several status codesTakes a list separated by spaces, such as NO_PUBKEY FAILURE; place it after the collection names.
ansible-galaxy collection install --disable-gpg-verifyDisable GPG verificationSkips signature checks for collections that come from a Galaxy server.

Listing, verifying and downloading collections 14

CommandWhat it does
ansible-galaxy collection listList installed collectionsCovers every configured collections path, including collections under development that have a galaxy.yml.
ansible-galaxy collection list fortinet.fortiosList one collectionGive 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 pathsPaths separated by colons are searched ahead of the configured ones.
ansible-galaxy collection list --format jsonChoose the list formatThe accepted values are human, yaml and json.
ansible-galaxy collection verify my_namespace.my_collectionVerify an installed collectionCompares 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 detailsAdds 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 versionWith no version the comparison is made against the latest release on the server.
ansible-galaxy collection verify -r requirements.ymlVerify from a requirements fileDependencies 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 serverUses the signature data saved at install time to check the collection locally.
ansible-galaxy collection download my_namespace.my_collectionDownload a collectionFetches 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 fileThe download folder also receives a requirements.yml that install -r can use offline.
ansible-galaxy collection download -p DOWNLOAD_PATHChoose the download directoryTarballs go to ./collections unless another directory is named here.
ansible-galaxy collection download -nDownload without dependenciesOnly the collections you name are fetched.

Creating and publishing collections 11

CommandWhat it does
ansible-galaxy collection init my_namespace.my_collectionCreate a collection skeletonRun 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 itThe skeleton lands in the current working directory unless a path is given.
ansible-galaxy collection init --collection-skeleton COLLECTION_SKELETONUse a custom skeletonBases the new collection on a template directory of your own.
ansible-galaxy collection init -e EXTRA_VARSSet extra variablesUses the same key=value, YAML/JSON or @file forms as on the other tools.
ansible-galaxy collection init -fOverwrite an existing collectionForces init to replace a collection that is already there.
ansible-galaxy collection buildBuild a collection tarballBuilds 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 pathThe 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 collectionUploads the built tarball to the Galaxy server from the command line.
ansible-galaxy collection publish --token API_KEYAuthenticate with an API tokenThe key comes from the token page of galaxy.ansible.com; --api-key is an alias.
ansible-galaxy collection publish --no-waitReturn without waitingDoes not hold on for the validation results of the import.
ansible-galaxy collection publish --import-timeout IMPORT_TIMEOUTLimit the import waitHow long the command waits for the server-side import to finish.

Galaxy roles 26

CommandWhat it does
ansible-galaxy role install namespace.role_nameInstall a roleDownloads it to the first writable directory of the roles path, normally ~/.ansible/roles.
ansible-galaxy role install --roles-path . geerlingguy.apacheInstall into a chosen directoryHere the role lands in the current working directory.
ansible-galaxy role install geerlingguy.apache,3.2.0Install a specific role versionThe 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 GitPoints straight at the repository; a branch name or commit hash follows the comma.
ansible-galaxy role install -r requirements.ymlInstall roles from a fileRoles from requirement files that the root file includes are installed as well.
ansible-galaxy role install -fReinstall over an existing roleForces the role to be overwritten when it is already installed.
ansible-galaxy role install -nSkip role dependenciesRoles listed as dependencies are not downloaded; long form --no-deps.
ansible-galaxy role install -gKeep SCM metadataLong form --keep-scm-meta; the role is packaged with tar, not with the archive command of the SCM.
ansible-galaxy role listList installed rolesPrints each role found in the roles path with its version.
ansible-galaxy role remove namespace.role_nameRemove an installed roleDeletes the role from the local roles path.
ansible-galaxy role search elasticsearch --author geerlingguySearch Galaxy for rolesReturns at most the first 1000 matches for the keyword, filtered here by author.
ansible-galaxy role search --author AUTHORFilter by authorTakes 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 detailsReturns everything Galaxy has recorded about the role.
ansible-galaxy role init role_nameCreate a role skeletonCreates 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 skeletonThe new role is based on a template directory of your own.
ansible-galaxy role init --type ROLE_TYPEChoose an alternate role typeThe accepted types are container, apb and network.
ansible-galaxy role import github_user github_repoImport a role into GalaxyNeeds an API token; unless told otherwise it waits and shows the import as it progresses.
ansible-galaxy role import --branch REFERENCEImport a specific branchOtherwise the default branch of the repository is imported.
ansible-galaxy role import --role-name ROLE_NAMERename the imported roleFor a role that should not carry the name of its repository.
ansible-galaxy role import --statusCheck the last importReports on the latest import request for that user and repository.
ansible-galaxy role delete github_user github_repoDelete a role from GalaxyThe GitHub repository itself is left untouched.
ansible-galaxy role setup travis github_user github_repo xxx-travis-token-xxxSet up a Travis integrationA Travis build then triggers an import in Galaxy; the token itself is not stored there.
ansible-galaxy role setup --listList integrationsShows each integration with the ID that --remove needs.
ansible-galaxy role setup --remove REMOVE_IDRemove an integrationDisables and removes the integration that has this ID.

Galaxy server and general options 8

CommandWhat it does
ansible-galaxy collection install -s API_SERVERUse another Galaxy serverTakes the API URL of the server; --server is the long form.
ansible-galaxy collection install -cIgnore certificate errorsLong form --ignore-certs; SSL validation failures no longer stop the command.
ansible-galaxy collection install --timeout TIMEOUTSet the server timeoutApplies to requests sent to the Galaxy server; 60 seconds unless changed.
ansible-galaxy collection install --no-cacheBypass the response cacheThe cached server responses are not consulted for this run.
ansible-galaxy collection install --clear-response-cacheClear the response cache
ansible-galaxy -hShow helpHelp exists at each level: the tool, collection or role, and every action below them.
ansible-galaxy --versionShow version and paths
ansible-galaxy -vIncrease verbosityThe collection guides use -vvv on list and verify for more detail.

Documentation and configuration lookups 23

CommandWhat it does
ansible --versionShow version and pathsReports the installed ansible-core version with the config file and module search path in use.
ansible-doc yumRead a module's documentationGive the name of a module to print its documentation in the terminal.
ansible-doc -lList available pluginsModules are listed unless -t picks another type; a namespace or collection name filters the list.
ansible-doc -FList plugins with source filesShows names and file locations without the summaries.
ansible-doc -t module -lList plugins of one typeThe -t value selects the plugin type; module is what applies when it is left out.
ansible-doc -t become -lList become pluginsThese are the names --become-method accepts.
ansible-doc -t connection -lList connection pluginsShows the connection types that can be given to -c.
ansible-doc -t inventory -lList inventory plugins
ansible-doc -t keyword NAMELook up a playbook keywordShows, among other things, whether the keyword supports templating.
ansible-doc -sShow a playbook snippetAvailable for inventory, lookup and module plugins.
ansible-doc -jOutput JSON
ansible-doc -e ENTRY_POINTSelect a role entry pointApplies when documenting roles, which is plugin type role.
ansible-doc -r ROLES_PATHSet the roles pathTells ansible-doc which directory holds your roles; repeatable.
ansible-config listList available settingsThe output can be switched to JSON or YAML with --format.
ansible-config list -t allList plugin settings tooThe -t value filters by plugin type: all, base, become, connection and others.
ansible-config dumpShow current settingsPrints the settings in effect, with ansible.cfg merged in when one is specified.
ansible-config dump --only-changedShow only changed settingsHides everything still at its default value; --changed-only is an alias.
ansible-config dump --format jsonDump settings as JSONThe dump formats are json, yaml and display.
ansible-config dump -c CONFIG_FILEUse a specific config fileOtherwise the first file found in the precedence order is read.
ansible-config viewDisplay the config fileShows the contents of the configuration file currently in use.
ansible-config init --disabled > ansible.cfgGenerate a commented ansible.cfgWrites 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 pluginsAdds the settings of the available plugins for a fuller file.
ansible-config validateValidate the configurationChecks 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.

CommandWhat it does
ansible-pull -U URL playbook.ymlPull and run a playbookChecks out the repository and runs the named playbook from it on the host.
ansible-pull -U URLSet the repository URLNames the VCS repository that holds the playbooks.
ansible-pull -C CHECKOUTChoose the revision to check outAccepts a branch, tag or commit; in this tool -C is not check mode.
ansible-pull -d DESTSet the checkout directoryThe repository is checked out into this path.
ansible-pull -m MODULE_NAMEChoose the repository moduleOne of git, subversion, hg or bzr; git when omitted.
ansible-pull -i INVENTORYChoose the inventory
ansible-pull -oRun only when the repo changedSkips the playbook when the checkout brought no update; long form --only-if-changed.
ansible-pull -fRun even if the update failsThe playbook still runs when the repository could not be refreshed; here -f means --force, not forks.
ansible-pull -s SLEEPWait a random interval firstSleeps between 0 and the given number of seconds, which spreads out git requests from many hosts.
ansible-pull --purgeDelete the checkout afterwardsRemoves the working copy once the playbook run is over.
ansible-pull --cleanDiscard local modificationsFiles changed in the working repository are thrown away.
ansible-pull --fullClone the full historyWithout it the checkout is a shallow clone.
ansible-pull --accept-host-keyAccept the repository host keyAdds the key for the repository URL when it is not known yet.
ansible-pull --verify-commitVerify the commit signatureAborts the run when the GPG signature of the checked-out commit does not verify.
ansible-pull --track-subsTrack submodule updatesHas the effect of the --remote flag of git submodule update.
ansible-pull --checkRun in check modeWritten out in full because -C belongs to --checkout in this tool.
ansible-pull --diffShow file differences

Interactive console 18

CommandWhat it does
ansible-consoleStart the interactive consoleOpens 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 onBecome can also be toggled later with the become command inside the console.
ansible-console -u REMOTE_USERSet the remote user
ansible-console --stepConfirm each taskAsks before every task typed into the console is run.
cd [pattern]Change the host or groupTyped inside the console; host patterns such as app*.dc*:!app01* are allowed.
listList available hosts
list groupsList groups in the current path
becomeToggle becomeConsole command that flips privilege escalation on or off for the tasks that follow.
!yum update -yRun a shell commandA 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 timeoutGiven in seconds; 0 disables the timeout.
help [command/module]Show console helpDisplays documentation for a console command or for a module.
exitLeave the console

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

31 more source pages

Every row on this page was matched to a line in the documentation above on . 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.