Suitable API Documentation
- class suitable.api.Api(servers: Hosts, ignore_unreachable: bool = False, ignore_errors: bool = False, host_key_checking: bool = True, sudo: bool = False, dry_run: bool = False, verbosity: Verbosity = 'info', environment: dict[str, str] | None = None, strategy: Incomplete | None = None, collections_path: str | Sequence[str] | None = None, **options: Incomplete)[source]
Provides all available ansible modules as local functions:
api = Api('personal.server.dev') api.sync(src='/Users/denis/.zshrc', dest='/home/denis/.zshrc')
- Parameters:
servers –
A sequence of servers, a string with space-delimited servers or a dict with server name as key and ansible host variables as values. The api instances will operate on these servers only. Servers which cannot be reached or whose use triggers an error are taken out of the list for the lifetime of the object.
Examples of valid uses:
api = Api(['web.example.org', 'db.example.org']) api = Api('web.example.org') api = Api('web.example.org db.example.org') api = Api({'web.example.org': {'ansible_host': '10.10.5.1'}}) api = Api(['example.org:2222', 'example.org:2223'])
ignore_unreachable – If true, unreachable servers will not trigger an exception. They are however still taken out of the list for the lifetime of the object.
ignore_errors – If true, errors on servers will not trigger an exception. Servers who trigger an error are still ignored for the lifteime of the object.
sudo –
If true, the commands run as root using sudo. This is a shortcut for the following:
Api('example.org', become=True, become_user='root')
If
becomeorbecome_userare passed, this option is ignored!sudo_pass – If given, sudo is invoked with the given password. Alternatively you can use Ansible’s builtin password option (e.g.
passwords={'become_pass': '***'}).remote_pass –
Passwords are passed to ansible using the passwords dictionary by default (e.g.
passwords={'conn_pass': '****'}). Since this is a bit cumbersome and because earlier Suitable releases supported remote_pass this convenience argument exists.If passwords is passed, the remote_pass argument is ignored.
dry_run – Runs ansible in ‘check’ mode, where no changes are actually applied to the server(s).
verbosity –
The verbosity level of ansible. Possible values:
debuginfo(default)warnerrorcritical
environment –
The environment variables which should be set during when a module is executed. For example:
api = Api('example.org', environment={ 'PGPORT': '5432' })
strategy –
The Ansible strategy to use. Defaults to None which lets Ansible decide which strategy it wants to use.
Note that you need to globally install strategy plugins using
install_strategy_plugins()before using strategies provided by plugins.collections_path –
Provide a custom path or sequence of path to look for ansible collections when loading/hooking the modules.
Ansible only initializes the module loader once, so it’s not possible to have multiple
Apiinstances with different values for this parameter. The first one will always be the one that matters.Additionally if the loader has already been initialized prior to the creation of the
Apiinstance, then this parameter has no effect at all.Requires ansible-core >= 2.15
host_key_checking – Set to false to disable host key checking.
extra_vars –
Extra variables available to Ansible. Note that those will be global and not bound to any particular host:
api = Api('webserver', extra_vars={'home': '/home/denis'}) api.file(dest="{{ home }}/.zshrc", state='touch')
This can be used to specify an alternative Python interpreter:
api = Api('example.org', extra_vars={ 'ansible_python_interpreter': '/path/to/interpreter' })
**options –
All remining keyword arguments are passed to the Ansible TaskQueueManager. The available options are listed here:
- on_unreachable_host(module: str, host: str) object[source]
If you want to customize your error handling, this would be the point to write your own method in a subclass.
Note that this method is not called if ignore_unreachable is True.
If the return value of this method is ‘keep-trying’, the server will not be ignored for the lifetime of the object. This enables you to practically write your own flavor of ‘ignore_unreachable’.
If an any exception is raised the server WILL be ignored.
- on_module_error(module: str, host: str, result: ResultData) object[source]
If you want to customize your error handling, this would be the point to write your own method in a subclass.
Note that this method is not called if ignore_errors is True.
If the return value of this method is ‘keep-trying’, the server will not be ignored for the lifetime of the object. This enables you to practically write your own flavor of ‘ignore_errors’.
If an any exception is raised the server WILL be ignored.
- valid_return_codes(*codes: int) Generator[None, None, None][source]
Sets codes which are considered valid when returned from command modules. The default is (0, ).
Should be used as a context:
with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log')
- acl(*, path: StrPath, state: Literal['absent', 'present', 'query'] = 'query', follow: bool = True, default: bool = False, entity: str = '', etype: Literal['group', 'mask', 'other', 'user'] = ..., permissions: str = ..., entry: str = ..., recursive: bool = False, use_nfsv4_acls: bool = False, recalculate_mask: Literal['default', 'mask', 'no_mask'] = 'default') AclResults
Set and retrieve file ACL information.
See also
- Parameters:
path – The full path of the file or object.
state – Define whether the ACL should be present or not. The
querystate gets the current ACL without changing it, for use inregisteroperations.follow – Whether to follow symlinks on the path if a symlink is encountered.
default – If
pathis a directory, setting this totruewill make it the default ACL for entities created inside the directory. Settingdefault=truecauses an error ifpathis a file.entity – The actual user or group that the ACL applies to when matching entity types user or group are selected.
etype – The entity type of the ACL to apply, see
setfacldocumentation for more info.permissions – The permissions to apply/remove can be any combination of
r,w,x(read, write and execute respectively), andX(execute permission if the file is a directory or already has execute permission for some user).entry – DEPRECATED. The ACL to set or remove. This must always be quoted in the form of
<etype>:<qualifier>:<perms>. The qualifier may be empty for some types, but the type and perms are always required.-can be used as placeholder when you do not care about permissions. This is now superseded by entity, type and permissions fields.recursive – Recursively sets the specified ACL. Incompatible with
state=query. Aliasrecurseadded in version 1.3.0.use_nfsv4_acls – Use NFSv4 ACLs instead of POSIX ACLs. This feature uses
nfs4_setfaclandnfs4_getfacl. The behavior depends on those implementation. And currently it only supportsAin ACE, soDmust be replaced with the appropriateA. Permission is set as optimised ACLs by the system. You can check the actual ACLs that has been set using the return value. More infoman nfs4_setfacl.recalculate_mask – Select if and when to recalculate the effective right masks of the files. See
setfacldocumentation for more info. Incompatible withstate=query.
- add_host(*, name: str, groups: Sequence[str] = ...) AddHostResults
Add a host (and alternatively a group) to the ansible-playbook in-memory inventory.
See also
- Parameters:
name – The hostname/ip of the host to add to the inventory, can include a colon and a port number.
groups – The groups to add the hostname to.
- apt(*, name: Sequence[str] = ..., state: Literal['absent', 'build-dep', 'latest', 'present', 'fixed'] = 'present', update_cache: bool = ..., update_cache_retries: int = 5, update_cache_retry_max_delay: int = 12, cache_valid_time: int = 0, purge: bool = False, default_release: str = ..., install_recommends: bool = ..., force: bool = False, clean: bool = False, allow_unauthenticated: bool = False, allow_downgrade: bool = False, allow_change_held_packages: bool = False, upgrade: Literal['dist', 'full', 'no', 'safe', 'yes'] = 'no', dpkg_options: str = 'force-confdef,force-confold', deb: StrPath = ..., autoremove: bool = False, autoclean: bool = False, policy_rc_d: int = ..., only_upgrade: bool = False, fail_on_autoremove: bool = False, force_apt_get: bool = False, lock_timeout: int = 60) AptResults
Manages apt-packages.
See also
- Parameters:
name – A list of package names, like
foo, or package specifier with version, likefoo=1.0orfoo>=1.0. Name wildcards (fnmatch) likeapt*and version wildcards likefoo=1.0*are also supported. Do not use single or double quotes around the version when referring to the package name with a specific version, such asfoo=1.0orfoo>=1.0.state – Indicates the desired package state.
latestensures that the latest version is installed.build-depensures the package build dependencies are installed.fixedattempt to correct a system with broken dependencies in place.update_cache – Run the equivalent of
apt-get updatebefore the operation. Can be run as part of the package installation or as a separate step. Default is not to update the cache.update_cache_retries – Amount of retries if the cache update fails. Also see
update_cache_retry_max_delay.update_cache_retry_max_delay – Use an exponential backoff delay for each retry (see
update_cache_retries) up to this max delay in seconds.cache_valid_time – Update the apt cache if it is older than the
cache_valid_time. This option is set in seconds. As of Ansible 2.4, if explicitly set, this setsupdate_cache=yes.purge – Will force purging of configuration files if
state=absentorautoremove=yes.default_release – Corresponds to the
-toption for apt and sets pin priorities.install_recommends – Corresponds to the
--no-install-recommendsoption forapt.trueinstalls recommended packages.falsedoes not install recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages are never installed.force – Corresponds to the
--force-yestoapt-getand impliesallow_unauthenticated=yesandallow_downgrade=yes. This option will disable checking both the packages’ signatures and the certificates of the web servers they are downloaded from. This option is not the equivalent of passing the-fflag toapt-geton the command line. This is a destructive operation with the potential to destroy your system, and it should almost never be used. Please also seeman apt-getfor more information.clean – Run the equivalent of
apt-get cleanto clear out the local repository of retrieved package files. It removes everything but the lock file from/var/cache/apt/archives/and/var/cache/apt/archives/partial/. Can be run as part of the package installation (clean runs before install) or as a separate step.allow_unauthenticated – Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup.
allow_unauthenticatedis only supported withstate:install/present.allow_downgrade – Corresponds to the
--allow-downgradesoption for apt. This option enables the named package and version to replace an already installed higher version of that package. Note that settingallow_downgrade=truecan make this module behave in a non-idempotent way. (The task could end up with a set of packages that does not match the complete list of specified packages to install).allow_downgradeis only supported byaptand will be ignored ifaptitudeis detected or specified.allow_change_held_packages – Allows changing the version of a package which is on the apt hold list.
upgrade – If yes or safe, performs an aptitude safe-upgrade. If full, performs an aptitude full-upgrade. If dist, performs an apt-get dist-upgrade. Note: This does not upgrade a specific package, use state=latest for that. Note: Since 2.4, apt-get is used as a fall-back if aptitude is not present.
dpkg_options – Add
dpkgoptions toaptcommand. Defaults to-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold". Options should be supplied as comma separated list.deb – Path to a .deb package on the remote machine. If
://in the path, ansible will attempt to download deb before installing. (Version added 2.1). Requires thexz-utilspackage to extract the control file of the deb package to install.autoremove – If
true, remove unused dependency packages for all module states exceptbuild-dep. It can also be used as the only option. Previous to version 2.4,autocleanwas also an alias forautoremove, now it is its own separate command. See documentation for further information.autoclean – If
true, cleans the local repository of retrieved package files that can no longer be downloaded.policy_rc_d – Force the exit code of
/usr/sbin/policy-rc.d. For example, ifpolicy_rc_d=101the installed package will not trigger a service start. If/usr/sbin/policy-rc.dalready exists, it is backed up and restored after the package installation. Ifnull, the/usr/sbin/policy-rc.dis not created/changed.only_upgrade – Only upgrade a package if it is already installed.
fail_on_autoremove – Corresponds to the
--no-removeoption forapt. Iftrue, it is ensured that no packages will be removed or the task will fail.fail_on_autoremoveis only supported withstateexceptabsent.fail_on_autoremoveis only supported byaptand will be ignored ifaptitudeis detected or specified.force_apt_get – Force usage of apt-get instead of aptitude.
lock_timeout – How many seconds will this action wait to acquire a lock on the apt db. Sometimes there is a transitory lock and this will retry at least until timeout is hit.
- apt_key(*, id: str = ..., data: str = ..., file: StrPath = ..., keyring: StrPath = ..., url: str = ..., keyserver: str = ..., state: Literal['absent', 'present'] = 'present', validate_certs: bool = True) AptKeyResults
Add or remove an apt key.
See also
- Parameters:
id – The identifier of the key. Including this allows check mode to correctly report the changed state. If specifying a subkey’s id be aware that apt-key does not understand how to remove keys via a subkey id. Specify the primary key’s id instead. This parameter is required when
stateis set toabsent.data – The keyfile contents to add to the keyring.
file – The path to a keyfile on the remote server to add to the keyring.
keyring – The full path to specific keyring file in
/etc/apt/trusted.gpg.d/.url – The URL to retrieve key from.
keyserver – The keyserver to retrieve key from.
state – Ensures that the key is present (added) or absent (revoked).
validate_certs – If
false, SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.
- apt_repository(*, repo: str, state: Literal['absent', 'present'] = 'present', mode: str = ..., update_cache: bool = True, update_cache_retries: int = 5, update_cache_retry_max_delay: int = 12, validate_certs: bool = True, filename: str = ..., codename: str = ..., install_python_apt: bool = True) AptRepositoryResults
Add and remove APT repositories.
See also
- Parameters:
repo – A source string for the repository.
state – A source string state.
mode – The octal mode for newly created files in
sources.list.d. Default is what system uses (probably 0644).update_cache – Run the equivalent of
apt-get updatewhen a change occurs. Cache updates are run after making changes.update_cache_retries – Amount of retries if the cache update fails. Also see
update_cache_retry_max_delay.update_cache_retry_max_delay – Use an exponential backoff delay for each retry (see
update_cache_retries) up to this max delay in seconds.validate_certs – If
false, SSL certificates for the target repo will not be validated. This should only be used on personally controlled sites using self-signed certificates.filename – Sets the name of the source list file in
sources.list.d. Defaults to a file name based on the repository source url. The.listextension will be automatically added.codename – Override the distribution codename to use for PPA repositories. Should usually only be set when working with a PPA on a non-Ubuntu target (for example, Debian or Mint).
install_python_apt – Whether to automatically try to install the Python apt library or not, if it is not already installed. Without this library, the module does not work. Runs
apt-get install python-aptfor Python 2, andapt-get install python3-aptfor Python 3. Only works with the system Python 2 or Python 3. If you are using a Python on the remote that is not the system Python, setinstall_python_apt=falseand ensure that the Python apt library for your Python version is installed some other way.
- assemble(*, src: StrPath, dest: StrPath, backup: bool = False, delimiter: str = ..., remote_src: bool = True, regexp: str = ..., ignore_hidden: bool = False, validate: str = ..., decrypt: bool = True, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) AssembleResults
Assemble configuration files from fragments.
See also
- Parameters:
src – An already existing directory full of source files.
dest – A file to create using the concatenation of all of the source files.
backup – Create a backup file (if
true), including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.delimiter – A delimiter to separate the file contents.
remote_src – If
false, it will search for src at originating/master machine. Iftrue, it will go to the remote/target machine for the src.regexp – Assemble files only if the given regular expression matches the filename. If not set, all files are assembled. Every
\(backslash) must be escaped as\\to comply to YAML syntax. Uses Python regular expressions.ignore_hidden – A boolean that controls if files that start with a
.will be included or not.validate – The validation command to run before copying into place. The path to the file to validate is passed in by
%swhich must be present as in the sshd example below. The command is passed securely so shell features like expansion and pipes won’t work.decrypt – This option controls the auto-decryption of source files using vault.
mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- assert_(*, that: Sequence[str], fail_msg: str = ..., success_msg: str = ..., quiet: bool = False) AssertResults
Asserts given expressions are true.
See also
- Parameters:
that – A list of string expressions of the same form that can be passed to the
whenstatement.fail_msg – The customized message used for a failing assertion. This argument was called
msgbefore Ansible 2.7, now it is renamed tofail_msgwith aliasmsg.success_msg – The customized message used for a successful assertion.
quiet – Set this to
trueto avoid verbose output.
- async_status(*, jid: str, mode: Literal['cleanup', 'status'] = 'status') AsyncStatusResults
Obtain status of asynchronous task.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
jid – Job or task identifier.
mode – If
status, obtain the status. Ifcleanup, clean up the async job cache (by default in~/.ansible_async/) for the specified jobjid, without waiting for it to finish.
- at(*, command: str = ..., script_file: str = ..., count: int = ..., units: Literal['minutes', 'hours', 'days', 'weeks'] = ..., state: Literal['absent', 'present'] = 'present', unique: bool = False) AtResults
Schedule the execution of a command or script file via the at command.
See also
- Parameters:
command – A command to be executed in the future.
script_file – An existing script file to be executed in the future.
count – The count of units in the future to execute the command or script file.
units – The type of units in the future to execute the command or script file.
state – The state dictates if the command or script file should be evaluated as
present(added) orabsent(deleted).unique – If a matching job is present a new job will not be added.
- authorized_key(*, user: str, key: str, path: StrPath = ..., manage_dir: bool = True, state: Literal['absent', 'present'] = 'present', key_options: str = ..., exclusive: bool = False, validate_certs: bool = True, comment: str = ..., follow: bool = False) AuthorizedKeyResults
Adds or removes an SSH authorized key.
See also
- Parameters:
user – The username on the remote host whose authorized_keys file will be modified.
key – The SSH public key(s), as a string or (since Ansible 1.9) url (https://github.com/username.keys).
path – Alternative path to the authorized_keys file. The default value is the
.ssh/authorized_keysof the home of the user specified in theuserparameter. Most of the time, it is not necessary to set this key. Use the path to your target authorized_keys if you need to explicitly point on it.manage_dir – Whether this module should manage the directory of the authorized key file. If set to
true, the module will create the directory, as well as set the owner and permissions of an existing directory. Be sure to setmanage_dir=falseif you are using an alternate directory for authorized_keys, as set withpath, since you could lock yourself out of SSH access. See the example below.state – Whether the given key (with the given key_options) should or should not be in the file.
key_options – A string of ssh key options to be prepended to the key in the authorized_keys file.
exclusive – Whether to remove all other non-specified keys from the authorized_keys file. Multiple keys can be specified in a single
keystring value by separating them by newlines. This option is not loop aware, so if you usewith_, it will be exclusive per iteration of the loop. If you want multiple keys in the file you need to pass them all tokeyin a single batch as mentioned above.validate_certs – This only applies if using a https url as the source of the keys. If set to
false, the SSL certificates will not be validated. This should only set tofalseused on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set totrue.comment – Change the comment on the public key. Rewriting the comment is useful in cases such as fetching it from GitHub or GitLab. If no comment is specified, the existing comment will be kept.
follow – Follow path symlink instead of replacing it.
- blockinfile(*, path: StrPath, state: Literal['absent', 'present'] = 'present', marker: str = ..., block: str = '', insertafter: str = ..., insertbefore: str = ..., create: bool = False, backup: bool = False, marker_begin: str = 'BEGIN', marker_end: str = 'END', append_newline: bool = False, prepend_newline: bool = False, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ..., validate: str = ...) BlockinfileResults
Insert/update/remove a text block surrounded by marker lines.
See also
- Parameters:
path – The file to modify. Before Ansible 2.3 this option was only usable as
dest,destfileandname.state – Whether the block should be there or not.
marker – The marker line template.
{mark}will be replaced with the values inmarker_begin(default=``BEGIN``) andmarker_end(default=``END``). Using a custom marker without the{mark}variable may result in the block being repeatedly inserted on subsequent playbook runs. Multi-line markers are not supported and will result in the block being repeatedly inserted on subsequent playbook runs. A newline is automatically appended by the module tomarker_beginandmarker_end.block – The text to insert inside the marker lines. If it is missing or an empty string, the block will be removed as if
statewere specified toabsent.insertafter – If specified and no begin/ending
markerlines are found, the block will be inserted after the last match of specified regular expression. A special value is available;EOFfor inserting the block at the end of the file. If specified regular expression has no matches or no value is passed,EOFwill be used instead. The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. This behaviour was added in ansible-core 2.14.insertbefore – If specified and no begin/ending
markerlines are found, the block will be inserted before the last match of specified regular expression. A special value is available;BOFfor inserting the block at the beginning of the file. If specified regular expression has no matches, the block will be inserted at the end of the file. The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. This behaviour was added in ansible-core 2.14.create – Create a new file if it does not exist.
backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
marker_begin – This will be inserted at
{mark}in the opening ansible blockmarker.marker_end – This will be inserted at
{mark}in the closing ansible blockmarker.append_newline – Append a blank line to the inserted block, if this does not appear at the end of the file. Note that this attribute is not considered when
stateis set toabsent. Requires ansible-core >= 2.16prepend_newline – Prepend a blank line to the inserted block, if this does not appear at the beginning of the file. Note that this attribute is not considered when
stateis set toabsent. Requires ansible-core >= 2.16mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.validate – The validation command to run before copying the updated file into the final destination. A temporary file path is used to validate, passed in through
%swhich must be present as in the examples below. Also, the command is passed securely so shell features such as expansion and pipes will not work. For an example on how to handle more complex validation than what this option provides, seehandling complex validation.
- cli_backup(*, defaults: bool = False, filename: str = ..., dir_path: StrPath = ...) CliBackupResults
Back up device configuration from network devices over network_cli.
See also
- Parameters:
defaults – The defaults argument will influence how the running-config is collected from the device. When the value is set to true, the command used to collect the running-config is append with the all keyword. When the value is set to false, the command is issued without the all keyword.
filename – The filename to be used to store the backup configuration. If the filename is not given it will be generated based on the hostname, current time and date in format defined by <hostname>_config.<current-date>@<current-time>.
dir_path – This option provides the path ending with directory name in which the backup configuration file will be stored. If the directory does not exist it will be first created and the filename is either the value of
filenameor default filename as described infilenameoptions description. If the path value is not given in that case a backup directory will be created in the current working directory and backup configuration will be copied infilenamewithin backup directory.
- cli_command(*, command: str, prompt: Sequence[str] = ..., answer: Sequence[str] = ..., sendonly: bool = False, newline: bool = True, check_all: bool = False) CliCommandResults
Run a cli command on cli-based network devices.
See also
- Parameters:
command – The command to send to the remote network device. The resulting output from the command is returned, unless sendonly is set.
prompt – A single regex pattern or a sequence of patterns to evaluate the expected prompt from command.
answer – The answer to reply with if prompt is matched. The value can be a single answer or a list of answer for multiple prompts. In case the command execution results in multiple prompts the sequence of the prompt and excepted answer should be in same order.
sendonly – The boolean value, that when set to true will send command to the device but not wait for a result.
newline – The boolean value, that when set to false will send answer to the device without a trailing newline.
check_all – By default if any one of the prompts mentioned in
promptoption is matched it won’t check for other prompts. This boolean flag, that when set to True will check for all the prompts mentioned inpromptoption in the given order. If the option is set to True all the prompts should be received from remote host if not it will result in timeout.
- cli_config(*, config: str = ..., commit: bool = ..., replace: str = ..., backup: bool = False, rollback: int = ..., commit_comment: str = ..., defaults: bool = False, multiline_delimiter: str = ..., diff_replace: Literal['line', 'block', 'config'] = ..., diff_match: Literal['line', 'strict', 'exact', 'none'] = ..., diff_ignore_lines: Sequence[str] = ..., backup_options: Mapping[str, Incomplete] = ...) CliConfigResults
Push text based configuration to network devices over network_cli.
See also
- Parameters:
config – The config to be pushed to the network device. This argument is mutually exclusive with
rollbackand either one of the option should be given as input. To ensure idempotency and correct diff the configuration lines should be similar to how they appear if present in the running configuration on device including the indentation.commit – The
commitargument instructs the module to push the configuration to the device. This is mapped to module check mode.replace – If the
replaceargument is set toTrue, it will replace the entire running-config of the device with theconfigargument value. For devices that support replacing running configuration from file on device like NXOS/JUNOS, thereplaceargument takes path to the file on the device that will be used for replacing the entire running-config. The value ofconfigoption should be None for such devices. Nexus 9K devices only support replace. Use net_put or nxos_file_copy in case of NXOS module to copy the flat file to remote device and then use set the fullpath to this argument.backup – This argument will cause the module to create a full backup of the current running config from the remote device before any changes are made. If the
backup_optionsvalue is not given, the backup file is written to thebackupfolder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.rollback – The
rollbackargument instructs the module to rollback the current configuration to the identifier specified in the argument. If the specified rollback identifier does not exist on the remote device, the module will fail. To rollback to the most recent commit, set therollbackargument to 0. This option is mutually exclusive withconfig.commit_comment – The
commit_commentargument specifies a text string to be used when committing the configuration. If thecommitargument is set to False, this argument is silently ignored. This argument is only valid for the platforms that support commit operation with comment.defaults – The defaults argument will influence how the running-config is collected from the device. When the value is set to true, the command used to collect the running-config is append with the all keyword. When the value is set to false, the command is issued without the all keyword.
multiline_delimiter – This argument is used when pushing a multiline configuration element to the device. It specifies the character to use as the delimiting character. This only applies to the configuration action.
diff_replace – Instructs the module on the way to perform the configuration on the device. If the
diff_replaceargument is set to line then the modified lines are pushed to the device in configuration mode. If the argument is set to block then the entire command block is pushed to the device in configuration mode if any line is not correct. Note that this parameter will be ignored if the platform has onbox diff support.diff_match – Instructs the module on the way to perform the matching of the set of commands against the current device config. If
diff_matchis set to line, commands are matched line by line. Ifdiff_matchis set to strict, command lines are matched with respect to position. Ifdiff_matchis set to exact, command lines must be an equal match. Finally, ifdiff_matchis set to none, the module will not attempt to compare the source configuration with the running configuration on the remote device. Note that this parameter will be ignored if the platform has onbox diff support.diff_ignore_lines – Use this argument to specify one or more lines that should be ignored during the diff. This is used for lines in the configuration that are automatically updated by the system. This argument takes a list of regular expressions or exact line matches. Note that this parameter will be ignored if the platform has onbox diff support.
backup_options – This is a dict object containing configurable options related to backup file path. The value of this option is read only when
backupis set to True, ifbackupis set to False this option will be silently ignored.
- cli_parse(*, command: str = ..., text: str = ..., parser: Mapping[str, Incomplete], set_fact: str = ...) CliParseResults
Parse cli output or text using a variety of parsers.
See also
- Parameters:
command – The command to run on the host.
text – Text to be parsed.
parser – Parser specific parameters.
set_fact – Set the resulting parsed data as a fact.
- cli_restore(*, filename: str = ..., path: str = ...) CliRestoreResults
Restore device configuration to network devices over network_cli.
See also
Note
Requires ansible >= 6.1.0
- Parameters:
filename – Filename of the backup file, present in the appliance where the restore operation is to be performed. Check appliance for the configuration backup file name.
path – The location in the target appliance where the file containing the backup exists. The path and the filename together create the input to the config replace command,. For an IOSXE appliance the path pattern is flash://<filename>.
- command(*, expand_argument_vars: bool = True, cmd: str = ..., argv: Sequence[str] = ..., creates: StrPath = ..., removes: StrPath = ..., chdir: StrPath = ..., stdin: str = ..., stdin_add_newline: bool = True, strip_empty_ends: bool = True) CommandResults
- command(arg: str, /) CommandResults
Execute commands on targets.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
expand_argument_vars – Expands the arguments that are variables, for example
$HOMEwill be expanded before being passed to the command to run. If a variable is not matched, it is left unchanged, unlike shell substitution which would remove it. Set tofalseto disable expansion and treat the value as a literal argument. Requires ansible-core >= 2.16cmd – The command to run.
argv – Passes the command as a list rather than a string. Use
argvto avoid quoting values that would otherwise be interpreted incorrectly (for example “user name”). Only the string (free form) or the list (argv) form can be provided, not both. One or the other must be provided.creates – A filename or (since 2.0) glob pattern. If a matching file already exists, this step will not be run. This is checked before
removesis checked.removes – A filename or (since 2.0) glob pattern. If a matching file exists, this step will be run. This is checked after
createsis checked.chdir – Change into this directory before running the command.
stdin – Set the stdin of the command directly to the specified value.
stdin_add_newline – If set to
true, append a newline to stdin data.strip_empty_ends – Strip empty lines from the end of stdout/stderr in result.
- copy(*, src: StrPath = ..., content: str = ..., dest: StrPath, backup: bool = False, force: bool = True, mode: str = ..., directory_mode: str = ..., remote_src: bool = False, follow: bool = False, local_follow: bool = True, checksum: str = ..., decrypt: bool = True, owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ..., validate: str = ...) CopyResults
Copy files to remote locations.
See also
- Parameters:
src – Local path to a file to copy to the remote server. This can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with
/, only inside contents of that directory are copied to destination. Otherwise, if it does not end with/, the directory itself with all contents is copied. This behavior is similar to thersynccommand line tool.content – When used instead of
src, sets the contents of a file directly to the specified value. Works only whendestis a file. Creates the file if it does not exist. For advanced formatting or ifcontentcontains a variable, use thetemplate()method.dest – Remote absolute path where the file should be copied to. If
srcis a directory, this must be a directory too. Ifdestis a non-existent path and if eitherdestends with/orsrcis a directory,destis created. Ifdestis a relative path, the starting directory is determined by the remote host. Ifsrcanddestare files, the parent directory ofdestis not created and the task fails if it does not already exist.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
force – Influence whether the remote file must always be replaced. If
true, the remote file will be replaced when contents are different than the source. Iffalse, the file will only be transferred if the destination does not exist.mode – The permissions of the destination file or directory. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must either add a leading zero so that Ansible’s YAML parser knows it is an octal number (like0644or01777) or quote it (like'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). As of Ansible 2.3, the mode may also be the special stringpreserve.preservemeans that the file will be given the same permissions as the source file. When doing a recursive copy, see alsodirectory_mode. Ifmodeis not specified and the destination file does not exist, the defaultumaskon the system will be used when setting the mode for the newly created file. Ifmodeis not specified and the destination file does exist, the mode of the existing file will be used. Specifyingmodeis the best way to ensure files are created with the correct permissions. See CVE-2020-1736 for further details.directory_mode – Set the access permissions of newly created directories to the given mode. Permissions on existing directories do not change. See
modefor the syntax of accepted values. The target system’s defaults determine permissions when this parameter is not set.remote_src – Influence whether
srcneeds to be transferred or already is present remotely. Iffalse, it will search forsrcon the controller node. Iftrue, it will search forsrcon the managed (remote) node.remote_srcsupports recursive copying as of version 2.8.remote_srconly works withmode=preserveas of version 2.6. Auto-decryption of files does not work whenremote_src=yes.follow – This flag indicates that filesystem links in the destination, if they exist, should be followed.
local_follow – This flag indicates that filesystem links in the source tree, if they exist, should be followed.
checksum – SHA1 checksum of the file being transferred. Used to validate that the copy of the file was successful. If this is not provided, ansible will use the local calculated checksum of the src file.
decrypt – This option controls the auto-decryption of source files using vault.
owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.validate – The validation command to run before copying the updated file into the final destination. A temporary file path is used to validate, passed in through
%swhich must be present as in the examples below. Also, the command is passed securely so shell features such as expansion and pipes will not work. For an example on how to handle more complex validation than what this option provides, seehandling complex validation.
- cron(*, name: str, user: str = ..., job: str = ..., state: Literal['absent', 'present'] = 'present', cron_file: StrPath = ..., backup: bool = False, minute: str = '*', hour: str = '*', day: str = '*', month: str = '*', weekday: str = '*', special_time: Literal['annually', 'daily', 'hourly', 'monthly', 'reboot', 'weekly', 'yearly'] = ..., disabled: bool = False, env: bool = False, insertafter: str = ..., insertbefore: str = ...) CronResults
Manage cron.d and crontab entries.
See also
- Parameters:
name – Description of a crontab entry or, if
envis set, the name of environment variable. This parameter is always required as of ansible-core 2.12.user – The specific user whose crontab should be modified. When unset, this parameter defaults to the current user.
job – The command to execute or, if
envis set, the value of environment variable. The command should not contain line breaks. Required ifstate=present.state – Whether to ensure the job or environment variable is present or absent.
cron_file – If specified, uses this file instead of an individual user’s crontab. The assumption is that this file is exclusively managed by the module, do not use if the file contains multiple entries, NEVER use for /etc/crontab. If this is a relative path, it is interpreted with respect to
/etc/cron.d. Many Linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens. Using this parameter requires you to specify theuseras well, unlessstate=absent. Either this parameter ornameis required.backup – If set, create a backup of the crontab before it is modified. The location of the backup is returned in the
ignore:backup_filevariable by this module.minute – Minute when the job should run (
0-59,*,*/2, and so on).hour – Hour when the job should run (
0-23,*,*/2, and so on).day – Day of the month the job should run (
1-31,*,*/2, and so on).month – Month of the year the job should run (
1-12,*,*/2, and so on).weekday – Day of the week that the job should run (
0-6for Sunday-Saturday,*, and so on).special_time – Special time specification nickname.
disabled – If the job should be disabled (commented out) in the crontab. Only has effect if
state=present.env – If set, manages a crontab’s environment variable. New variables are added on top of crontab.
nameandvalueparameters are the name and the value of environment variable.insertafter – Used with
state=presentandenv. If specified, the environment variable will be inserted after the declaration of specified environment variable.insertbefore – Used with
state=presentandenv. If specified, the environment variable will be inserted before the declaration of specified environment variable.
- deb822_repository(*, allow_downgrade_to_insecure: bool = ..., allow_insecure: bool = ..., allow_weak: bool = ..., architectures: Sequence[str] = ..., by_hash: bool = ..., check_date: bool = ..., check_valid_until: bool = ..., components: Sequence[str] = ..., date_max_future: int = ..., enabled: bool = ..., inrelease_path: str = ..., languages: Sequence[str] = ..., name: str, pdiffs: bool = ..., signed_by: str = ..., suites: Sequence[str] = ..., targets: Sequence[str] = ..., trusted: bool = ..., types: Sequence[str] = ..., uris: Sequence[str] = ..., mode: str = '0644', state: Literal['absent', 'present'] = 'present') Deb822RepositoryResults
Add and remove deb822 formatted repositories.
See also
Note
Requires ansible-core >= 2.15
- Parameters:
allow_downgrade_to_insecure – Allow downgrading a package that was previously authenticated but is no longer authenticated.
allow_insecure – Allow insecure repositories.
allow_weak – Allow repositories signed with a key using a weak digest algorithm.
architectures – Architectures to search within repository.
by_hash – Controls if APT should try to acquire indexes via a URI constructed from a hashsum of the expected file instead of using the well-known stable filename of the index.
check_date – Controls if APT should consider the machine’s time correct and hence perform time related checks, such as verifying that a Release file is not from the future.
check_valid_until – Controls if APT should try to detect replay attacks.
components – Components specify different sections of one distribution version present in a
Suite.date_max_future – Controls how far from the future a repository may be.
enabled – Tells APT whether the source is enabled or not.
inrelease_path – Determines the path to the
InReleasefile, relative to the normal position of anInReleasefile.languages – Defines which languages information such as translated package descriptions should be downloaded.
name – Name of the repo. Specifically used for
X-Repolib-Nameand in naming the repository and signing key files.pdiffs – Controls if APT should try to use
PDiffsto update old indexes instead of downloading the new indexes entirely.signed_by – Either a URL to a GPG key, absolute path to a keyring file, one or more fingerprints of keys either in the
trusted.gpgkeyring or in the keyrings in thetrusted.gpg.d/directory, or an ASCII armored GPG public key block.suites – Suite can specify an exact path in relation to the UR*s* provided, in which case the Components: must be omitted and suite must end with a slash (
/). Alternatively, it may take the form of a distribution version (for example a version codename likediscoorartful). If the suite does not specify a path, at least one component must be present.targets – Defines which download targets apt will try to acquire from this source.
trusted – Decides if a source is considered trusted or if warnings should be raised before, for example packages are installed from this source.
types – Which types of packages to look for from a given source; either binary
debor source codedeb-src.uris – The URIs must specify the base of the Debian distribution archive, from which APT finds the information it needs.
mode – The octal mode for newly created files in
sources.list.d.state – A source string state.
- debconf(*, name: str, question: str = ..., vtype: Literal['boolean', 'error', 'multiselect', 'note', 'password', 'seen', 'select', 'string', 'text', 'title'] = ..., value: str = ..., unseen: bool = False) DebconfResults
Configure a .deb package.
See also
- Parameters:
name – Name of package to configure.
question – A debconf configuration setting.
vtype – The type of the value supplied. It is highly recommended to add
no_log=Trueto task while specifyingvtype=password.seenwas added in Ansible 2.2. After Ansible 2.17, user can specifyvalueas a list, ifvtypeis set asmultiselect.value – Value to set the configuration to. After Ansible 2.17,
valueis of typeraw.unseen – Do not set
seenflag when pre-seeding.
- debug(*, msg: str = ..., var: str = ..., verbosity: int = 0) DebugResults
Print statements during execution.
See also
- Parameters:
msg – The customized message that is printed. If omitted, prints a generic message.
var – A variable name to debug. Mutually exclusive with the
msgoption. Be aware that this option already runs in Jinja2 context and has an implicit{{ }}wrapping, so you should not be using Jinja2 delimiters unless you are looking for double interpolation.verbosity – A number that controls when the debug is run, if you set to 3 it will only run debug when -vvv or above.
- dnf(*, use_backend: Literal['auto', 'yum', 'dnf', 'yum4', 'dnf4', 'dnf5'] = 'auto', name: Sequence[str] = ..., list: str = ..., state: Literal['absent', 'present', 'installed', 'removed', 'latest'] = ..., enablerepo: Sequence[str] = ..., disablerepo: Sequence[str] = ..., conf_file: str = ..., disable_gpg_check: bool = False, installroot: str = '/', releasever: str = ..., autoremove: bool = False, exclude: Sequence[str] = ..., skip_broken: bool = False, update_cache: bool = False, update_only: bool = False, security: bool = False, bugfix: bool = False, enable_plugin: Sequence[str] = ..., disable_plugin: Sequence[str] = ..., disable_excludes: str = ..., validate_certs: bool = True, sslverify: bool = True, allow_downgrade: bool = False, install_repoquery: bool = True, download_only: bool = False, lock_timeout: int = 30, install_weak_deps: bool = True, download_dir: str = ..., allowerasing: bool = False, nobest: bool = ..., best: bool = ..., cacheonly: bool = False) DnfResults
Manages packages with the dnf package manager.
See also
- Parameters:
use_backend – Backend module to use. Requires ansible-core >= 2.15
name – A package name or package specifier with version, like
name-1.0. When using state=latest, this can be ‘*’ which means run: dnf -y update. You can also pass a url or a local path to an rpm file. To operate on several packages this can accept a comma separated string of packages or a list of packages. Comparison operators for package version are valid here>,<,>=,<=. Example -name >= 1.0. Spaces around the operator are required. You can also pass an absolute path for a binary which is provided by the package to install. See examples for more information.list – Various (non-idempotent) commands for usage with
/usr/bin/ansibleand not playbooks. Usepackage_facts()instead of thelistargument as a best practice.state – Whether to install (
present,latest), or remove (absent) a package. Default isNone, however in effect the default action ispresentunless theautoremove=true, thenabsentis inferred.enablerepo –
Repoidof repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a “,”.disablerepo –
Repoidof repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a,.conf_file – The remote dnf configuration file to use for the transaction.
disable_gpg_check – Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if
state=presentorstate=latest. This setting affects packages installed from a repository as well as “local” packages installed from the filesystem or a URL.installroot – Specifies an alternative installroot, relative to which all packages will be installed.
releasever – Specifies an alternative release from which all packages will be installed.
autoremove – If
true, removes all “leaf” packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or whenstate=absent.exclude – Package name(s) to exclude when
state=present, or latest. This can be a list or a comma separated string.skip_broken – Skip all unavailable packages or packages with broken dependencies without raising an error. Equivalent to passing the
--skip-brokenoption.update_cache – Force dnf to check if cache is out of date and redownload if needed. Has an effect only if
state=presentorstate=latest.update_only – When using latest, only update installed packages. Do not install packages. Has an effect only if
state=presentorstate=latest.security – If set to
true, andstate=latestthen only installs updates that have been marked security related. Note that, similar todnf upgrade-minimal, this filter applies to dependencies as well.bugfix – If set to
true, andstate=latestthen only installs updates that have been marked bugfix related. Note that, similar todnf upgrade-minimal, this filter applies to dependencies as well.enable_plugin –
Pluginname to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.disable_plugin –
Pluginname to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.disable_excludes – Disable the excludes defined in DNF config files. If set to
all, disables all excludes. If set tomain, disable excludes defined in[main]indnf.conf. If set torepoid, disable excludes defined for given repo id.validate_certs – This only applies if using a https url as the source of the rpm. For example, for localinstall. If set to
false, the SSL certificates will not be validated. This should only set tofalseused on personally controlled sites using self-signed certificates as it avoids verifying the source site.sslverify – Disables SSL validation of the repository server for this transaction. This should be set to
falseif one of the configured repositories is using an untrusted or self-signed certificate.allow_downgrade – Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting
allow_downgrade=truecan make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction).install_repoquery – This is effectively a no-op in DNF as it is not needed with DNF. This option is deprecated and will be removed in ansible-core 2.20.
download_only – Only download the packages, do not install them.
lock_timeout – Amount of time to wait for the dnf lockfile to be freed.
install_weak_deps – Will also install all packages linked by a weak dependency relation.
download_dir – Specifies an alternate directory to store packages. Has an effect only if
download_onlyis specified.allowerasing – If
trueit allows erasing of installed packages to resolve dependencies.nobest – This is the opposite of the
bestoption kept for backwards compatibility. Since ansible-core 2.17 the default value is set by the operating system distribution.best – When set to
true, either use a package with the highest version available or fail. When set tofalse, if the latest version cannot be installed go with the lower version. Default is set by the operating system distribution. Requires ansible-core >= 2.17cacheonly – Tells dnf to run entirely from system cache; does not download or update metadata.
- dnf5(*, name: Sequence[str] = ..., list: str = ..., state: Literal['absent', 'present', 'installed', 'removed', 'latest'] = ..., enablerepo: Sequence[str] = ..., disablerepo: Sequence[str] = ..., conf_file: str = ..., disable_gpg_check: bool = False, installroot: str = '/', releasever: str = ..., autoremove: bool = False, exclude: Sequence[str] = ..., skip_broken: bool = False, update_cache: bool = False, update_only: bool = False, security: bool = False, bugfix: bool = False, enable_plugin: Sequence[str] = ..., disable_plugin: Sequence[str] = ..., disable_excludes: str = ..., validate_certs: bool = True, sslverify: bool = True, allow_downgrade: bool = False, install_repoquery: bool = True, download_only: bool = False, lock_timeout: int = 30, install_weak_deps: bool = True, download_dir: str = ..., allowerasing: bool = False, nobest: bool = ..., best: bool = ..., cacheonly: bool = False) Dnf5Results
Manages packages with the dnf5 package manager.
See also
Note
Requires ansible-core >= 2.15
- Parameters:
name – A package name or package specifier with version, like
name-1.0. When usingstate=latest, this can be*which means run:dnf -y update. You can also pass a url or a local path to an rpm file. To operate on several packages this can accept a comma separated string of packages or a list of packages. Comparison operators for package version are valid here>,<,>=,<=. Example -name >= 1.0. Spaces around the operator are required. You can also pass an absolute path for a binary which is provided by the package to install. See examples for more information.list – Various (non-idempotent) commands for usage with
/usr/bin/ansibleand not playbooks. Usepackage_facts()instead of thelistargument as a best practice.state – Whether to install (
present,latest), or remove (absent) a package. Default isNone, however in effect the default action ispresentunless theautoremove=true, thenabsentis inferred.enablerepo – Repoid of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a
,.disablerepo – Repoid of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a
,.conf_file – The remote dnf configuration file to use for the transaction.
disable_gpg_check – Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if
stateispresentorlatest. This setting affects packages installed from a repository as well as “local” packages installed from the filesystem or a URL.installroot – Specifies an alternative installroot, relative to which all packages will be installed.
releasever – Specifies an alternative release from which all packages will be installed.
autoremove – If
true, removes all “leaf” packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or whenstate=absent.exclude – Package name(s) to exclude when
state=presentorstate=latest. This can be a list or a comma separated string.skip_broken – Skip all unavailable packages or packages with broken dependencies without raising an error. Equivalent to passing the
--skip-brokenoption.update_cache – Force dnf to check if cache is out of date and redownload if needed. Has an effect only if
state=presentorstate=latest.update_only – When using latest, only update installed packages. Do not install packages. Has an effect only if
state=presentorstate=latest.security – If set to
true, andstate=latestthen only installs updates that have been marked security related. Note that, similar todnf upgrade-minimal, this filter applies to dependencies as well.bugfix – If set to
true, andstate=latestthen only installs updates that have been marked bugfix related. Note that, similar todnf upgrade-minimal, this filter applies to dependencies as well.enable_plugin – Plugin name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.
disable_plugintakes precedence in case a plugin is listed in bothenable_pluginanddisable_plugin. Requires python3-libdnf5 5.2.0.0+.disable_plugin – Plugin name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.
disable_plugintakes precedence in case a plugin is listed in bothenable_pluginanddisable_plugin. Requires python3-libdnf5 5.2.0.0+.disable_excludes – Disable the excludes defined in DNF config files. If set to
all, disables all excludes. If set tomain, disable excludes defined in[main]indnf.conf. If set torepoid, disable excludes defined for given repo id.validate_certs – This is effectively a no-op in the dnf5 module as dnf5 itself handles downloading a https url as the source of the rpm, but is an accepted parameter for feature parity/compatibility with the
dnf()method.sslverify – Disables SSL validation of the repository server for this transaction. This should be set to
falseif one of the configured repositories is using an untrusted or self-signed certificate.allow_downgrade – Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting
allow_downgrade=truecan make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction).install_repoquery – This is effectively a no-op in DNF as it is not needed with DNF. This option is deprecated and will be removed in ansible-core 2.20.
download_only – Only download the packages, do not install them.
lock_timeout – This is currently a no-op as dnf5 does not provide an option to configure it. Amount of time to wait for the dnf lockfile to be freed.
install_weak_deps – Will also install all packages linked by a weak dependency relation.
download_dir – Specifies an alternate directory to store packages. Has an effect only if
download_onlyis specified.allowerasing – If
trueit allows erasing of installed packages to resolve dependencies.nobest – This is the opposite of the
bestoption kept for backwards compatibility. Since ansible-core 2.17 the default value is set by the operating system distribution.best – When set to
true, either use a package with the highest version available or fail. When set tofalse, if the latest version cannot be installed go with the lower version. Default is set by the operating system distribution. Requires ansible-core >= 2.17cacheonly – Tells dnf to run entirely from system cache; does not download or update metadata.
- dpkg_selections(*, name: str, selection: Literal['install', 'hold', 'deinstall', 'purge']) DpkgSelectionsResults
Dpkg package selection selections.
See also
- Parameters:
name – Name of the package.
selection – The selection state to set the package to.
- expect(*, command: str, creates: StrPath = ..., removes: StrPath = ..., chdir: StrPath = ..., responses: Mapping[str, Incomplete], timeout: int | str = 30, echo: bool = False) ExpectResults
Executes a command and responds to prompts.
See also
- Parameters:
command – The command module takes command to run.
creates – A filename, when it already exists, this step will not be run.
removes – A filename, when it does not exist, this step will not be run.
chdir – Change into this directory before running the command.
responses – Mapping of prompt regular expressions and corresponding answer(s). Each key in
responsesis a Python regex regular-expression-syntax. The value of each key is a string or list of strings. If the value is a string and the prompt is encountered multiple times, the answer will be repeated. Provide the value as a list to give different answers for successive matches.timeout – Amount of time in seconds to wait for the expected strings. Use
nullto disable timeout.echo – Whether or not to echo out your response strings.
- fact_diff(*, before: str, after: str, plugin: Mapping[str, Incomplete] = ...) FactDiffResults
Find the difference between currently set facts.
See also
- Parameters:
before – The first fact to be used in the comparison.
after – The second fact to be used in the comparison.
plugin – Configure and specify the diff plugin to use.
- fail(*, msg: str = ...) FailResults
Fail with custom message.
See also
- Parameters:
msg – The customized message used for failing execution. If omitted, fail will simply bail out with a generic message.
- fetch(*, src: str, dest: str, fail_on_missing: bool = True, validate_checksum: bool = True, flat: bool = False) FetchResults
Fetch files from remote nodes.
See also
- Parameters:
src – The file on the remote system to fetch. This must be a file, not a directory. Recursive fetching may be supported in a later release.
dest – A directory to save the file into. For example, if
dest=/backup, thensrc=/etc/profileon hosthost.example.com, would save the file into/backup/host.example.com/etc/profile. The host name is based on the inventory name.fail_on_missing – When set to
true, the task will fail if the remote file cannot be read for any reason. Prior to Ansible 2.5, setting this would only fail if the source file was missing. The default was changed totruein Ansible 2.5.validate_checksum – Verify that the source and destination checksums match after the files are fetched.
flat – Allows you to override the default behavior of appending hostname/path/to/file to the destination. If
destends with ‘/’, it will use the basename of the source file, similar to the copy module. This can be useful if working with a single host, or if retrieving files that are uniquely named per host. If using multiple hosts with the same filename, the file will be overwritten for each host.
- file(*, path: StrPath, state: Literal['absent', 'directory', 'file', 'hard', 'link', 'touch'] = ..., src: StrPath = ..., recurse: bool = False, force: bool = False, follow: bool = True, modification_time: str = ..., modification_time_format: str = '%Y%m%d%H%M.%S', access_time: str = ..., access_time_format: str = '%Y%m%d%H%M.%S', mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) FileResults
Manage files and file properties.
See also
- Parameters:
path – Path to the file being managed.
state – If
absent, directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, ifdiffis declared, you will see the files and folders deleted listed underpath_contents. Note thatabsentwill not causefile()to fail if thepathdoes not exist as the state did not change. Ifdirectory, all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. Iffile, with no other options, returns the current state ofpath. Iffile, even with other options (such asmode), the file will be modified if it exists but will NOT be created if it does not exist. Set totouchor use thecopy()ortemplate()method if you want to create the file if it does not exist. Ifhard, the hard link will be created or changed. Iflink, the symbolic link will be created or changed. Iftouch(new in 1.4), an empty file will be created if the file does not exist, while an existing file or directory will receive updated file access and modification times (similar to the waytouchworks from the command line). Default is the current state of the file if it exists,directoryifrecurse=yes, orfileotherwise.src – Path of the file to link to. This applies only to
state=linkandstate=hard. Forstate=link, this will also accept a non-existing path. Relative paths are relative to the file being created (path) which is how the Unix commandln -s SRC DESTtreats relative paths.recurse – Recursively set the specified file attributes on directory contents. This applies only when
stateis set todirectory.force – Force the creation of the links in two cases: if the link type is symbolic and the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the
pathfile and create a link to thesrcfile in place of it).follow – This flag indicates that filesystem links, if they exist, should be followed.
follow=yesandstate=linkcan modifysrcwhen combined with parameters such asmode. Previous to Ansible 2.5, this wasfalseby default. While creating a symlink with a non-existent destination, setfollow=falseto avoid a warning message related to permission issues. The warning message is added to notify the user that we can not set permissions to the non-existent destination.modification_time – This parameter indicates the time the file’s modification time should be set to. Should be
preservewhen no modification is required,YYYYMMDDHHMM.SSwhen using default time format, ornow. Default is None meaning thatpreserveis the default forstate=[file,directory,link,hard]andnowis default forstate=touch.modification_time_format – When used with
modification_time, indicates the time format that must be used. Based on default Python format (see time.strftime doc).access_time – This parameter indicates the time the file’s access time should be set to. Should be
preservewhen no modification is required,YYYYMMDDHHMM.SSwhen using default time format, ornow. Default isNonemeaning thatpreserveis the default forstate=[file,directory,link,hard]andnowis default forstate=touch.access_time_format – When used with
access_time, indicates the time format that must be used. Based on default Python format (see time.strftime doc).mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- find(*, age: str = ..., patterns: Sequence[str] = ..., excludes: Sequence[str] = ..., contains: str = ..., read_whole_file: bool = False, paths: Sequence[StrPath], file_type: Literal['any', 'directory', 'file', 'link'] = 'file', recurse: bool = False, size: str = ..., age_stamp: Literal['atime', 'ctime', 'mtime'] = 'mtime', hidden: bool = False, mode: str = ..., exact_mode: bool = True, follow: bool = False, get_checksum: bool = False, use_regex: bool = False, depth: int = ..., encoding: str = ..., limit: int = ...) FindResults
Return a list of files based on specific criteria.
See also
- Parameters:
age – Select files whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (e.g., “1w”).
patterns – One or more (shell or regex) patterns, which type is controlled by
use_regexoption. The patterns restrict the list of files to be returned to those whose basenames match at least one of the patterns specified. Multiple patterns can be specified using a list. The pattern is matched against the file base name, excluding the directory. When using regexen, the pattern MUST match the ENTIRE file name, not just parts of it. So if you are looking to match all files ending in .default, you’d need to use.*\.defaultas a regexp and not just\.default. This parameter expects a list, which can be either comma separated or YAML. If any of the patterns contain a comma, make sure to put them in a list to avoid splitting the patterns in undesirable ways. Defaults to*whenuse_regex=False, or.*whenuse_regex=True.excludes – One or more (shell or regex) patterns, which type is controlled by
use_regexoption. Items whose basenames match anexcludespattern are culled frompatternsmatches. Multiple patterns can be specified using a list.contains – A regular expression or pattern which should be matched against the file content. If
read_whole_file=falseit matches against the beginning of the line (usesre.match(\)). Ifread_whole_file=true, it searches anywhere for that pattern (usesre.search(\)). Works only whenfile_typeisfile.read_whole_file – When doing a
containssearch, determines whether the whole file should be read into memory or if the regex should be applied to the file line-by-line. Setting this totruecan have performance and memory implications for large files. This usesre.search(\) instead ofre.match(\).paths – List of paths of directories to search. All paths must be fully qualified. From ansible-core 2.18 and onwards, the data type has changed from
strtopath.file_type – Type of file to select. The
linkandanychoices were added in Ansible 2.3.recurse – If target is a directory, recursively descend into the directory looking for files.
size – Select files whose size is equal to or greater than the specified size. Use a negative size to find files equal to or less than the specified size. Unqualified values are in bytes but b, k, m, g, and t can be appended to specify bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively. Size is not evaluated for directories.
age_stamp – Choose the file property against which we compare age.
hidden – Set this to
trueto include hidden files, otherwise they will be ignored.mode – Choose objects matching a specified permission. This value is restricted to modes that can be applied using the python
os.chmodfunction. The mode can be provided as an octal such as"0644"or as symbolic such asu=rw,g=r,o=r. Requires ansible-core >= 2.16exact_mode – Restrict mode matching to exact matches only, and not as a minimum set of permissions to match. Requires ansible-core >= 2.16
follow – Set this to
trueto follow symlinks in path for systems with python 2.6+.get_checksum – Set this to
trueto retrieve a file’s SHA1 checksum.use_regex – If
false, the patterns are file globs (shell). Iftrue, they are python regexes.depth – Set the maximum number of levels to descend into. Setting
recurse=falsewill override this value, which is effectively depth 1. Default is unlimited depth.encoding – When doing a
containssearch, determine the encoding of the files to be searched. Requires ansible-core >= 2.17limit – Limit the maximum number of matching paths returned. After finding this many, the find action will stop looking. Matches are made from the top, down (i.e. shallowest directory first). If not set, or set to v(null), it will do unlimited matches. Default is unlimited matches. Requires ansible-core >= 2.18
- firewalld(*, service: str = ..., protocol: str = ..., port: str = ..., port_forward: Sequence[Mapping[str, Incomplete]] = ..., rich_rule: str = ..., source: str = ..., interface: str = ..., icmp_block: str = ..., icmp_block_inversion: str = ..., zone: str = ..., permanent: bool = False, immediate: bool = False, state: Literal['absent', 'disabled', 'enabled', 'present'], timeout: int = 0, forward: str = ..., masquerade: str = ..., offline: bool = False, target: Literal['default', 'ACCEPT', 'DROP', '%%REJECT%%'] = ...) FirewalldResults
Manage arbitrary ports/services with firewalld.
See also
- Parameters:
service – Name of a service to add/remove to/from firewalld. The service must be listed in output of
firewall-cmd --get-services.protocol – Name of a protocol to add/remove to/from firewalld.
port – Name of a port or port range to add/remove to/from firewalld. Must be in the form PORT/PROTOCOL or PORT-PORT/PROTOCOL for port ranges.
port_forward – Port and protocol to forward using firewalld.
rich_rule – Rich rule to add/remove to/from firewalld. See Syntax for firewalld rich language rules.
source – The source/network you would like to add/remove to/from firewalld.
interface – The interface you would like to add/remove to/from a zone in firewalld.
icmp_block – The ICMP block you would like to add/remove to/from a zone in firewalld.
icmp_block_inversion – Enable/Disable inversion of ICMP blocks for a zone in firewalld.
zone – The firewalld zone to add/remove to/from. Note that the default zone can be configured per system but
publicis default from upstream. Available choices can be extended based on per-system configs, listed here are “out of the box” defaults. Possible values includeblock,dmz,drop,external,home,internal,public,trusted,work.permanent – Whether to apply this change to the permanent firewalld configuration. As of Ansible 2.3, permanent operations can operate on firewalld configs when it is not running (requires firewalld >= 0.3.9). Note that if this is
false,immediate=trueby default.immediate – Whether to apply this change to the runtime firewalld configuration. Defaults to
trueifpermanent=false.state – Enable or disable a setting. For ports: Should this port accept (
enabled) or reject (disabled) connections. The statespresentandabsentcan only be used in zone level operations (i.e. when no other parameters but zone and state are set).timeout – The amount of time in seconds the rule should be in effect for when non-permanent.
forward – The forward setting you would like to enable/disable to/from zones within firewalld. This option only is supported by firewalld v0.9.0 or later.
masquerade – The masquerade setting you would like to enable/disable to/from zones within firewalld.
offline – Ignores
immediateifpermanent=trueand firewalld is not running.target – firewalld Zone target. If
state=absent, this will reset the target to default.
- firewalld_info(*, active_zones: bool = False, zones: Sequence[str] = ...) FirewalldInfoResults
Gather information about firewalld.
See also
- Parameters:
active_zones – Gather information about active zones.
zones – Gather information about specific zones. If only works if
active_zones=false.
- gather_facts(*, parallel: bool = ...) GatherFactsResults
Gathers facts about remote hosts.
See also
- Parameters:
parallel – A toggle that controls if the fact modules are executed in parallel or serially and in order. This can guarantee the merge order of module facts at the expense of performance. By default it will be true if more than one fact module is used. For low cost/delay fact modules parallelism overhead might end up meaning the whole process takes longer. Test your specific case to see if it is a speed improvement or not. The
ansible_facts_parallelvariable can be used to set this option, overriding the default, but not the direct assignment of the option in the task.
- get_url(*, ciphers: Sequence[str] = ..., decompress: bool = True, url: str, dest: StrPath, tmp_dest: StrPath = ..., force: bool = False, backup: bool = False, checksum: str = '', use_proxy: bool = True, validate_certs: bool = True, timeout: int = 10, headers: Mapping[str, Incomplete] = ..., url_username: str = ..., url_password: str = ..., force_basic_auth: bool = False, client_cert: StrPath = ..., client_key: StrPath = ..., http_agent: str = 'ansible-httpget', unredirected_headers: Sequence[str] = ..., use_gssapi: bool = False, use_netrc: bool = True, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) GetUrlResults
Downloads files from HTTP, HTTPS, or FTP to node.
See also
- Parameters:
ciphers – SSL/TLS Ciphers to use for the request. When a list is provided, all ciphers are joined in order with
:. See the OpenSSL Cipher List Format for more details. The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions. Requires ansible-core >= 2.14decompress – Whether to attempt to decompress gzip content-encoded responses. Requires ansible-core >= 2.14
url – HTTP, HTTPS, or FTP URL in the form
(http|https|ftp://[user[:pass]]@host.domain[:port]/path).dest – Absolute path of where to download the file to. If
destis a directory, either the server provided filename or, if none provided, the base name of the URL on the remote server will be used. If a directory,forcehas no effect. Ifdestis a directory, the file will always be downloaded (regardless of theforceandchecksumoption), but replaced only if the contents changed.tmp_dest – Absolute path of where temporary file is downloaded to. When run on Ansible 2.5 or greater, path defaults to ansible’s
remote_tmpsetting. When run on Ansible prior to 2.5, it defaults toTMPDIR,TEMPorTMPenv variables or a platform specific value. tempfile.tempdir.force – If
trueanddestis not a directory, will download the file every time and replace the file if the contents change. Iffalse, the file will only be downloaded if the destination does not exist. Generally should betrueonly for small local files. Prior to 0.6, this module behaved as iftruewas the default.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
checksum – If a checksum is passed to this parameter, the digest of the destination file will be calculated after it is downloaded to ensure its integrity and verify that the transfer completed successfully. Format: <algorithm>:<checksum|url>, for example
checksum="sha256:D98291AC[...]B6DC7B97", C(checksum="sha256:http://example.com/path/sha256sum.txt". If you worry about portability, only the sha1 algorithm is available on all platforms and python versions. The Pythonhashlibmodule is responsible for providing the available algorithms. The choices vary based on Python version and OpenSSL version. On systems running in FIPS compliant mode, themd5algorithm may be unavailable. Additionally, if a checksum is passed to this parameter, and the file exist under thedestlocation, thedestination_checksumwould be calculated, and if checksum equalsdestination_checksum, the file download would be skipped (unlessforce=true). If the checksum does not equaldestination_checksum, the destination file is deleted. If the checksum URL requires username and password,url_usernameandurl_passwordare used to download the checksum file.use_proxy – if
false, it will not use a proxy, even if one is defined in an environment variable on the target hosts.validate_certs – If
false, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.timeout – Timeout in seconds for URL request.
headers – Add custom HTTP headers to a request in hash/dict format. The hash/dict format was added in Ansible 2.6. Previous versions used a
"key:value,key:value"string format. The"key:value,key:value"string format is deprecated and has been removed in version 2.10.url_username – The username for use in HTTP basic authentication. This parameter can be used without
url_passwordfor sites that allow empty passwords. Since version 2.8 you can also use theusernamealias for this option.url_password – The password for use in HTTP basic authentication. If the
url_usernameparameter is not specified, theurl_passwordparameter will not be used. Since version 2.8 you can also use thepasswordalias for this option.force_basic_auth – Force the sending of the Basic authentication header upon initial request. httplib2, the library used by the uri module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail.
client_cert – PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key as well, and if the key is included,
client_keyis not required.client_key – PEM formatted file that contains your private key to be used for SSL client authentication. If
client_certcontains both the certificate and key, this option is not required.http_agent – Header to identify as, generally appears in web server logs.
unredirected_headers – A list of header names that will not be sent on subsequent redirected requests. This list is case insensitive. By default all headers will be redirected. In some cases it may be beneficial to list headers such as
Authorizationhere to avoid potential credential exposure.use_gssapi – Use GSSAPI to perform the authentication, typically this is for Kerberos or Kerberos through Negotiate authentication. Requires the Python library gssapi to be installed. Credentials for GSSAPI can be specified with
url_username/url_passwordor with the GSSAPI env varKRB5CCNAMEthat specified a custom Kerberos credential cache. NTLM authentication is not supported even if the GSSAPI mech for NTLM has been installed.use_netrc – Determining whether to use credentials from
~/.netrcfile. By default.netrcis used with Basic authentication headers. Whenfalse,.netrccredentials are ignored. Requires ansible-core >= 2.14mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- getent(*, database: str, key: str = ..., service: str = ..., split: str = ..., fail_key: bool = True) GetentResults
A wrapper to the unix getent utility.
See also
- Parameters:
database – The name of a getent database supported by the target system (passwd, group, hosts, etc).
key – Key from which to return values from the specified database, otherwise the full contents are returned.
service – Override all databases with the specified service. The underlying system must support the service flag which is not always available.
split – Character used to split the database values into lists/arrays such as
:or\t, otherwise it will try to pick one depending on the database.fail_key – If a supplied key is missing this will make the task fail if
true.
- git(*, repo: str, dest: StrPath, version: str = 'HEAD', accept_hostkey: bool = False, accept_newhostkey: bool = False, ssh_opts: str = ..., key_file: StrPath = ..., reference: str = ..., remote: str = 'origin', refspec: str = ..., force: bool = False, depth: int = ..., clone: bool = True, update: bool = True, executable: StrPath = ..., bare: bool = False, umask: str = ..., recursive: bool = True, single_branch: bool = False, track_submodules: bool = False, verify_commit: bool = False, archive: StrPath = ..., archive_prefix: str = ..., separate_git_dir: StrPath = ..., gpg_allowlist: Sequence[str] = ...) GitResults
Deploy software (or files) from git checkouts.
See also
- Parameters:
repo – git, SSH, or HTT``S`` protocol address of the git repository.
dest – The path of where the repository should be checked out. This is equivalent to
git clone [repo_url] [directory]. The repository named inrepois not appended to this path and the destination directory must be empty. This parameter is required, unlesscloneis set tofalse.version – What version of the repository to check out. This can be the literal string
HEAD, a branch name, a tag name. It can also be a SHA-1 hash, in which caserefspecneeds to be specified if the given revision is not already available.accept_hostkey – Will ensure or not that
-o StrictHostKeyChecking=nois present as an ssh option. Be aware that this disables a protection against MITM attacks. Those using OpenSSH >= 7.5 might want to useaccept_newhostkeyor setssh_optstoStrictHostKeyChecking=accept-newinstead, it does not remove the MITM issue but it does restrict it to the first attempt.accept_newhostkey – As of OpenSSH 7.5,
-o StrictHostKeyChecking=accept-newcan be used which is safer and will only accepts host keys which are not present or are the same. Iftrue, ensure that-o StrictHostKeyChecking=accept-newis present as an ssh option.ssh_opts – Options git will pass to ssh when used as protocol, it works via
git’sGIT_SSH/GIT_SSH_COMMANDenvironment variables. For older versions it appendsGIT_SSH_OPTS(specific to this module) to the variables above or via a wrapper script. Other options can add to this list, likekey_fileandaccept_hostkey. An example value could be-o StrictHostKeyChecking=no(although this particular option is better set byaccept_hostkey). The module ensures thatBatchMode=yesis always present to avoid prompts.key_file – Specify an optional private key file path, on the target host, to use for the checkout. This ensures
IdentitiesOnly=yesis present inssh_opts.reference – Reference repository (see
git clone --reference ...).remote – Name of the remote.
refspec – Add an additional refspec to be fetched. If version is set to a SHA-1 not reachable from any branch or tag, this option may be necessary to specify the ref containing the SHA-1. Uses the same syntax as the
git fetchcommand. An example value could be “refs/meta/config”.force – If
true, any modified files in the working repository will be discarded. Prior to 0.7, this was alwaystrueand could not be disabled. Prior to 1.9, the default wastrue.depth – Create a shallow clone with a history truncated to the specified number or revisions. The minimum possible value is
1, otherwise ignored. Needs git>=1.9.1 to work correctly.clone – If
false, do not clone the repository even if it does not exist locally.update – If
false, do not retrieve new revisions from the origin repository. Operations like archive will work on the existing (old) repository and might not respond to changes to the options version or remote.executable – Path to git executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.
bare – If
true, repository will be created as a bare repo, otherwise it will be a standard repo with a workspace.umask – The umask to set before doing any checkouts, or any other repository maintenance.
recursive – If
false, repository will be cloned without the--recursiveoption, skipping sub-modules.single_branch – Clone only the history leading to the tip of the specified revision.
track_submodules – If
true, submodules will track the latest commit on their master branch (or other branch specified in.gitmodules). Iffalse, submodules will be kept at the revision specified by the main project. This is equivalent to specifying the--remoteflag to git submodule update.verify_commit – If
true, when cloning or checking out aversionverify the signature of a GPG signed commit. This requires git version>=2.1.0 to be installed. The commit MUST be signed and the public key MUST be present in the GPG keyring.archive – Specify archive file path with extension. If specified, creates an archive file of the specified format containing the tree structure for the source tree. Allowed archive formats [“zip”, “tar.gz”, “tar”, “tgz”]. This will clone and perform git archive from local directory as not all git servers support git archive.
archive_prefix – Specify a prefix to add to each file path in archive. Requires
archiveto be specified.separate_git_dir – The path to place the cloned repository. If specified, Git repository can be separated from working tree.
gpg_allowlist – A list of trusted GPG fingerprints to compare to the fingerprint of the GPG-signed commit. Only used when
verify_commit=yes. Use of this feature requires Git 2.6+ due to its reliance on git’s--rawflag toverify-commitandverify-tag. Aliasgpg_allowlistis added in version 2.17. Aliasgpg_whitelistis deprecated and will be removed in version 2.21.
- group(*, name: str, gid: int = ..., state: Literal['absent', 'present'] = 'present', force: bool = False, system: bool = False, local: bool = False, non_unique: bool = False, gid_min: int = ..., gid_max: int = ...) GroupResults
Add or remove groups.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – Name of the group to manage.
gid – Optional GID to set for the group.
state – Whether the group should be present or not on the remote host.
force – Whether to delete a group even if it is the primary group of a user. Only applicable on platforms which implement a
--forceflag on the group deletion command. Requires ansible-core >= 2.15system – If
True, indicates that the group created is a system group.local – Forces the use of “local” command alternatives on platforms that implement it. This is useful in environments that use centralized authentication when you want to manipulate the local groups. (for example, it uses
lgroupaddinstead ofgroupadd). This requires that these commands exist on the targeted host, otherwise it will be a fatal error.non_unique – This option allows to change the group ID to a non-unique value. Requires
gid. Not supported on macOS or BusyBox distributions.gid_min – Sets the GID_MIN value for group creation. Overwrites /etc/login.defs default value. Currently supported on Linux. Does nothing when used with other platforms. Requires
localis omitted orFalse. Requires ansible-core >= 2.18gid_max – Sets the GID_MAX value for group creation. Overwrites /etc/login.defs default value. Currently supported on Linux. Does nothing when used with other platforms. Requires
localis omitted orFalse. Requires ansible-core >= 2.18
- group_by(*, key: str, parents: Sequence[str] = ...) GroupByResults
Create Ansible groups based on facts.
See also
- Parameters:
key – The variables whose values will be used as groups.
parents – The list of the parent groups.
- grpc_config(*, config: str = ..., state: str = ..., backup: bool = False, backup_options: Mapping[str, Incomplete] = ...) GrpcConfigResults
Fetch configuration/state data from gRPC enabled target hosts.
See also
- Parameters:
config – This option specifies the string which acts as a filter to restrict the portions of the data to be retrieved from the target host device. If this option is not specified the entire configuration or state data is returned in response provided it is supported by target host.
state – action to be performed.
backup – This argument will cause the module to create a full backup of the current
running-configfrom the remote device before any changes are made. If thebackup_optionsvalue is not given, the backup file is written to thebackupfolder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.backup_options – This is a dict object containing configurable options related to backup file path. The value of this option is read only when
backupis set to True, ifbackupis set to False this option will be silently ignored.
- grpc_get(*, section: str = ..., command: str = ..., display: str = ..., data_type: str = ...) GrpcGetResults
Fetch configuration/state data from gRPC enabled target hosts.
See also
- Parameters:
section – This option specifies the string which acts as a filter to restrict the portions of the data to be retrieved from the target host device. If this option is not specified the entire configuration or state data is returned in response provided it is supported by target host.
command – The option specifies the command to be executed on the target host and return the response in result. This option is supported if the gRPC target host supports executing CLI command over the gRPC connection.
display – Encoding scheme to use when serializing output from the device. The encoding scheme value depends on the capability of the gRPC server running on the target host. The values can be json, text etc.
data_type – The type of data that should be fetched from the target host. The value depends on the capability of the gRPC server running on target host. The values can be config, oper etc. based on what is supported by the gRPC server. By default it will return both configuration and operational state data in response.
- hostname(*, name: str, use: Literal['alpine', 'debian', 'freebsd', 'generic', 'macos', 'macosx', 'darwin', 'openbsd', 'openrc', 'redhat', 'sles', 'solaris', 'systemd'] = ...) HostnameResults
Manage hostname.
See also
- Parameters:
name – Name of the host. If the value is a fully qualified domain name that does not resolve from the given host, this will cause the module to hang for a few seconds while waiting for the name resolution attempt to timeout.
use – Which strategy to use to update the hostname. If not set we try to autodetect, but this can be problematic, particularly with containers as they can present misleading information. Note that
systemdshould be specified for RHEL/EL/CentOS 7+. Older distributions should useredhat.
- import_role(*, name: str, tasks_from: str = 'main', vars_from: str = 'main', defaults_from: str = 'main', allow_duplicates: bool = True, handlers_from: str = 'main', rolespec_validate: bool = True, public: bool = True) ImportRoleResults
Import a role into a play.
See also
- Parameters:
name – The name of the role to be executed.
tasks_from – File to load from a role’s
tasks/directory.vars_from – File to load from a role’s
vars/directory.defaults_from – File to load from a role’s
defaults/directory.allow_duplicates – Overrides the role’s metadata setting to allow using a role more than once with the same parameters.
handlers_from – File to load from a role’s
handlers/directory.rolespec_validate – Perform role argument spec validation if an argument spec is defined.
public – This option dictates whether the role’s
varsanddefaultsare exposed to the play. Variables are exposed to the play at playbook parsing time, and available to earlier roles and tasks as well unlikeinclude_role. The default depends on the configuration optionDEFAULT_PRIVATE_ROLE_VARS. Requires ansible-core >= 2.17
- import_tasks(*, file: str = ...) ImportTasksResults
- import_tasks(arg: str, /) ImportTasksResults
Import a task list.
See also
- Parameters:
file – Specifies the name of the file that lists tasks to add to the current playbook.
- include_role(*, apply: str = ..., name: str, tasks_from: str = 'main', vars_from: str = 'main', defaults_from: str = 'main', allow_duplicates: bool = True, public: bool = False, handlers_from: str = 'main', rolespec_validate: bool = True) IncludeRoleResults
Load and execute a role.
See also
- Parameters:
apply – Accepts a hash of task keywords (for example
tags,become) that will be applied to all tasks within the included role.name – The name of the role to be executed.
tasks_from – File to load from a role’s
tasks/directory.vars_from – File to load from a role’s
vars/directory.defaults_from – File to load from a role’s
defaults/directory.allow_duplicates – Overrides the role’s metadata setting to allow using a role more than once with the same parameters.
public – This option dictates whether the role’s
varsanddefaultsare exposed to the play. If set totruethe variables will be available to tasks following theinclude_roletask. This functionality differs from standard variable exposure for roles listed under therolesheader orimport_role()as they are exposed to the play at playbook parsing time, and available to earlier roles and tasks as well.handlers_from – File to load from a role’s
handlers/directory.rolespec_validate – Perform role argument spec validation if an argument spec is defined.
- include_tasks(*, file: str = ..., apply: str = ...) IncludeTasksResults
- include_tasks(arg: str, /) IncludeTasksResults
Dynamically include a task list.
See also
- Parameters:
file – Specifies the name of the file that lists tasks to add to the current playbook.
apply – Accepts a hash of task keywords (for example
tags,become) that will be applied to the tasks within the include.
- include_vars(*, file: StrPath = ..., dir: StrPath = ..., name: str = ..., depth: int = 0, files_matching: str = ..., ignore_files: Sequence[str] = ..., extensions: Sequence[str] = ..., ignore_unknown_extensions: bool = False, hash_behaviour: Literal['replace', 'merge'] = ...) IncludeVarsResults
- include_vars(arg: str, /) IncludeVarsResults
Load variables from files, dynamically within a task.
See also
- Parameters:
file – The file name from which variables should be loaded. If the path is relative, it will look for the file in
vars/subdirectory of a role or relative to playbook.dir – The directory name from which the variables should be loaded. If the path is relative and the task is inside a role, it will look inside the role’s
vars/subdirectory. If the path is relative and not inside a role, it will be parsed relative to the playbook.name – The name of a variable into which assign the included vars. If omitted (
null) they will be made top level vars.depth – When using
dir, this module will, by default, recursively go through each sub directory and load up the variables. By explicitly setting the depth, this module will only go as deep as the depth.files_matching – Limit the files that are loaded within any directory to this regular expression.
ignore_files – List of file names to ignore.
extensions – List of file extensions to read when using
dir.ignore_unknown_extensions – Ignore unknown file extensions within the directory. This allows users to specify a directory containing vars files that are intermingled with non-vars files extension types (e.g. a directory with a README in it and vars files).
hash_behaviour – If set to
merge, merges existing hash variables instead of overwriting them. If omitted (null), the behavior falls back to the globalhash_behaviourconfiguration. This option is self-contained and does not apply to individual files indir. You can use a loop to applyhash_behaviourper file.
- iptables(*, table: Literal['filter', 'nat', 'mangle', 'raw', 'security'] = 'filter', state: Literal['absent', 'present'] = 'present', action: Literal['append', 'insert'] = 'append', rule_num: str = ..., ip_version: Literal['ipv4', 'ipv6'] = 'ipv4', chain: str = ..., protocol: str = ..., source: str = ..., destination: str = ..., tcp_flags: Mapping[str, Incomplete] = ..., match: Sequence[str] = ..., jump: str = ..., gateway: str = ..., log_prefix: str = ..., log_level: Literal['0', '1', '2', '3', '4', '5', '6', '7', 'emerg', 'alert', 'crit', 'error', 'warning', 'notice', 'info', 'debug'] = ..., goto: str = ..., in_interface: str = ..., out_interface: str = ..., fragment: str = ..., set_counters: str = ..., source_port: str = ..., destination_port: str = ..., destination_ports: Sequence[str] = ..., to_ports: str = ..., to_destination: str = ..., to_source: str = ..., syn: Literal['ignore', 'match', 'negate'] = 'ignore', set_dscp_mark: str = ..., set_dscp_mark_class: str = ..., comment: str = ..., ctstate: Sequence[str] = ..., src_range: str = ..., dst_range: str = ..., match_set: str = ..., match_set_flags: Literal['src', 'dst', 'src,dst', 'dst,src', 'dst,dst', 'src,src'] = ..., limit: str = ..., limit_burst: str = ..., uid_owner: str = ..., gid_owner: str = ..., reject_with: str = ..., icmp_type: str = ..., flush: bool = False, policy: Literal['ACCEPT', 'DROP', 'QUEUE', 'RETURN'] = ..., wait: str = ..., chain_management: bool = False, numeric: bool = False) IptablesResults
Modify iptables rules.
See also
- Parameters:
table – This option specifies the packet matching table on which the command should operate. If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there.
state – Whether the rule should be absent or present.
action – Whether the rule should be appended at the bottom or inserted at the top. If the rule already exists the chain will not be modified.
rule_num – Insert the rule as the given rule number. This works only with
action=insert.ip_version – Which version of the IP protocol this rule should apply to.
chain – Specify the iptables chain to modify. This could be a user-defined chain or one of the standard iptables chains, like
INPUT,FORWARD,OUTPUT,PREROUTING,POSTROUTING,SECMARKorCONNSECMARK.protocol – The protocol of the rule or of the packet to check. The specified protocol can be one of
tcp,udp,udplite,icmp,ipv6-icmporicmpv6,esp,ah,sctpor the special keywordall, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from/etc/protocolsis also allowed. A!argument before the protocol inverts the test. The number zero is equivalent to all.allwill match with all protocols and is taken as default when this option is omitted.source – Source specification. Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address. Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea. The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A
!argument before the address specification inverts the sense of the address.destination – Destination specification. Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address. Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea. The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A
!argument before the address specification inverts the sense of the address.tcp_flags – TCP flags specification.
tcp_flagsexpects a dict with the two keysflagsandflags_set.match – Specifies a match to use, that is, an extension module that tests for a specific property. The set of matches makes up the condition under which a target is invoked. Matches are evaluated first to last if specified as an array and work in short-circuit fashion, in other words if one extension yields false, the evaluation will stop.
jump – This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets that decide the fate of the packet immediately, or an extension (see EXTENSIONS below). If this option is omitted in a rule (and the goto parameter is not used), then matching the rule will have no effect on the packet’s fate, but the counters on the rule will be incremented.
gateway – This specifies the IP address of the host to send the cloned packets. This option is only valid when
jump=TEE.log_prefix – Specifies a log text for the rule. Only makes sense with a LOG jump.
log_level – Logging level according to the syslogd-defined priorities. The value can be strings or numbers from 1-8. This parameter is only applicable if
jump=LOG.goto – This specifies that the processing should continue in a user-specified chain. Unlike the jump argument return will not continue processing in this chain but instead in the chain that called us via jump.
in_interface – Name of an interface via which a packet was received (only for packets entering the
INPUT,FORWARDandPREROUTINGchains). When the!argument is used before the interface name, the sense is inverted. If the interface name ends in a+, then any interface which begins with this name will match. If this option is omitted, any interface name will match.out_interface – Name of an interface via which a packet is going to be sent (for packets entering the
FORWARD,OUTPUTandPOSTROUTINGchains). When the!argument is used before the interface name, the sense is inverted. If the interface name ends in a+, then any interface which begins with this name will match. If this option is omitted, any interface name will match.fragment – This means that the rule only refers to second and further fragments of fragmented packets. Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them. When the “!” argument precedes the fragment argument, the rule will only match head fragments, or unfragmented packets.
set_counters – This enables the administrator to initialize the packet and byte counters of a rule (during
INSERT,APPEND,REPLACEoperations).source_port – Source port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format
first:last. If the first port is omitted,0is assumed; if the last is omitted,65535is assumed. If the first port is greater than the second one they will be swapped.destination_port – Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format first:last. If the first port is omitted, ‘0’ is assumed; if the last is omitted, ‘65535’ is assumed. If the first port is greater than the second one they will be swapped. This is only valid if the rule also specifies one of the following protocols: tcp, udp, dccp or sctp.
destination_ports – This specifies multiple destination port numbers or port ranges to match in the multiport module. It can only be used in conjunction with the protocols tcp, udp, udplite, dccp and sctp.
to_ports – This specifies a destination port or range of ports to use, without this, the destination port is never altered. This is only valid if the rule also specifies one of the protocol
tcp,udp,dccporsctp.to_destination – This specifies a destination address to use with
ctstate=DNAT. Without this, the destination address is never altered.to_source – This specifies a source address to use with
ctstate=SNAT. Without this, the source address is never altered.syn – This allows matching packets that have the SYN bit set and the ACK and RST bits unset. When negated, this matches all packets with the RST or the ACK bits set.
set_dscp_mark – This allows specifying a DSCP mark to be added to packets. It takes either an integer or hex value. If the parameter is set,
jumpis set toDSCP. Mutually exclusive withset_dscp_mark_class.set_dscp_mark_class – This allows specifying a predefined DiffServ class which will be translated to the corresponding DSCP mark. If the parameter is set,
jumpis set toDSCP. Mutually exclusive withset_dscp_mark.comment – This specifies a comment that will be added to the rule.
ctstate – A list of the connection states to match in the conntrack module. Possible values are
INVALID,NEW,ESTABLISHED,RELATED,UNTRACKED,SNAT,DNAT.src_range – Specifies the source IP range to match the iprange module.
dst_range – Specifies the destination IP range to match in the iprange module.
match_set – Specifies a set name that can be defined by ipset. Must be used together with the
match_set_flagsparameter. When the!argument is prepended then it inverts the rule. Uses the iptables set extension.match_set_flags – Specifies the necessary flags for the match_set parameter. Must be used together with the
match_setparameter. Uses the iptables set extension. Choicesdst,dstandsrc,srcadded in version 2.17.limit – Specifies the maximum average number of matches to allow per second. The number can specify units explicitly, using
/second,/minute,/houror/day, or parts of them (so5/secondis the same as5/s).limit_burst – Specifies the maximum burst before the above limit kicks in.
uid_owner – Specifies the UID or username to use in the match by owner rule. From Ansible 2.6 when the
!argument is prepended then the it inverts the rule to apply instead to all users except that one specified.gid_owner – Specifies the GID or group to use in the match by owner rule.
reject_with – Specifies the error packet type to return while rejecting. It implies
jump=REJECT.icmp_type – This allows specification of the ICMP type, which can be a numeric ICMP type, type/code pair, or one of the ICMP type names shown by the command
iptables -p icmp -h.flush – Flushes the specified table and chain of all rules. If no chain is specified then the entire table is purged. Ignores all other parameters.
policy – Set the policy for the chain to the given target. Only built-in chains can have policies. This parameter requires the
chainparameter. If you specify this parameter, all other parameters will be ignored. This parameter is used to set the default policy for the givenchain. Do not confuse this withjumpparameter.wait – Wait N seconds for the xtables lock to prevent multiple instances of the program from running concurrently.
chain_management – If
trueandstateispresent, the chain will be created if needed. Iftrueandstateisabsent, the chain will be deleted if the only other parameter passed arechainand optionallytable.numeric – This parameter controls the running of the list -action of iptables, which is used internally by the module. Does not affect the actual functionality. Use this if iptables hang when creating a chain or altering policy. If
true, then iptables skips the DNS-lookup of the IP addresses in a chain when it uses the list -action. Listing is used internally for example when setting a policy or creating a chain. Requires ansible-core >= 2.15
- known_hosts(*, name: str, key: str = ..., path: StrPath = '~/.ssh/known_hosts', hash_host: bool = False, state: Literal['absent', 'present'] = 'present') KnownHostsResults
Add or remove a host from the
known_hostsfile.See also
- Parameters:
name – The host to add or remove (must match a host specified in key). It will be converted to lowercase so that
ssh-keygencan find it. Must match with <hostname> or <ip> present in key attribute. For custom SSH port,nameneeds to specify port as well. See example section.key – The SSH public host key, as a string. Required if
state=present, optional whenstate=absent, in which case all keys for the host are removed. The key must be in the right format for SSH (see sshd(8), section “SSH_KNOWN_HOSTS FILE FORMAT”). Specifically, the key should not match the format that is found in an SSH pubkey file, but should rather have the hostname prepended to a line that includes the pubkey, the same way that it would appear in the known_hosts file. The value prepended to the line must also match the value of the name parameter. Should be of format<hostname[,IP]> ssh-rsa <pubkey>. For custom SSH port,keyneeds to specify port as well. See example section.path – The known_hosts file to edit. The known_hosts file will be created if needed. The rest of the path must exist prior to running the module.
hash_host – Hash the hostname in the known_hosts file.
state –
presentto add host keys.absentto remove host keys.
- lineinfile(*, path: StrPath, regexp: str = ..., search_string: str = ..., state: Literal['absent', 'present'] = 'present', line: str = ..., backrefs: bool = False, insertafter: str = ..., insertbefore: str = ..., create: bool = False, backup: bool = False, firstmatch: bool = False, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ..., validate: str = ...) LineinfileResults
Manage lines in text files.
See also
- Parameters:
path – The file to modify. Before Ansible 2.3 this option was only usable as
dest,destfileandname.regexp – The regular expression to look for in every line of the file. For
state=present, the pattern to replace if found. Only the last line found will be replaced. Forstate=absent, the pattern of the line(s) to remove. If the regular expression is not matched, the line will be added to the file in keeping withinsertbeforeorinsertaftersettings. When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement bylineto ensure idempotence. Uses Python regular expressions. See reference.search_string – The literal string to look for in every line of the file. This does not have to match the entire line. For
state=present, the line to replace if the string is found in the file. Only the last line found will be replaced. Forstate=absent, the line(s) to remove if the string is in the line. If the literal expression is not matched, the line will be added to the file in keeping withinsertbeforeorinsertaftersettings. Mutually exclusive withbackrefsandregexp.state – Whether the line should be there or not.
line – The line to insert/replace into the file. Required for
state=present. Ifbackrefsis set, may contain backreferences that will get expanded with theregexpcapture groups if the regexp matches.backrefs – Used with
state=present. If set,linecan contain backreferences (both positional and named) that will get populated if theregexpmatches. This parameter changes the operation of the module slightly;insertbeforeandinsertafterwill be ignored, and if theregexpdoes not match anywhere in the file, the file will be left unchanged. If theregexpdoes match, the last matching line will be replaced by the expanded line parameter. Mutually exclusive withsearch_string.insertafter – Used with
state=present. If specified, the line will be inserted after the last match of specified regular expression. If the first match is required, use(firstmatch=yes). A special value is available;EOFfor inserting the line at the end of the file. If specified regular expression has no matches or no value is passed,EOFwill be used instead. Ifinsertbeforeis set, default valueEOFwill be ignored. If regular expressions are passed to bothregexpandinsertafter,insertafteris only honored if no match forregexpis found. May not be used withbackrefsorinsertbefore.insertbefore – Used with
state=present. If specified, the line will be inserted before the last match of specified regular expression. If the first match is required, usefirstmatch=yes. A value is available;BOFfor inserting the line at the beginning of the file. If specified regular expression has no matches, the line will be inserted at the end of the file. If regular expressions are passed to bothregexpandinsertbefore,insertbeforeis only honored if no match forregexpis found. May not be used withbackrefsorinsertafter.create – Used with
state=present. If specified, the file will be created if it does not already exist. By default it will fail if the file is missing.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
firstmatch – Used with
insertafterorinsertbefore. If set,insertafterandinsertbeforewill work with the first line that matches the given regular expression.mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.validate – The validation command to run before copying the updated file into the final destination. A temporary file path is used to validate, passed in through
%swhich must be present as in the examples below. Also, the command is passed securely so shell features such as expansion and pipes will not work. For an example on how to handle more complex validation than what this option provides, seehandling complex validation.
- mount(*, path: StrPath, src: StrPath = ..., fstype: str = ..., opts: str = ..., opts_no_log: bool = False, dump: str = '0', passno: str = '0', state: Literal['absent', 'absent_from_fstab', 'mounted', 'present', 'unmounted', 'remounted', 'ephemeral'], fstab: str = ..., boot: bool = True, backup: bool = False) MountResults
Control active and configured mount points.
See also
- Parameters:
path – Path to the mount point (e.g.
/mnt/files). Before Ansible 2.3 this option was only usable asignore:dest,ignore:destfile, andname.src – Device (or NFS volume, or something else) to be mounted on path. Required when
stateset topresent,mounted, orephemeral. Ignored whenstateset toabsentorunmounted.fstype – Filesystem type. Required when
stateispresent,mounted, orephemeral.opts – Mount options (see fstab(5), or vfstab(4) on Solaris).
opts_no_log – Do not log opts.
dump – Dump (see fstab(5)). Note that if set to
nullandstate=present, it will cease to work and duplicate entries will be made with subsequent runs. Has no effect on Solaris systems or when used withstate=ephemeral.passno – Passno (see fstab(5)). Note that if set to
nullandstate=present, it will cease to work and duplicate entries will be made with subsequent runs. Deprecated on Solaris systems. Has no effect when used withstate=ephemeral.state – If
mounted, the device will be actively mounted and appropriately configured in fstab. If the mount point is not present, the mount point will be created. Ifunmounted, the device will be unmounted without changing fstab.presentonly specifies that the device is to be configured in fstab and does not trigger or require a mount.ephemeralonly specifies that the device is to be mounted, without changing fstab. If it is already mounted, a remount will be triggered. This will always returnignore:changed=true. If the mount pointpathhas already a device mounted on, and its source is different thansrc, the module will fail to avoid unexpected unmount or mount point override. If the mount point is not present, the mount point will be created. The fstab is completely ignored. This option is added in version 1.5.0.absentspecifies that the mount point entrypathwill be removed from fstab and will also unmount the mounted device and remove the mount point. A mounted device will be unmounted regardless ofsrcor its real source.absentdoes not unmount recursively, and the module will fail if multiple devices are mounted on the same mount point. Usingabsentwith a mount point that is not registered in the fstab has no effect, useunmountedinstead.remountedspecifies that the device will be remounted for when you want to force a refresh on the mount itself (added in 2.9). This will always returnignore:changed=true. Ifoptsis set, the options will be applied to the remount, but will not change fstab. Additionally, ifoptsis set, and the remount command fails, the module will error to prevent unexpected mount changes. Try usingmountedinstead to work around this issue.remountedexpects the mount point to be present in the fstab. To remount a mount point not registered in fstab, useephemeralinstead, especially with BSD nodes.absent_from_fstabspecifies that the device mount’s entry will be removed from fstab. This option does not unmount it or delete the mountpoint.fstab – File to use instead of
/etc/fstab. You should not use this option unless you really know what you are doing. This might be useful if you need to configure mountpoints in a chroot environment. OpenBSD does not allow specifying alternate fstab files with mount so do not use this on OpenBSD with any state that operates on the live filesystem. This parameter defaults to/etc/fstabor/etc/vfstabon Solaris. This parameter is ignored whenstate=ephemeral.boot – Determines if the filesystem should be mounted on boot. Only applies to Solaris and Linux systems. For Solaris systems,
truewill setTrueas the value of mount at boot in/etc/vfstab. For Linux, FreeBSD, NetBSD and OpenBSD systems,falsewill addnoautoto mount options in/etc/fstab. To avoid mount option conflicts, ifnoautospecified inopts, mount module will ignoreboot. This parameter is ignored whenstate=ephemeral.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
- mount_facts(*, devices: Sequence[str] = ..., fstypes: Sequence[str] = ..., sources: Sequence[str] = ..., mount_binary: str = 'mount', timeout: float = ..., on_timeout: Literal['error', 'warn', 'ignore'] = 'error', include_aggregate_mounts: bool = ...) MountFactsResults
Retrieve mount information.
See also
ansible.builtin
Note
Requires ansible-core >= 2.18
- Parameters:
devices – A list of fnmatch patterns to filter mounts by the special device or remote file system.
fstypes – A list of fnmatch patterns to filter mounts by the type of the file system.
sources – A list of sources used to determine the mounts. Missing file sources (or empty files) are skipped. Repeat sources, including symlinks, are skipped. The
mount_pointsreturn value contains the first definition found for a mount point. Additional mounts to the same mount point are available fromaggregate_mounts(if enabled). By default, mounts are retrieved from all of the standard locations, which have the predefined aliasesall/static/dynamic.allcontainsdynamicandstatic.dynamiccontains/etc/mtab,/proc/mounts,/etc/mnttab, and the value ofmount_binaryif it is not None. This allows platforms like BSD or AIX, which don’t have an equivalent to/proc/mounts, to collect the current mounts by default. See themount_binaryoption to disable the fall back or configure a different executable.staticcontains/etc/fstab,/etc/vfstab, and/etc/filesystems. Note that/etc/filesystemsis specific to AIX. The Linux file by this name has a different format/purpose and is ignored. The value ofmount_binarycan be configured as a source, which will cause it to always execute. Depending on the other sources configured, this could be inefficient/redundant. For example, if/proc/mountsandmountare listed assources, Linux hosts will retrieve the same mounts twice.mount_binary – The
mount_binaryis used ifsourcescontain the value “mount”, or ifsourcescontains a dynamic source, and none were found (as can be expected on BSD or AIX hosts). Set tonullto stop after no dynamic file source is found instead.timeout – This is the maximum number of seconds to wait for each mount to complete. When this is
null, wait indefinitely. Configure in conjunction withon_timeoutto skip unresponsive mounts. This timeout also applies to themount_binarycommand to list mounts. If the module is configured to run during the play’s fact gathering stage, set a timeout using module_defaults to prevent a hang (see example).on_timeout – The action to take when gathering mount information exceeds
timeout.include_aggregate_mounts – Whether or not the module should return the
aggregate_mountslist inansible_facts. When this isnull, a warning will be emitted if multiple mounts for the same mount point are found.
- net_get(*, src: str, protocol: Literal['scp', 'sftp'] = 'scp', dest: str = ...) NetGetResults
Copy a file from a network device to Ansible Controller.
See also
- Parameters:
src – Specifies the source file. The path to the source file can either be the full path on the network device or a relative path as per path supported by destination network device.
protocol – Protocol used to transfer file.
dest – Specifies the destination file. The path to the destination file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory.
- net_ping(*, count: int | str = 5, dest: str, source: str = ..., state: Literal['absent', 'present'] = 'present', vrf: str = 'default') NetPingResults
Tests reachability using ping from a network device.
See also
- Parameters:
count – Number of packets to send.
dest – The IP Address or hostname (resolvable by switch) of the remote node.
source – The source IP Address.
state – Determines if the expected result is success or fail.
vrf – The VRF to use for forwarding.
- net_put(*, src: str, protocol: Literal['scp', 'sftp'] = 'scp', dest: str = ..., mode: Literal['binary', 'text'] = 'binary') NetPutResults
Copy a file from Ansible Controller to a network device.
See also
- Parameters:
src – Specifies the source file. The path to the source file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory.
protocol – Protocol used to transfer file.
dest – Specifies the destination file. The path to destination file can either be the full path or relative path as supported by network_os.
mode – Set the file transfer mode. If mode is set to text then src file will go through Jinja2 template engine to replace any vars if present in the src file. If mode is set to binary then file will be copied as it is to destination device.
- netconf_config(*, content: str = ..., target: Literal['auto', 'candidate', 'running'] = 'auto', source_datastore: str = ..., format: Literal['xml', 'text', 'json'] = ..., lock: Literal['never', 'always', 'if-supported'] = 'always', default_operation: Literal['merge', 'replace', 'none'] = ..., confirm: int = 0, confirm_commit: bool = False, error_option: Literal['stop-on-error', 'continue-on-error', 'rollback-on-error'] = 'stop-on-error', save: bool = False, backup: bool = False, delete: bool = False, commit: bool = True, validate: bool = False, backup_options: Mapping[str, Incomplete] = ..., get_filter: str = ...) NetconfConfigResults
netconf device configuration.
See also
- Parameters:
content – The configuration data as defined by the device’s data models, the value can be either in xml string format or text format or python dictionary representation of JSON format. In case of json string format it will be converted to the corresponding xml string using xmltodict library before pushing onto the remote host. In case the value of this option isn text format the format should be supported by remote Netconf server. If the value of
contentoption is in xml format in that case the xml value should have config as root tag.target – Name of the configuration datastore to be edited. - auto, uses candidate and fallback to running - candidate, edit <candidate/> datastore and then commit - running, edit <running/> datastore directly.
source_datastore – Name of the configuration datastore to use as the source to copy the configuration to the datastore mentioned by
targetoption. The values can be either running, candidate, startup or a remote URL.format – The format of the configuration provided as value of
content. In case of json string format it will be converted to the corresponding xml string using xmltodict library before pushing onto the remote host. In case of text format of the configuration should be supported by remote Netconf server. If the value offormatoptions is not given it tries to guess the data format ofcontentoption as one of xml or json or text. If the data format is not identified it is set to xml by default.lock – Instructs the module to explicitly lock the datastore specified as
target. By setting the option value always is will explicitly lock the datastore mentioned intargetoption. It the value is never it will not lock thetargetdatastore. The value if-supported lock thetargetdatastore only if it is supported by the remote Netconf server.default_operation – The default operation for <edit-config> rpc, valid values are merge, replace and none. If the default value is merge, the configuration data in the
contentoption is merged at the corresponding level in thetargetdatastore. If the value is replace the data in thecontentoption completely replaces the configuration in thetargetdatastore. If the value is none thetargetdatastore is unaffected by the configuration in the config option, unless and until the incoming configuration data uses theoperationoperation to request a different operation.confirm – This argument will configure a timeout value for the commit to be confirmed before it is automatically rolled back. If the
confirm_commitargument is set to False, this argument is silently ignored. If the value of this argument is set to 0, the commit is confirmed immediately. The remote host MUST support :candidate and :confirmed-commit capability for this option to .confirm_commit – This argument will execute commit operation on remote device. It can be used to confirm a previous commit.
error_option – This option controls the netconf server action after an error occurs while editing the configuration. If error_option=stop-on-error, abort the config edit on first error. If error_option=continue-on-error, continue to process configuration data on error. The error is recorded and negative response is generated if any errors occur. If error_option=rollback-on-error, rollback to the original configuration if any error occurs. This requires the remote Netconf server to support the error_option=rollback-on-error capability.
save – The
saveargument instructs the module to save the configuration intargetdatastore to the startup-config if changed and if :startup capability is supported by Netconf server.backup – This argument will cause the module to create a full backup of the current
running-configfrom the remote device before any changes are made. If thebackup_optionsvalue is not given, the backup file is written to thebackupfolder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.delete – It instructs the module to delete the configuration from value mentioned in
targetdatastore.commit – This boolean flag controls if the configuration changes should be committed or not after editing the candidate datastore. This option is supported only if remote Netconf server supports :candidate capability. If the value is set to False commit won’t be issued after edit-config operation and user needs to handle commit or discard-changes explicitly.
validate – This boolean flag if set validates the content of datastore given in
targetoption. For this option to work remote Netconf server should support :validate capability.backup_options – This is a dict object containing configurable options related to backup file path. The value of this option is read only when
backupis set to True, ifbackupis set to False this option will be silently ignored.get_filter – This argument specifies the XML string which acts as a filter to restrict the portions of the data retrieved from the remote device when comparing the before and after state of the device following calls to edit_config. When not specified, the entire configuration or state data is returned for comparison depending on the value of
sourceoption. Theget_filtervalue can be either XML string or XPath or JSON string or native python dictionary, if the filter is in XPath format the NETCONF server running on remote host should support xpath capability else it will result in an error.
- netconf_get(*, source: Literal['running', 'candidate', 'startup'] = ..., filter: str = ..., display: Literal['json', 'pretty', 'xml', 'native'] = ..., lock: Literal['never', 'always', 'if-supported'] = 'never') NetconfGetResults
Fetch configuration/state data from NETCONF enabled network devices.
See also
- Parameters:
source – This argument specifies the datastore from which configuration data should be fetched. Valid values are running, candidate and startup. If the
sourcevalue is not set both configuration and state information are returned in response from running datastore.filter – This argument specifies the string which acts as a filter to restrict the portions of the data to be are retrieved from the remote device. If this option is not specified entire configuration or state data is returned in result depending on the value of
sourceoption. Thefiltervalue can be either XML string or XPath or JSON string or native python dictionary, if the filter is in XPath format the NETCONF server running on remote host should support xpath capability else it will result in an error. If the filter is in JSON format the xmltodict library should be installed on the control node for JSON to XML conversion.display – Encoding scheme to use when serializing output from the device. The option json will serialize the output as JSON data. If the option value is json it requires jxmlease to be installed on control node. The option pretty is similar to received XML response but is using human readable format (spaces, new lines). The option value xml is similar to received XML response but removes all XML namespaces.
lock – Instructs the module to explicitly lock the datastore specified as
source. If no source is defined, the running datastore will be locked. By setting the option value always is will explicitly lock the datastore mentioned insourceoption. By setting the option value never it will not lock thesourcedatastore. The value if-supported allows better interworking with NETCONF servers, which do not support the (un)lock operation for all supported datastores.
- netconf_rpc(*, rpc: str, xmlns: str = ..., content: str = ..., display: Literal['json', 'pretty', 'xml'] = ...) NetconfRpcResults
Execute operations on NETCONF enabled network devices.
See also
- Parameters:
rpc – This argument specifies the request (name of the operation) to be executed on the remote NETCONF enabled device.
xmlns – NETCONF operations not defined in rfc6241 typically require the appropriate XML namespace to be set. In the case the request option is not already provided in XML format, the namespace can be defined by the xmlns option.
content – This argument specifies the optional request content (all RPC attributes). The content value can either be provided as XML formatted string or as dictionary.
display – Encoding scheme to use when serializing output from the device. The option json will serialize the output as JSON data. If the option value is json it requires jxmlease to be installed on control node. The option pretty is similar to received XML response but is using human readable format (spaces, new lines). The option value xml is similar to received XML response but removes all XML namespaces.
- network_resource(*, os_name: str = ..., name: str = ..., config: str = ..., running_config: str = ..., state: str = ...) NetworkResourceResults
Manage resource modules.
See also
- Parameters:
os_name – The name of the os to manage the resource modules. The name should be fully qualified collection name format, that is <namespace>.<collection-name>.<plugin-name>. If value of this option is not set the os value will be read from ansible_network_os variable. If value of both os_name and ansible_network_os is not set it will result in error.
name – The name of the resource module to manage. The resource module should be supported for given os_name, if not supported it will result in error.
config – The resource module configuration. For details on the type and structure of this option refer the individual resource module platform documentation.
running_config – This option is used only with state parsed. The value of this option should be the output received from the host device by executing the cli command to get the resource configuration on host. The state parsed reads the configuration from
running_configoption and transforms it into Ansible structured data as per the resource module’s argspec and the value is then returned in the parsed key within the result.state – The state the configuration should be left in. For supported values refer the individual resource module platform documentation.
- package(*, name: str, state: str, use: str = 'auto') PackageResults
Generic OS package manager.
See also
- Parameters:
name – Package name, or package specifier with version. Syntax varies with package manager. For example
name-1.0orname=1.0. Package names also vary with package manager; this module will not “translate” them per distribution. For examplelibyaml-dev,libyaml-devel. To operate on several packages this can accept a comma separated string of packages or a list of packages, depending on the underlying package manager.state – Whether to install (
present), or remove (absent) a package. You can use other states likelatestONLY if they are supported by the underlying package module(s) executed.use – The required package manager module to use (
dnf,apt, and so on). The defaultautowill use existing facts or try to auto-detect it. You should only use this field if the automatic selection is not working for some reason. Since version 2.17 you can use theansible_package_usevariable to override the automatic detection, but this option still takes precedence.
- package_facts(*, manager: Sequence[str] = ..., strategy: Literal['first', 'all'] = 'first') PackageFactsResults
Package information as facts.
See also
- Parameters:
manager – The package manager(s) used by the system so we can query the package information. This is a list and can support multiple package managers per system, since version 2.8. The
portageandpkgoptions were added in version 2.8. Theapkoption was added in version 2.11. Thepkg_info’ option was added in version 2.13. Aliases were added in 2.18, to support usingmanager={{ansible_facts['pkg_mgr']}}.strategy – This option controls how the module queries the package managers on the system.
- patch(*, basedir: StrPath = ..., dest: StrPath = ..., src: StrPath, state: Literal['absent', 'present'] = 'present', remote_src: bool = False, strip: int = 0, backup: bool = False, binary: bool = False, ignore_whitespace: bool = False) PatchResults
Apply patch files using the GNU patch tool.
See also
- Parameters:
basedir – Path of a base directory in which the patch file will be applied. May be omitted when
destoption is specified, otherwise required.dest – Path of the file on the remote machine to be patched. The names of the files to be patched are usually taken from the patch file, but if there’s just one file to be patched it can specified with this option.
src – Path of the patch file as accepted by the GNU patch tool. If
remote_src=false, the patch source file is looked up from the module’s files directory.state – Whether the patch should be applied or reverted.
remote_src – If
false, it will search for src at originating/controller machine,. Iftrue, it will go to the remote/target machine for thesrc.strip – Number that indicates the smallest prefix containing leading slashes that will be stripped from each file name found in the patch file. For more information see the strip parameter of the GNU patch tool.
backup – Passes
--backup --version-control=numberedto patch, producing numbered backup copies.binary – Setting to
truewill disable patch’s heuristic for transforming CRLF line endings into LF. Line endings ofsrcanddestmust match. If set tofalse,patchwill replace CRLF insrcfiles on POSIX.ignore_whitespace – Setting to
truewill ignore white space changes between patch and input.
- pause(*, minutes: str = ..., seconds: str = ..., prompt: str = ..., echo: bool = True) PauseResults
Pause playbook execution.
See also
- Parameters:
minutes – A positive number of minutes to pause for.
seconds – A positive number of seconds to pause for.
prompt – Optional text to use for the prompt message. User input is only returned if
secondsandminutesare both not specified, otherwise this is just a custom message before playbook execution is paused.echo – Controls whether or not keyboard input is shown when typing. Only has effect if neither
secondsnorminutesare set.
- ping(*, data: str = 'pong') PingResults
Try to connect to host, verify a usable python and return
pongon success.See also
- Parameters:
data – Data to return for the
pingreturn value. If this parameter is set tocrash, the module will cause an exception.
- pip(*, name: Sequence[str] = ..., version: str = ..., requirements: str = ..., virtualenv: StrPath = ..., virtualenv_site_packages: bool = False, virtualenv_command: StrPath = 'virtualenv', virtualenv_python: str = ..., state: Literal['absent', 'forcereinstall', 'latest', 'present'] = 'present', extra_args: str = ..., editable: bool = False, chdir: StrPath = ..., executable: StrPath = ..., umask: str = ..., break_system_packages: bool = False) PipResults
Manages Python library dependencies.
See also
- Parameters:
name – The name of a Python library to install or the url(bzr+,hg+,git+,svn+) of the remote package. This can be a list (since 2.2) and contain version specifiers (since 2.7).
version – The version number to install of the Python library specified in the
nameparameter.requirements – The path to a pip requirements file, which should be local to the remote system. File can be specified as a relative path if using the
chdiroption.virtualenv – An optional path to a virtualenv directory to install into. It cannot be specified together with the
executableparameter (added in 2.1). If the virtualenv does not exist, it will be created before installing packages. The optionalvirtualenv_site_packages,virtualenv_command, andvirtualenv_pythonoptions affect the creation of the virtualenv.virtualenv_site_packages – Whether the virtual environment will inherit packages from the global
site-packagesdirectory. Note that if this setting is changed on an already existing virtual environment it will not have any effect, the environment must be deleted and newly created.virtualenv_command – The command or a pathname to the command to create the virtual environment with. For example
pyvenv,virtualenv,virtualenv2,~/bin/virtualenv,/usr/local/bin/virtualenv.virtualenv_python – The Python executable used for creating the virtual environment. For example
python3.12,python2.7. When not specified, the Python version used to run the ansible module is used. This parameter should not be used whenvirtualenv_commandis usingpyvenvor the-m venvmodule.state – The state of module. The
forcereinstalloption is only available in Ansible 2.1 and above.extra_args – Extra arguments passed to
pip.editable – Pass the editable flag.
chdir – cd into this directory before running the command.
executable – The explicit executable or pathname for the
pipexecutable, if different from the Ansible Python interpreter. For examplepip3.3, if there are both Python 2.7 and 3.3 installations in the system and you want to run pip for the Python 3.3 installation. Mutually exclusive withvirtualenv(added in 2.1). Does not affect the Ansible Python interpreter. Thesetuptoolspackage must be installed for both the Ansible Python interpreter and for the version of Python specified by this option.umask – The system umask to apply before installing the pip package. This is useful, for example, when installing on systems that have a very restrictive umask by default (e.g.,
0077) and you want topip installpackages which are to be used by all users. Note that this requires you to specify desired umask mode as an octal string, (e.g.,0022).break_system_packages – Allow
pipto modify an externally-managed Python installation as defined by PEP 668. This is typically required when installing packages outside a virtual environment on modern systems. Requires ansible-core >= 2.17
- raw(*, executable: str = ...) RawResults
- raw(arg: str, /) RawResults
Executes a low-down and dirty command.
See also
- Parameters:
executable – Change the shell used to execute the command. Should be an absolute path to the executable. When using privilege escalation (
become) a default shell will be assigned if one is not provided as privilege escalation requires a shell.
- reboot(*, pre_reboot_delay: int = 0, post_reboot_delay: int = 0, reboot_timeout: int = 600, connect_timeout: int = ..., test_command: str = 'whoami', msg: str = ..., search_paths: Sequence[str] = ..., boot_time_command: str = ..., reboot_command: str = ...) RebootResults
Reboot a machine.
See also
- Parameters:
pre_reboot_delay – Seconds to wait before reboot. Passed as a parameter to the reboot command. On Linux, macOS and OpenBSD, this is converted to minutes and rounded down. If less than 60, it will be set to 0. On Solaris and FreeBSD, this will be seconds.
post_reboot_delay – Seconds to wait after the reboot command was successful before attempting to validate the system rebooted successfully. This is useful if you want wait for something to settle despite your connection already working.
reboot_timeout – Maximum seconds to wait for machine to reboot and respond to a test command. This timeout is evaluated separately for both reboot verification and test command success so the maximum execution time for the module is twice this amount.
connect_timeout – Maximum seconds to wait for a successful connection to the managed hosts before trying again. If unspecified, the default setting for the underlying connection plugin is used.
test_command – Command to run on the rebooted host and expect success from to determine the machine is ready for further tasks.
msg – Message to display to users before reboot.
search_paths – Paths to search on the remote machine for the
shutdowncommand. Only these paths will be searched for theshutdowncommand.PATHis ignored in the remote node when searching for theshutdowncommand.boot_time_command – Command to run that returns a unique string indicating the last time the system was booted. Setting this to a command that has different output each time it is run will cause the task to fail.
reboot_command – Command to run that reboots the system, including any parameters passed to the command. Can be an absolute path to the command or just the command name. If an absolute path to the command is not given,
search_pathson the target system will be searched to find the absolute path. This will causepre_reboot_delay,post_reboot_delay, andmsgto be ignored.
- replace(*, path: StrPath, regexp: str, replace: str = '', after: str = ..., before: str = ..., backup: bool = False, encoding: str = 'utf-8', mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ..., validate: str = ...) ReplaceResults
Replace all instances of a particular string in a file using a back-referenced regular expression.
See also
- Parameters:
path – The file to modify. Before Ansible 2.3 this option was only usable as
dest,destfileandname.regexp – The regular expression to look for in the contents of the file. Uses Python regular expressions; see reference. Uses MULTILINE mode, which means
^and$match the beginning and end of the file, as well as the beginning and end respectively of each line of the file. Does not use DOTALL, which means the.special character matches any character except newlines. A common mistake is to assume that a negated character set like[^#]will also not match newlines. In order to exclude newlines, they must be added to the set like[^#\n]. Note that, as of Ansible 2.0, short form tasks should have any escape sequences backslash-escaped in order to prevent them being parsed as string literal escapes. See the examples.replace – The string to replace regexp matches. May contain backreferences that will get expanded with the regexp capture groups if the regexp matches. If not set, matches are removed entirely. Backreferences can be used ambiguously like
\1, or explicitly like\g<1>.after – If specified, only content after this match will be replaced/removed. Can be used in combination with
before. Uses Python regular expressions; see reference. Uses DOTALL, which means the.special character can match newlines. Does not use MULTILINE, so^and$will only match the beginning and end of the file.before – If specified, only content before this match will be replaced/removed. Can be used in combination with
after. Uses Python regular expressions; see reference. Uses DOTALL, which means the.special character can match newlines. Does not use MULTILINE, so^and$will only match the beginning and end of the file.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
encoding – The character encoding for reading and writing the file.
mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.validate – The validation command to run before copying the updated file into the final destination. A temporary file path is used to validate, passed in through
%swhich must be present as in the examples below. Also, the command is passed securely so shell features such as expansion and pipes will not work. For an example on how to handle more complex validation than what this option provides, seehandling complex validation.
- restconf_config(*, path: str, content: str = ..., method: Literal['post', 'put', 'patch', 'delete'] = 'post', format: Literal['json', 'xml'] = 'json') RestconfConfigResults
Handles create, update, read and delete of configuration data on RESTCONF enabled devices.
See also
- Parameters:
path – URI being used to execute API calls.
content – The configuration data in format as specififed in
formatoption. Required unlessmethodis delete.method – The RESTCONF method to manage the configuration change on device. The value post is used to create a data resource or invoke an operation resource, put is used to replace the target data resource, patch is used to modify the target resource, and delete is used to delete the target resource.
format – The format of the configuration provided as value of
content. Accepted values are xml and json and the given configuration format should be supported by remote RESTCONF server.
- restconf_get(*, path: str, content: Literal['config', 'nonconfig', 'all'] = ..., output: Literal['json', 'xml'] = 'json') RestconfGetResults
Fetch configuration/state data from RESTCONF enabled devices.
See also
- Parameters:
path – URI being used to execute API calls.
content – The
contentis a query parameter that controls how descendant nodes of the requested data nodes inpathwill be processed in the reply. If value is config return only configuration descendant data nodes of value inpath. If value is nonconfig return only non-configuration descendant data nodes of value inpath. If value is all return all descendant data nodes of value inpath.output – The output of response received.
- rhel_facts(arg: str, /) RhelFactsResults
Facts module to set or override RHEL specific facts.
See also
- rhel_rpm_ostree(*, name: Sequence[str] = ..., state: Literal['absent', 'installed', 'latest', 'present', 'removed'] = ...) RhelRpmOstreeResults
Ensure packages exist in a RHEL for Edge rpm-ostree based system.
See also
- Parameters:
name – A package name or package specifier with version, like
name-1.0. Comparison operators for package version are valid here>,<,>=,<=. Example -name>=1.0. If a previous version is specified, the task also needs to turnallow_downgradeon. See theallow_downgradedocumentation for caveats with downgrading packages. When usingstate=latest, this can be'*'which means runyum -y update. You can also pass a url or a local path to a rpm file (usingstate=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages.state – Whether to install (
presentorinstalled,latest), or remove (absentorremoved) a package.presentandinstalledwill simply ensure that a desired package is installed.latestwill update the specified package if it’s not of the latest available version.absentandremovedwill remove the specified package. Default isnull, however in effect the default action ispresentunless theautoremoveoption is enabled for this module, thenabsentis inferred.
- rpm_key(*, key: str, state: Literal['absent', 'present'] = 'present', validate_certs: bool = True, fingerprint: Sequence[str] = ...) RpmKeyResults
Adds or removes a gpg key from the rpm db.
See also
- Parameters:
key – Key that will be modified. Can be a url, a file on the managed node, or a keyid if the key already exists in the database.
state – If the key will be imported or removed from the rpm db.
validate_certs – If
falseand thekeyis a url starting withhttps, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.fingerprint – The long-form fingerprint of the key being imported. This will be used to verify the specified key.
- rpm_ostree_upgrade(*, os: str = '', cache_only: bool = False, allow_downgrade: bool = False, peer: bool = False) RpmOstreeUpgradeResults
Manage rpm-ostree upgrade transactions.
See also
- Parameters:
os – The OSNAME upon which to operate.
cache_only – Perform the transaction using only pre-cached data, do not download.
allow_downgrade – Allow for the upgrade to be a chronologically older tree.
peer – Force peer-to-peer connection instead of using a system message bus.
- script(*, cmd: str = ..., creates: str = ..., removes: str = ..., chdir: str = ..., executable: str = ..., decrypt: bool = True) ScriptResults
- script(arg: str, /) ScriptResults
Runs a local script on a remote node after transferring it.
See also
- Parameters:
cmd – Path to the local script to run followed by optional arguments.
creates – A filename on the remote node, when it already exists, this step will not be run.
removes – A filename on the remote node, when it does not exist, this step will not be run.
chdir – Change into this directory on the remote node before running the script.
executable – Name or path of an executable to invoke the script with.
decrypt – This option controls the auto-decryption of source files using vault.
- seboolean(*, name: str, persistent: bool = False, state: bool, ignore_selinux_state: bool = False) SebooleanResults
Toggles SELinux booleans.
See also
- Parameters:
name – Name of the boolean to configure.
persistent – Set to
trueif the boolean setting should survive a reboot.state – Desired boolean value.
ignore_selinux_state – Useful for scenarios (chrooted environment) that you can’t get the real SELinux state.
- selinux(*, policy: str = ..., state: Literal['disabled', 'enforcing', 'permissive'], update_kernel_param: bool = False, configfile: str = '/etc/selinux/config') SelinuxResults
Change policy and state of SELinux.
See also
- Parameters:
policy – The name of the SELinux policy to use (e.g.
targeted) will be required unlessstate=disabled.state – The SELinux mode.
update_kernel_param – If set to
true, will update also the kernel boot parameters when disabling/enabling SELinux. Thegrubbytool must be present on the target system for this to work.configfile – The path to the SELinux configuration file, if non-standard.
- service(*, name: str, state: Literal['reloaded', 'restarted', 'started', 'stopped'] = ..., sleep: int = ..., pattern: str = ..., enabled: bool = ..., runlevel: str = 'default', arguments: str = '', use: str = 'auto') ServiceResults
Manage services.
See also
- Parameters:
name – Name of the service.
state –
started/stoppedare idempotent actions that will not run commands unless necessary.restartedwill always bounce the service.reloadedwill always reload. At least one ofstateandenabledare required. Note thatreloadedwill start the service if it is not already started, even if your chosen init system wouldn’t normally.sleep – If the service is being
restartedthen sleep this many seconds between the stop and start command. This helps to work around badly-behaving init scripts that exit immediately after signaling a process to stop. Not all service managers support sleep, i.e when using systemd this setting will be ignored.pattern – If the service does not respond to the status command, name a substring to look for as would be found in the output of the
pscommand as a stand-in for a status result. If the string is found, the service will be assumed to be started. While using remote hosts with systemd this setting will be ignored.enabled – Whether the service should start on boot. At least one of
stateandenabledare required.runlevel – For OpenRC init scripts (e.g. Gentoo) only. The runlevel that this service belongs to. While using remote hosts with systemd this setting will be ignored.
arguments – Additional arguments provided on the command line. While using remote hosts with systemd this setting will be ignored.
use – The service module actually uses system specific modules, normally through auto detection, this setting can force a specific module. Normally it uses the value of the
ansible_service_mgrfact and falls back to theansible.legacy.servicemodule when none matching is found. The ‘old service module’ still uses autodetection and in no way does it correspond to theservicecommand.
- service_facts() ServiceFactsResults
Return service state information as fact data.
See also
- set_fact(*, key_value: str, cacheable: bool = False) SetFactResults
Set host variable(s) and fact(s).
See also
- Parameters:
key_value – The
set_fact()method takeskey=valuepairs orkey: value(YAML notation) as variables to set in the playbook scope. The ‘key’ is the resulting variable name and the value is, of course, the value of said variable. You can create multiple variables at once, by supplying multiple pairs, but do NOT mix notations.cacheable – This boolean converts the variable into an actual ‘fact’ which will also be added to the fact cache. It does not enable fact caching across runs, it just means it will work with it if already enabled. Normally this module creates ‘host level variables’ and has much higher precedence, this option changes the nature and precedence (by 7 steps) of the variable created. variable-precedence-where-should-i-put-a-variable. This actually creates 2 copies of the variable, a normal ‘set_fact’ host variable with high precedence and a lower ‘ansible_fact’ one that is available for persistence via the facts cache plugin. This creates a possibly confusing interaction with
meta: clear_factsas it will remove the ‘ansible_fact’ but not the host variable.
- set_stats(*, data: Mapping[str, Incomplete], per_host: bool = False, aggregate: bool = True) SetStatsResults
Define and display stats for the current ansible run.
See also
- Parameters:
data – A dictionary of which each key represents a stat (or variable) you want to keep track of.
per_host – Whether the stats are per host or for all hosts in the run.
aggregate – Whether the provided value is aggregated to the existing stat
trueor will replace itfalse.
- setup(*, gather_subset: Sequence[str] = ..., gather_timeout: int = 10, filter: Sequence[str] = ..., fact_path: StrPath = '/etc/ansible/facts.d') SetupResults
Gathers facts about remote hosts.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
gather_subset – If supplied, restrict the additional facts collected to the given subset. Possible values:
all,all_ipv4_addresses,all_ipv6_addresses,apparmor,architecture,caps,chroot,``cmdline``,date_time,default_ipv4,default_ipv6,devices,distribution,distribution_major_version,distribution_release,distribution_version,dns,effective_group_ids,effective_user_id,env,facter,fips,hardware,interfaces,is_chroot,iscsi,kernel,local,lsb,machine,machine_id,mounts,network,ohai,os_family,pkg_mgr,platform,processor,processor_cores,processor_count,python,python_version,real_user_id,selinux,service_mgr,ssh_host_key_dsa_public,ssh_host_key_ecdsa_public,ssh_host_key_ed25519_public,ssh_host_key_rsa_public,ssh_host_pub_keys,ssh_pub_keys,system,system_capabilities,system_capabilities_enforced,systemd,user,user_dir,user_gecos,user_gid,user_id,user_shell,user_uid,virtual,virtualization_role,virtualization_type. Can specify a list of values to specify a larger subset. Values can also be used with an initial!to specify that that specific subset should not be collected. For instance:!hardware,!network,!virtual,!ohai,!facter. If!allis specified then only the min subset is collected. To avoid collecting even the min subset, specify!all,!min. To collect only specific facts, use!all,!min, and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts.gather_timeout – Set the default timeout in seconds for individual fact gathering.
filter – If supplied, only return facts that match one of the shell-style (fnmatch) pattern. An empty list basically means ‘no filter’. As of Ansible 2.11, the type has changed from string to list and the default has became an empty list. A simple string is still accepted and works as a single pattern. The behaviour prior to Ansible 2.11 remains.
fact_path – Path used for local ansible facts (
*.fact) - files in this dir will be run (if executable) and their results be added toansible_localfacts. If a file is not executable it is read instead. File/results format can be JSON or INI-format. The defaultfact_pathcan be specified inansible.cfgfor when setup is automatically called as part ofgather_facts. NOTE - For windows clients, the results will be added to a variable named after the local file (without extension suffix), rather thanansible_local. Since Ansible 2.1, Windows hosts can usefact_path. Make sure that this path exists on the target host. Files in this path MUST be PowerShell scripts.ps1which outputs an object. This object will be formatted by Ansible as json so the script should be outputting a raw hashtable, array, or other primitive object.
- shell(*, cmd: str = ..., creates: StrPath = ..., removes: StrPath = ..., chdir: StrPath = ..., executable: StrPath = ..., stdin: str = ..., stdin_add_newline: bool = True) ShellResults
- shell(arg: str, /) ShellResults
Execute shell commands on targets.
See also
- Parameters:
cmd – The command to run followed by optional arguments.
creates – A filename, when it already exists, this step will not be run.
removes – A filename, when it does not exist, this step will not be run.
chdir – Change into this directory before running the command.
executable – Change the shell used to execute the command. This expects an absolute path to the executable.
stdin – Set the stdin of the command directly to the specified value.
stdin_add_newline – Whether to append a newline to stdin data.
- slurp(*, src: StrPath) SlurpResults
Slurps a file from remote nodes.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
src – The file on the remote system to fetch. This must be a file, not a directory.
- stat(*, path: StrPath, follow: bool = False, get_checksum: bool = True, checksum_algorithm: Literal['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'] = 'sha1', get_mime: bool = True, get_attributes: bool = True) StatResults
Retrieve file or file system status.
See also
- Parameters:
path – The full path of the file/object to get the facts of.
follow – Whether to follow symlinks.
get_checksum – Whether to return a checksum of the file.
checksum_algorithm – Algorithm to determine checksum of file. Will throw an error if the host is unable to use specified algorithm. The remote host has to support the hashing method specified,
md5can be unavailable if the host is FIPS-140 compliant.get_mime – Use file magic and return data about the nature of the file. This uses the
fileutility found on most Linux/Unix systems. This will add bothstat.mimetypeandstat.charsetfields to the return, if possible. In Ansible 2.3 this option changed frommimetoget_mimeand the default changed totrue.get_attributes – Get file attributes using lsattr tool if present.
- subversion(*, repo: str, dest: StrPath = ..., revision: str = 'HEAD', force: bool = False, in_place: bool = False, username: str = ..., password: str = ..., executable: StrPath = ..., checkout: bool = True, update: bool = True, export: bool = False, switch: bool = True, validate_certs: bool = False) SubversionResults
Deploys a subversion repository.
See also
- Parameters:
repo – The subversion URL to the repository.
dest – Absolute path where the repository should be deployed. The destination directory must be specified unless
checkout=no,update=no, andexport=no.revision – Specific revision to checkout.
force – If
true, modified files will be discarded. Iffalse, module will fail if it encounters modified files. Prior to 1.9 the default wastrue.in_place – If the directory exists, then the working copy will be checked-out over-the-top using
svn checkout --force; if force is specified then existing files with different content are reverted.username –
--usernameparameter passed to svn.password –
--passwordparameter passed to svn when svn is less than version 1.10.0. This is not secure and the password will be leaked to argv.--password-from-stdinparameter when svn is greater or equal to version 1.10.0.executable – Path to svn executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.
checkout – If
false, do not check out the repository if it does not exist locally.update – If
false, do not retrieve new revisions from the origin repository.export – If
true, do export instead of checkout/update.switch – If
false, do not call svn switch before update.validate_certs – If
false, passes the--trust-server-certflag to svn. Iftrue, does not pass the flag.
- synchronize(*, src: StrPath, dest: StrPath, dest_port: int = ..., mode: Literal['pull', 'push'] = 'push', archive: bool = True, checksum: bool = False, compress: bool = True, existing_only: bool = False, delete: bool = False, dirs: bool = False, recursive: bool = ..., links: bool = ..., copy_links: bool = False, perms: bool = ..., times: bool = ..., owner: bool = ..., group: bool = ..., rsync_path: str = ..., rsync_timeout: int = 0, set_remote_user: bool = True, ssh_connection_multiplexing: bool = False, rsync_opts: Sequence[str] = ..., partial: bool = False, verify_host: bool = False, private_key: StrPath = ..., link_dest: Sequence[StrPath] = ..., delay_updates: bool = True, use_ssh_args: bool = False, _local_rsync_path: StrPath = 'rsync', _local_rsync_password: str = ..., _substitute_controller: bool = False, _ssh_args: str = ...) SynchronizeResults
A wrapper around rsync to make common tasks in your playbooks quick and easy.
See also
- Parameters:
src – Path on the source host that will be synchronized to the destination. The path can be absolute or relative.
dest – Path on the destination host that will be synchronized from the source. The path can be absolute or relative.
dest_port – Port number for ssh on the destination host. Prior to Ansible 2.0, the
ansible_ssh_portinventory var took precedence over this value. This parameter defaults to the value ofansible_port, theremote_portconfig setting or the value from ssh client configuration if none of the former have been set.mode – Specify the direction of the synchronization. In
pushmode the localhost or delegate is the source. Inpullmode the remote host in context is the source.archive – Mirrors the rsync archive flag, enables recursive, links, perms, times, owner, group flags, and
-D.checksum – Skip based on checksum, rather than mod-time & size; Note that that
archiveoption is still enabled by default - thechecksumoption will not disable it.compress – Compress file data during the transfer. In most cases, leave this enabled unless it causes problems.
existing_only – Skip creating new files on receiver.
delete – Delete files in
destthat do not exist (after transfer, not before) in thesrcpath. This option requiresrecursive=true. This option ignores excluded files and behaves like the rsync opt--delete-after.dirs – Transfer directories without recursing.
recursive – Recurse into directories. This parameter defaults to the value of the archive option.
links – Copy symlinks as symlinks. This parameter defaults to the value of the archive option.
copy_links – Copy symlinks as the item that they point to (the referent) is copied, rather than the symlink.
perms – Preserve permissions. This parameter defaults to the value of the archive option.
times – Preserve modification times. This parameter defaults to the value of the archive option.
owner – Preserve owner (super user only). This parameter defaults to the value of the archive option.
group – Preserve group. This parameter defaults to the value of the archive option.
rsync_path – Specify the rsync command to run on the remote host. See
--rsync-pathon the rsync man page. To specify the rsync command to run on the local host, you need to set this your task varansible_rsync_path.rsync_timeout – Specify a
--timeoutfor the rsync command in seconds.set_remote_user – Put
user@for the remote paths. If you have a custom ssh config to define the remote user for a host that does not match the inventory user, you should set this parameter tofalse.ssh_connection_multiplexing – SSH connection multiplexing for rsync is disabled by default to prevent misconfigured ControlSockets from resulting in failed SSH connections. This is accomplished by setting the SSH
ControlSockettonone. Set this option totrueto allow multiplexing and reduce SSH connection overhead. Note that simply setting this option totrueis not enough; You must also configure SSH connection multiplexing in your SSH client config by setting values forControlMaster,ControlPersistandControlPath.rsync_opts – Specify additional rsync options by passing in an array. Note that an empty string in
rsync_optswill end up transfer the current working directory.partial – Tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster.
verify_host – Verify destination host key.
private_key – Specify the private key to use for SSH-based rsync connections (e.g.
~/.ssh/id_rsa).link_dest – Add a destination to hard link against during the rsync.
delay_updates – This option puts the temporary file from each updated file into a holding directory until the end of the transfer, at which time all the files are renamed into place in rapid succession.
use_ssh_args – In Ansible 2.10 and lower, it uses the ssh_args specified in
ansible.cfg. In Ansible 2.11 and onwards, when set totrue, it uses all SSH connection configurations likeansible_ssh_args,ansible_ssh_common_args, andansible_ssh_extra_args._local_rsync_path – Internal use only.
_local_rsync_password – Internal use only, never logged.
_substitute_controller – Internal use only.
_ssh_args – Internal use only. See
use_ssh_argsfor ssh arg settings.
- sysctl(*, name: str, value: str = ..., state: Literal['present', 'absent'] = 'present', ignoreerrors: bool = False, reload: bool = True, sysctl_file: StrPath = '/etc/sysctl.conf', sysctl_set: bool = False) SysctlResults
Manage entries in sysctl.conf.
See also
- Parameters:
name – The dot-separated path (also known as
key) specifying the sysctl variable.value – Desired value of the sysctl key.
state – Whether the entry should be present or absent in the sysctl file.
ignoreerrors – Use this option to ignore errors about unknown keys.
reload – If
true, performs a/sbin/sysctl -pif thesysctl_fileis updated. Iffalse, does not reloadsysctleven if thesysctl_fileis updated.sysctl_file – Specifies the absolute path to
sysctl.conf, if not/etc/sysctl.conf.sysctl_set – Verify token value with the sysctl command and set with
-wif necessary.
- systemd(*, name: str = ..., state: Literal['reloaded', 'restarted', 'started', 'stopped'] = ..., enabled: bool = ..., force: bool = ..., masked: bool = ..., daemon_reload: bool = False, daemon_reexec: bool = False, scope: Literal['system', 'user', 'global'] = 'system', no_block: bool = False) SystemdResults
Manage systemd units.
See also
- Parameters:
name – Name of the unit. This parameter takes the name of exactly one unit to work with. When no extension is given, it is implied to a
.serviceas systemd. When using in a chroot environment you always need to specify the name of the unit with the extension. For example,crond.service.state –
started/stoppedare idempotent actions that will not run commands unless necessary.restartedwill always bounce the unit.reloadedwill always reload and if the service is not running at the moment of the reload, it is started. If set, requiresname.enabled – Whether the unit should start on boot. At least one of
stateandenabledare required. If set, requiresname.force – Whether to override existing symlinks.
masked – Whether the unit should be masked or not. A masked unit is impossible to start. If set, requires
name.daemon_reload – Run
daemon-reloadbefore doing any other operations, to make sure systemd has read any changes. When set totrue, runsdaemon-reloadeven if the module does not start or stop anything.daemon_reexec – Run daemon_reexec command before doing any other operations, the systemd manager will serialize the manager state.
scope – Run
systemctlwithin a given service manager scope, either as the default system scopesystem, the current user’s scopeuser, or the scope of all usersglobal. For systemd to work withuser, the executing user must have its own instance of dbus started and accessible (systemd requirement). The user dbus process is normally started during normal login, but not during the run of Ansible tasks. Otherwise you will probably get a ‘Failed to connect to bus: no such file or directory’ error. The user must have access, normally given via setting theXDG_RUNTIME_DIRvariable, see the example below.no_block – Do not synchronously wait for the requested operation to finish. Enqueued job will continue without Ansible blocking on its completion.
- systemd_service(*, name: str = ..., state: Literal['reloaded', 'restarted', 'started', 'stopped'] = ..., enabled: bool = ..., force: bool = ..., masked: bool = ..., daemon_reload: bool = False, daemon_reexec: bool = False, scope: Literal['system', 'user', 'global'] = 'system', no_block: bool = False) SystemdServiceResults
Manage systemd units.
See also
- Parameters:
name – Name of the unit. This parameter takes the name of exactly one unit to work with. When no extension is given, it is implied to a
.serviceas systemd. When using in a chroot environment you always need to specify the name of the unit with the extension. For example,crond.service.state –
started/stoppedare idempotent actions that will not run commands unless necessary.restartedwill always bounce the unit.reloadedwill always reload and if the service is not running at the moment of the reload, it is started. If set, requiresname.enabled – Whether the unit should start on boot. At least one of
stateandenabledare required. If set, requiresname.force – Whether to override existing symlinks.
masked – Whether the unit should be masked or not. A masked unit is impossible to start. If set, requires
name.daemon_reload – Run
daemon-reloadbefore doing any other operations, to make sure systemd has read any changes. When set totrue, runsdaemon-reloadeven if the module does not start or stop anything.daemon_reexec – Run daemon_reexec command before doing any other operations, the systemd manager will serialize the manager state.
scope – Run
systemctlwithin a given service manager scope, either as the default system scopesystem, the current user’s scopeuser, or the scope of all usersglobal. For systemd to work withuser, the executing user must have its own instance of dbus started and accessible (systemd requirement). The user dbus process is normally started during normal login, but not during the run of Ansible tasks. Otherwise you will probably get a ‘Failed to connect to bus: no such file or directory’ error. The user must have access, normally given via setting theXDG_RUNTIME_DIRvariable, see the example below.no_block – Do not synchronously wait for the requested operation to finish. Enqueued job will continue without Ansible blocking on its completion.
- sysvinit(*, name: str, state: Literal['started', 'stopped', 'restarted', 'reloaded'] = ..., enabled: bool = ..., sleep: int = 1, pattern: str = ..., runlevels: Sequence[str] = ..., arguments: str = ..., daemonize: bool = False) SysvinitResults
Manage SysV services.
See also
- Parameters:
name – Name of the service.
state –
started/stoppedare idempotent actions that will not run commands unless necessary. Not all init scripts supportrestartednorreloadednatively, so these will both trigger a stop and start as needed.enabled – Whether the service should start on boot. At least one of
stateandenabledare required.sleep – If the service is being
restartedorreloadedthen sleep this many seconds between the stop and start command. This helps to workaround badly behaving services.pattern – A substring to look for as would be found in the output of the ps command as a stand-in for a status result. If the string is found, the service will be assumed to be running. This option is mainly for use with init scripts that don’t support the
statusoption.runlevels – The runlevels this script should be enabled/disabled from. Use this to override the defaults set by the package or init script itself.
arguments – Additional arguments provided on the command line that some init scripts accept.
daemonize – Have the module daemonize as the service itself might not do so properly. This is useful with badly written init scripts or daemons, which commonly manifests as the task hanging as it is still holding the tty or the service dying when the task is over as the connection closes the session.
- telnet(*, command: Sequence[str], host: str = 'remote_addr', user: str = 'remote_user', password: str = ..., port: int = 23, timeout: int = 120, prompts: Sequence[str] = ..., login_prompt: str = ..., password_prompt: str = ..., pause: int = 1, send_newline: bool = False, crlf: bool = False) TelnetResults
Executes a low-down and dirty telnet command.
See also
- Parameters:
command – List of commands to be executed in the telnet session.
host – The host/target on which to execute the command.
user – The user for login.
password – The password for login.
port – Remote port to use.
timeout – timeout for remote operations.
prompts – List of prompts expected before sending next command.
login_prompt – Login or username prompt to expect.
password_prompt – Login or username prompt to expect.
pause – Seconds to pause between each command issued.
send_newline – Sends a newline character upon successful connection to start the terminal session.
crlf – Sends a CRLF (Carrage Return) instead of just a LF (Line Feed).
- tempfile(*, state: Literal['directory', 'file'] = 'file', path: StrPath = ..., prefix: str = 'ansible.', suffix: str = '') TempfileResults
Creates temporary files and directories.
See also
- Parameters:
state – Whether to create file or directory.
path – Location where temporary file or directory should be created. If path is not specified, the default system temporary directory will be used.
prefix – Prefix of file/directory name created by module.
suffix – Suffix of file/directory name created by module.
- template(*, follow: bool = False, backup: bool = False, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ..., src: StrPath, dest: StrPath, newline_sequence: Literal['\\n', '\\r', '\\r\\n'] = '\\n', block_start_string: str = '{%', block_end_string: str = '%}', variable_start_string: str = '{{', variable_end_string: str = '}}', comment_start_string: str = ..., comment_end_string: str = ..., trim_blocks: bool = True, lstrip_blocks: bool = False, force: bool = True, output_encoding: str = 'utf-8', validate: str = ...) TemplateResults
Template a file out to a target host.
See also
- Parameters:
follow – Determine whether symbolic links should be followed. When set to
truesymbolic links will be followed, if they exist. When set tofalsesymbolic links will not be followed. Previous to Ansible 2.4, this was hardcoded astrue.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.src – Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or an absolute path. The file must be encoded with
utf-8butoutput_encodingcan be used to control the encoding of the output template.dest – Location to render the template to on the remote machine.
newline_sequence – Specify the newline sequence to use for templating files.
block_start_string – The string marking the beginning of a block.
block_end_string – The string marking the end of a block.
variable_start_string – The string marking the beginning of a print statement.
variable_end_string – The string marking the end of a print statement.
comment_start_string – The string marking the beginning of a comment statement.
comment_end_string – The string marking the end of a comment statement.
trim_blocks – Determine when newlines should be removed from blocks. When set to
Truethe first newline after a block is removed (block, not variable tag!).lstrip_blocks – Determine when leading spaces and tabs should be stripped. When set to
Trueleading spaces and tabs are stripped from the start of a line to a block.force – Determine when the file is being transferred if the destination already exists. When set to
True, replace the remote file when contents are different than the source. When set toFalse, the file will only be transferred if the destination does not exist.output_encoding – Overrides the encoding used to write the template file defined by
dest. It defaults toutf-8, but any encoding supported by python can be used. The source template file must always be encoded usingutf-8, for homogeneity.validate – The validation command to run before copying the updated file into the final destination. A temporary file path is used to validate, passed in through
%swhich must be present as in the examples below. Also, the command is passed securely so shell features such as expansion and pipes will not work. For an example on how to handle more complex validation than what this option provides, seehandling complex validation.
- unarchive(*, src: StrPath, dest: StrPath, copy: bool = True, creates: StrPath = ..., io_buffer_size: int = 65536, list_files: bool = False, exclude: Sequence[str] = ..., include: Sequence[str] = ..., keep_newer: bool = False, extra_opts: Sequence[str] = ..., remote_src: bool = False, validate_certs: bool = True, decrypt: bool = True, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) UnarchiveResults
Unpacks an archive after (optionally) copying it from the local machine.
See also
- Parameters:
src – If
remote_src=no(default), local path to archive file to copy to the target server; can be absolute or relative. Ifremote_src=yes, path on the target server to existing archive file to unpack. Ifremote_src=yesandsrccontains://, the remote machine will download the file from the URL first. (version_added 2.0). This is only for simple cases, for full download support use theget_url()method.dest – Remote absolute path where the archive should be unpacked. The given path must exist. Base directory is not created by this module.
copy – If true, the file is copied from local controller to the managed (remote) node, otherwise, the plugin will look for src archive on the managed machine. This option has been deprecated in favor of
remote_src. This option is mutually exclusive withremote_src.creates – If the specified absolute path (file or directory) already exists, this step will not be run. The specified absolute path (file or directory) must be below the base path given with
dest.io_buffer_size – Size of the volatile memory buffer that is used for extracting files from the archive in bytes.
list_files – If set to True, return the list of files that are contained in the tarball.
exclude – List the directory and file entries that you would like to exclude from the unarchive action. Mutually exclusive with
include.include – List of directory and file entries that you would like to extract from the archive. If
includeis not empty, only files listed here will be extracted. Mutually exclusive withexclude.keep_newer – Do not replace existing files that are newer than files from the archive.
extra_opts – Specify additional options by passing in an array. Each space-separated command-line option should be a new element of the array. See examples. Command-line options with multiple elements must use multiple lines in the array, one for each element.
remote_src – Set to
trueto indicate the archived file is already on the remote system and not local to the Ansible controller. This option is mutually exclusive withcopy.validate_certs – This only applies if using a https URL as the source of the file. This should only set to
falseused on personally controlled sites using self-signed certificate. Prior to 2.2 the code worked as if this was set totrue.decrypt – This option controls the auto-decryption of source files using vault.
mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- update_fact(*, updates: Sequence[Mapping[str, Incomplete]]) UpdateFactResults
Update currently set facts.
See also
- Parameters:
updates – A list of dictionaries, each a desired update to make.
- uri(*, ciphers: Sequence[str] = ..., decompress: bool = True, url: str, dest: StrPath = ..., url_username: str = ..., url_password: str = ..., body: str = ..., body_format: Literal['form-urlencoded', 'json', 'raw', 'form-multipart'] = 'raw', method: str = 'GET', return_content: bool = False, force_basic_auth: bool = False, follow_redirects: Literal['all', 'none', 'safe', 'urllib2', 'no', 'yes'] = 'safe', creates: StrPath = ..., removes: StrPath = ..., status_code: Sequence[int] = ..., timeout: int = 30, headers: Mapping[str, Incomplete] = ..., validate_certs: bool = True, client_cert: StrPath = ..., client_key: StrPath = ..., ca_path: StrPath = ..., src: StrPath = ..., remote_src: bool = False, force: bool = False, use_proxy: bool = True, unix_socket: StrPath = ..., http_agent: str = 'ansible-httpget', unredirected_headers: Sequence[str] = ..., use_gssapi: bool = False, use_netrc: bool = True, mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) UriResults
Interacts with webservices.
See also
- Parameters:
ciphers – SSL/TLS Ciphers to use for the request. When a list is provided, all ciphers are joined in order with
:. See the OpenSSL Cipher List Format for more details. The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions. Requires ansible-core >= 2.14decompress – Whether to attempt to decompress gzip content-encoded responses. Requires ansible-core >= 2.14
url – HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path.
dest – A path of where to download the file to (if desired). If
destis a directory, the basename of the file on the remote server will be used.url_username – A username for the module to use for Digest, Basic or WSSE authentication.
url_password – A password for the module to use for Digest, Basic or WSSE authentication.
body – The body of the http request/response to the web service. If
body_formatis set tojsonit will take an already formatted JSON string or convert a data structure into JSON. Ifbody_formatis set toform-urlencodedit will convert a dictionary or list of tuples into anapplication/x-www-form-urlencodedstring. (Added in v2.7). Ifbody_formatis set toform-multipartit will convert a dictionary intomultipart/form-multipartbody. (Added in v2.10).body_format – The serialization format of the body. When set to
json,form-multipart, orform-urlencoded, encodes the body argument, if needed, and automatically sets theContent-Typeheader accordingly. As of v2.3 it is possible to override theContent-Typeheader, when set tojsonorform-urlencodedvia theheadersoption. TheContent-Typeheader cannot be overridden when usingform-multipart.form-urlencodedwas added in v2.7.form-multipartwas added in v2.10.method – The HTTP method of the request or response. In more recent versions we do not restrict the method at the module level anymore but it still must be a valid method accepted by the service handling the request.
return_content – Whether or not to return the body of the response as a “content” key in the dictionary result no matter it succeeded or failed. Independently of this option, if the reported
Content-Typeisapplication/json, then the JSON is always loaded into a key calledignore:jsonin the dictionary results.force_basic_auth – Force the sending of the Basic authentication header upon initial request. When this setting is
false, this module will first try an unauthenticated request, and when the server replies with anHTTP 401error, it will submit the Basic authentication header. When this setting istrue, this module will immediately send a Basic authentication header on the first request. Use this setting in any of the following scenarios:. You know the webservice endpoint always requires HTTP Basic authentication, and you want to speed up your requests by eliminating the first roundtrip. The web service does not properly send an HTTP 401 error to your client, so Ansible’s HTTP library will not properly respond with HTTP credentials, and logins will fail. The webservice bans or rate-limits clients that cause any HTTP 401 errors.follow_redirects – Whether or not the URI module should follow redirects.
creates – A filename, when it already exists, this step will not be run.
removes – A filename, when it does not exist, this step will not be run.
status_code – A list of valid, numeric, HTTP status codes that signifies success of the request.
timeout – The socket level timeout in seconds.
headers – Add custom HTTP headers to a request in the format of a YAML hash. As of Ansible 2.3 supplying
Content-Typehere will override the header generated by supplyingjsonorform-urlencodedforbody_format.validate_certs – If
false, SSL certificates will not be validated. This should only set tofalseused on personally controlled sites using self-signed certificates. Prior to 1.9.2 the code defaulted tofalse.client_cert – PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key as well, and if the key is included,
client_keyis not required.client_key – PEM formatted file that contains your private key to be used for SSL client authentication. If
client_certcontains both the certificate and key, this option is not required.ca_path – PEM formatted file that contains a CA certificate to be used for validation.
src – Path to file to be submitted to the remote server. Cannot be used with
body. Should be used withforce_basic_authto ensure success when the remote end sends a 401.remote_src – If
false, the module will search for thesrcon the controller node. Iftrue, the module will search for thesrcon the managed (remote) node.force – If
truedo not get a cached copy.use_proxy – If
false, it will not use a proxy, even if one is defined in an environment variable on the target hosts.unix_socket – Path to Unix domain socket to use for connection.
http_agent – Header to identify as, generally appears in web server logs.
unredirected_headers – A list of header names that will not be sent on subsequent redirected requests. This list is case insensitive. By default all headers will be redirected. In some cases it may be beneficial to list headers such as
Authorizationhere to avoid potential credential exposure.use_gssapi – Use GSSAPI to perform the authentication, typically this is for Kerberos or Kerberos through Negotiate authentication. Requires the Python library gssapi to be installed. Credentials for GSSAPI can be specified with
url_username/url_passwordor with the GSSAPI env varKRB5CCNAMEthat specified a custom Kerberos credential cache. NTLM authentication is not supported even if the GSSAPI mech for NTLM has been installed.use_netrc – Determining whether to use credentials from
~/.netrcfile. By default.netrcis used with Basic authentication headers. Whenfalse,.netrccredentials are ignored. Requires ansible-core >= 2.14mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- user(*, name: str, uid: int = ..., comment: str = ..., hidden: bool = ..., non_unique: bool = False, seuser: str = ..., group: str = ..., groups: Sequence[str] = ..., append: bool = False, shell: StrPath = ..., home: StrPath = ..., skeleton: str = ..., password: str = ..., state: Literal['absent', 'present'] = 'present', create_home: bool = True, move_home: bool = False, system: bool = False, force: bool = False, remove: bool = False, login_class: str = ..., generate_ssh_key: bool = False, ssh_key_bits: int = ..., ssh_key_type: str = 'rsa', ssh_key_file: StrPath = ..., ssh_key_comment: str = ..., ssh_key_passphrase: str = ..., update_password: Literal['always', 'on_create'] = 'always', expires: float = ..., password_lock: bool = ..., local: bool = False, profile: str = ..., authorization: str = ..., role: str = ..., password_expire_max: int = ..., password_expire_min: int = ..., password_expire_warn: int = ..., umask: str = ..., password_expire_account_disable: int = ..., uid_min: int = ..., uid_max: int = ...) UserResults
Manage user accounts.
See also
Warning
The documentation is referring to the module from ansible.builtin, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – Name of the user to create, remove or modify.
uid – Optionally sets the UID of the user.
comment – Optionally sets the description (aka GECOS) of user account. On macOS, this defaults to the
nameoption.hidden – macOS only, optionally hide the user from the login window and system preferences. The default will be
trueif thesystemoption is used.non_unique – Optionally when used with the
-uoption, this option allows to change the user ID to a non-unique value.seuser – Optionally sets the
seusertypeuser_uon SELinux enabled systems.group – Optionally sets the user’s primary group (takes a group name). On macOS, this defaults to
staff.groups – A list of supplementary groups which the user is also a member of. By default, the user is removed from all other groups. Configure
appendto modify this. When set to an empty string'', the user is removed from all groups except the primary group. Before Ansible 2.3, the only input format allowed was a comma separated string.append – If
true, add the user to the groups specified ingroups. Iffalse, user will only be added to the groups specified ingroups, removing them from all other groups.shell – Optionally set the user’s shell. On macOS, before Ansible 2.5, the default shell for non-system users was
/usr/bin/false. Since Ansible 2.5, the default shell for non-system users on macOS is/bin/bash. On other operating systems, the default shell is determined by the underlying tool invoked by this module. See Notes for a per platform list of invoked tools. From Ansible 2.18, the type is changed to path from str.home – Optionally set the user’s home directory.
skeleton – Optionally set a home skeleton directory. Requires
create_homeoption!.password – If provided, set the user’s password to the provided encrypted hash (Linux) or plain text password (macOS). Linux/Unix/POSIX: Enter the hashed password as the value. See FAQ entry for details on various ways to generate the hash of a password. To create an account with a locked/disabled password on Linux systems, set this to
'!'or'*'. To create an account with a locked/disabled password on OpenBSD, set this to'*************'. OS X/macOS: Enter the cleartext password as the value. Be sure to take relevant security precautions. On macOS, the password specified in thepasswordoption will always be set, regardless of whether the user account already exists or not. When the password is passed as an argument, theuser()method will always return changed totruefor macOS systems. Since macOS no longer provides access to the hashed passwords directly.state – Whether the account should exist or not, taking action if the state is different from what is stated. See this FAQ entry for additional requirements when removing users on macOS systems.
create_home – Unless set to
false, a home directory will be made for the user when the account is created or if the home directory does not exist. Changed fromcreatehometocreate_homein Ansible 2.5.move_home – If set to
truewhen used withhome, attempt to move the user’s old home directory to the specified directory if it isn’t there already and the old home exists.system – When creating an account
state=present, setting this totruemakes the user a system account. This setting cannot be changed on existing users.force – This only affects
state=absent, it forces removal of the user and associated directories on supported platforms. The behavior is the same asuserdel --force, check the man page foruserdelon your system for details and support. When used withgenerate_ssh_key=yesthis forces an existing key to be overwritten.remove – This only affects
state=absent, it attempts to remove directories associated with the user. The behavior is the same asuserdel --remove, check the man page for details and support.login_class – Optionally sets the user’s login class, a feature of most BSD OSs.
generate_ssh_key – Whether to generate a SSH key for the user in question. This will not overwrite an existing SSH key unless used with
force=yes.ssh_key_bits – Optionally specify number of bits in SSH key to create. The default value depends on
ssh-keygen.ssh_key_type – Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present on target host.
ssh_key_file – Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user’s home directory. This parameter defaults to
.ssh/id_rsa.ssh_key_comment – Optionally define the comment for the SSH key.
ssh_key_passphrase – Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase.
update_password –
alwayswill update passwords if they differ.on_createwill only set the password for newly created users.expires – An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD. Since Ansible 2.6 you can remove the expiry time by specifying a negative value. Currently supported on GNU/Linux and FreeBSD.
password_lock – Lock the password (
usermod -L,usermod -U,pw lock). Implementation differs by platform. This option does not always mean the user cannot login using other methods. This option does not disable the user, only lock the password. This must be set tofalsein order to unlock a currently locked password. The absence of this parameter will not unlock a password. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD, OpenBSD.local – Forces the use of “local” command alternatives on platforms that implement it. This is useful in environments that use centralized authentication when you want to manipulate the local users (in other words, it uses
luseraddinstead ofuseradd). This will check/etc/passwdfor an existing account before invoking commands. If the local account database exists somewhere other than/etc/passwd, this setting will not work properly. This requires that the above commands as well as/etc/passwdmust exist on the target host, otherwise it will be a fatal error.profile – Sets the profile of the user. Can set multiple profiles using comma separation. To delete all the profiles, use
profile=''. Currently supported on Illumos/Solaris. Does nothing when used with other platforms.authorization – Sets the authorization of the user. Can set multiple authorizations using comma separation. To delete all authorizations, use
authorization=''. Currently supported on Illumos/Solaris. Does nothing when used with other platforms.role – Sets the role of the user. Can set multiple roles using comma separation. To delete all roles, use
role=''. Currently supported on Illumos/Solaris. Does nothing when used with other platforms.password_expire_max – Maximum number of days between password change. Supported on Linux only.
password_expire_min – Minimum number of days between password change. Supported on Linux only.
password_expire_warn – Number of days of warning before password expires. Supported on Linux only. Requires ansible-core >= 2.16
umask – Sets the umask of the user. Currently supported on Linux. Does nothing when used with other platforms. Requires
localis omitted orfalse.password_expire_account_disable – Number of days after a password expires until the account is disabled. Currently supported on AIX, Linux, NetBSD, OpenBSD. Requires ansible-core >= 2.18
uid_min – Sets the UID_MIN value for user creation. Overwrites /etc/login.defs default value. Currently supported on Linux. Does nothing when used with other platforms. Requires
localis omitted orFalse. Requires ansible-core >= 2.18uid_max – Sets the UID_MAX value for user creation. Overwrites /etc/login.defs default value. Currently supported on Linux. Does nothing when used with other platforms. Requires
localis omitted orFalse. Requires ansible-core >= 2.18
- validate(*, data: str, engine: str = 'ansible.utils.jsonschema', criteria: str) ValidateResults
Validate data with provided criteria.
See also
- Parameters:
data – Data that will be validated against criteria. For the type of data refer to the documentation of individual validate plugins.
engine – The name of the validate plugin to use. The engine value should follow the fully qualified collection name format, that is <org-name>.<collection-name>.<validate-plugin-name>.
criteria – The criteria used for validation of data. For the type of criteria refer to the documentation of individual validate plugins.
- validate_argument_spec(*, argument_spec: str, provided_arguments: str = ...) ValidateArgumentSpecResults
Validate role argument specs.
See also
- Parameters:
argument_spec – A dictionary like AnsibleModule argument_spec. See
argument spec definition.provided_arguments – A dictionary of the arguments that will be validated according to argument_spec.
- wait_for(*, host: str = '127.0.0.1', timeout: int = 300, connect_timeout: int = 5, delay: int = 0, port: int = ..., active_connection_states: Sequence[str] = ..., state: Literal['absent', 'drained', 'present', 'started', 'stopped'] = 'started', path: StrPath = ..., search_regex: str = ..., exclude_hosts: Sequence[str] = ..., sleep: int = 1, msg: str = ...) WaitForResults
Waits for a condition before continuing.
See also
- Parameters:
host – A resolvable hostname or IP address to wait for.
timeout – Maximum number of seconds to wait for, when used with another condition it will force an error. When used without other conditions it is equivalent of just sleeping.
connect_timeout – Maximum number of seconds to wait for a connection to happen before closing and retrying.
delay – Number of seconds to wait before starting to poll.
port – Port number to poll.
pathandportare mutually exclusive parameters.active_connection_states – The list of TCP connection states which are counted as active connections.
state – Either
present,started, orstopped,absent, ordrained. When checking a portstartedwill ensure the port is open,stoppedwill check that it is closed,drainedwill check for active connections. When checking for a file or a search stringpresentorstartedwill ensure that the file or string is present before continuing,absentwill check that file is absent or removed.path – Path to a file on the filesystem that must exist before continuing.
pathandportare mutually exclusive parameters.search_regex – Can be used to match a string in either a file or a socket connection. Defaults to a multiline regex.
exclude_hosts – List of hosts or IPs to ignore when looking for active TCP connections for
drainedstate.sleep – Number of seconds to sleep between checks. Before Ansible 2.3 this was hardcoded to 1 second.
msg – This overrides the normal error message from a failure to meet the required conditions.
- wait_for_connection(*, connect_timeout: int = 5, delay: int = 0, sleep: int = 1, timeout: int = 600) WaitForConnectionResults
Waits until remote system is reachable/usable.
See also
- Parameters:
connect_timeout – Maximum number of seconds to wait for a connection to happen before closing and retrying.
delay – Number of seconds to wait before starting to poll.
sleep – Number of seconds to sleep between checks.
timeout – Maximum number of seconds to wait for.
- win_acl(*, path: str, user: str, state: Literal['absent', 'present'] = 'present', type: Literal['allow', 'deny'], rights: str, inherit: Literal['ContainerInherit', 'ObjectInherit'] = ..., propagation: Literal['InheritOnly', 'None', 'NoPropagateInherit'] = 'None', follow: bool = False) WinAclResults
Set file/directory/registry/certificate permissions for a system user or group.
See also
- Parameters:
path – The path to the file or directory.
user – User or Group to add specified rights to act on src file/folder or registry key.
state – Specify whether to add
presentor removeabsentthe specified access rule.type – Specify whether to allow or deny the rights specified.
rights – The rights/permissions that are to be allowed/denied for the specified user or group for the item at
path. Ifpathis a file or directory, rights can be any right under MSDN FileSystemRights reference. Ifpathis a registry key, rights can be any right under MSDN RegistryRights reference. If path is a certificate key, rights can beReadand/orFullControl. (Added in 2.2.0).inherit – Inherit flags on the ACL rules. Can be specified as a comma separated list, e.g.
ContainerInherit,ObjectInherit. For more information on the choices see MSDN InheritanceFlags enumeration at reference. Defaults toContainerInherit, ObjectInheritfor Directories.propagation – Propagation flag on the ACL rules. For more information on the choices see MSDN PropagationFlags enumeration at reference.
follow – Follow the symlinks and junctions to apply the ACLs to the target instead of the link.
- win_acl_inheritance(*, path: str, state: Literal['absent', 'present'] = 'absent', reorganize: bool = False) WinAclInheritanceResults
Change ACL inheritance.
See also
- Parameters:
path – Path to be used for changing inheritance. Support for registry keys have been added in
ansible.windows>=1.11.0.state – Specify whether to enable present or disable absent ACL inheritance.
reorganize – For
state=absent, indicates if the inherited ACE’s should be copied from the parent. This is necessary (in combination with removal) for a simple ACL instead of using multiple ACE deny entries. Forstate=present, indicates if the inherited ACE’s should be deduplicated compared to the parent. This removes complexity of the ACL structure.
- win_audit_policy_system(*, category: str = ..., subcategory: str = ..., audit_type: Sequence[str]) WinAuditPolicySystemResults
Used to make changes to the system wide Audit Policy.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
category – Single string value for the category you would like to adjust the policy on. Cannot be used with subcategory. You must define one or the other. Changing this setting causes all subcategories to be adjusted to the defined audit_type.
subcategory – Single string value for the subcategory you would like to adjust the policy on. Cannot be used with category. You must define one or the other.
audit_type – The type of event you would like to audit for. Accepts a list. See examples.
- win_audit_rule(*, path: str, user: str, rights: Sequence[str] = ..., inheritance_flags: Sequence[str] = ..., propagation_flags: Literal['None', 'InheritOnly', 'NoPropagateInherit'] = 'None', audit_flags: Sequence[str] = ..., state: Literal['absent', 'present'] = 'present') WinAuditRuleResults
Adds an audit rule to files, folders, or registry keys.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
path – Path to the file, folder, or registry key. Registry paths should be in Powershell format, beginning with an abbreviation for the root such as,
HKLM:\Software.user – The user or group to adjust rules for.
rights – Comma separated list of the rights desired. Only required for adding a rule. If path is a file or directory, rights can be any right under MSDN FileSystemRights reference. If path is a registry key, rights can be any right under MSDN RegistryRights reference.
inheritance_flags – Defines what objects inside of a folder or registry key will inherit the settings. If you are setting a rule on a file, this value has to be changed to
none. For more information on the choices see MSDN PropagationFlags enumeration at reference.propagation_flags – Propagation flag on the audit rules. This value is ignored when the path type is a file. For more information on the choices see MSDN PropagationFlags enumeration at reference.
audit_flags – Defines whether to log on failure, success, or both. To log both define as comma separated list “Success, Failure”.
state – Whether the rule should be
presentorabsent. For absent, only path, user, and state are required. Specifyingabsentwill remove all rules matching the defined user.
- win_auto_logon(*, logon_count: int = ..., username: str = ..., password: str = ..., state: Literal['absent', 'present'] = 'present') WinAutoLogonResults
Adds or Sets auto logon registry keys.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
logon_count – The number of times to do an automatic logon. This count is deremented by Windows everytime an automatic logon is performed. Once the count reaches
0then the automatic logon process is disabled.username – Username to login automatically. Must be set when
state=present. This can be the Netlogon or UPN of a domain account and is automatically parsed to theDefaultUserNameandDefaultDomainNameregistry properties.password – Password to be used for automatic login. Must be set when
state=present. Value of this input will be used as password for username. While this value is encrypted by LSA it is decryptable to any user who is an Administrator on the remote host.state – Whether the registry key should be
presentorabsent.
- win_certificate_info(*, thumbprint: str = ..., store_name: str = 'My', store_location: Literal['CurrentUser', 'LocalMachine'] = 'LocalMachine') WinCertificateInfoResults
Get information on certificates from a Windows Certificate Store.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
thumbprint – The thumbprint as a hex string of a certificate to find. When specified, filters the certificates return value to a single certificate. See the examples for how to format the thumbprint.
store_name – The name of the store to search. See reference for a list of built-in store names.
store_location – The location of the store to search.
- win_certificate_store(*, state: Literal['absent', 'exported', 'present'] = 'present', path: StrPath = ..., thumbprint: str = ..., store_name: str = 'My', store_location: str = 'LocalMachine', store_type: Literal['system', 'service'] = 'system', password: str = ..., key_exportable: bool = True, key_storage: Literal['default', 'machine', 'user'] = 'default', file_type: Literal['der', 'pem', 'pkcs12'] = 'der') WinCertificateStoreResults
Manages the certificate store.
See also
- Parameters:
state – If
present, will ensure that the certificate at path is imported into the certificate store specified. Ifabsent, will ensure that the certificate specified by thumbprint or the thumbprint of the cert at path is removed from the store specified. Ifexported, will ensure the file at path is a certificate specified by thumbprint. When exporting a certificate, if path is a directory then the module will fail, otherwise the file will be replaced if needed.path – The path to a certificate file. This is required when state is
presentorexported. When state isabsentand thumbprint is not specified, the thumbprint is derived from the certificate at this path.thumbprint – The thumbprint as a hex string to either export or remove. See the examples for how to specify the thumbprint.
store_name – The store name to use when importing a certificate or searching for a certificate.
AddressBook: The X.509 certificate store for other users.AuthRoot: The X.509 certificate store for third-party certificate authorities (CAs).CertificateAuthority: The X.509 certificate store for intermediate certificate authorities (CAs).Disallowed: The X.509 certificate store for revoked certificates.My: The X.509 certificate store for personal certificates.Root: The X.509 certificate store for trusted root certificate authorities (CAs).TrustedPeople: The X.509 certificate store for directly trusted people and resources.TrustedPublisher: The X.509 certificate store for directly trusted publishers.store_location – The store location to use when importing a certificate or searching for a certificate. Can be set to
CurrentUserorLocalMachinewhenstore_type=system. Defaults toLocalMachinewhenstore_type=system. Must be set to any service name whenstore_type=service.store_type – The store type to manage. Use
systemto manage locations in the system store,LocalMachineandCurrentUser. Useserviceto manage the store of a service account specified by store_location.password – The password of the pkcs12 certificate key. This is used when reading a pkcs12 certificate file or the password to set when
state=exportedandfile_type=pkcs12. If the pkcs12 file has no password set or no password should be set on the exported file, do not set this option.key_exportable – Whether to allow the private key to be exported. If
false, then this module and other process will only be able to export the certificate and the private key cannot be exported. Used whenstate=presentonly.key_storage – Specifies where Windows will store the private key when it is imported. When set to
default, the default option as set by Windows is used, typicallyuser. When set tomachine, the key is stored in a path accessible by various users. When set touser, the key is stored in a path only accessible by the current user. Used whenstate=presentonly and cannot be changed once imported. See reference for more details.file_type – The file type to export the certificate as when
state=exported.deris a binary ASN.1 encoded file.pemis a base64 encoded file of a der file in the OpenSSL form.pkcs12(also known as pfx) is a binary container that contains both the certificate and private key unlike the other options. Whenpkcs12is set and the private key is not exportable or accessible by the current user, it will throw an exception.
- win_command(*, _raw_params: str = ..., cmd: str = ..., argv: Sequence[str] = ..., creates: StrPath = ..., removes: StrPath = ..., chdir: StrPath = ..., stdin: str = ..., output_encoding_override: str = ...) WinCommandResults
Executes a command on a remote Windows node.
See also
- Parameters:
_raw_params – The
win_commandmodule takes a free form command to run. This is mutually exclusive with thecmdandargvoptions. There is no parameter actually named ‘_raw_params’. See the examples!.cmd – The command and arguments to run. This is mutually exclusive with the
_raw_paramsandargvoptions.argv – A list that contains the executable and arguments to run. The module will attempt to quote the arguments specified based on the Win32 C command-line argument rules. Not all applications use the same quoting rules so the escaping may not work, for those scenarios use
cmdinstead.creates – A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped.
removes – A path or path filter pattern; when the referenced path does not exist on the target host, the task will be skipped.
chdir – Set the specified path as the current working directory before executing a command.
stdin – Set the stdin of the command directly to the specified value.
output_encoding_override – This option overrides the encoding of stdout/stderr output. You can use this option when you need to run a command which ignore the console’s codepage. You should only need to use this option in very rare circumstances. This value can be any valid encoding
Namebased on the output of[System.Text.Encoding]::GetEncodings(). See reference.
- win_computer_description(*, description: str = ..., organization: str = ..., owner: str = ...) WinComputerDescriptionResults
Set windows description, owner and organization.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
description – String value to apply to Windows descripton. Specify value of “” to clear the value.
organization – String value of organization that the Windows is licensed to. Specify value of “” to clear the value.
owner – String value of the persona that the Windows is licensed to. Specify value of “” to clear the value.
- win_copy(*, content: str = ..., decrypt: bool = True, dest: StrPath, backup: bool = False, force: bool = True, local_follow: bool = True, remote_src: bool = False, src: StrPath = ...) WinCopyResults
Copies files to remote locations on windows hosts.
See also
- Parameters:
content – When used instead of
src, sets the contents of a file directly to the specified value. This is for simple values, for anything complex or with formatting please switch to thewin_template()method.decrypt – This option controls the autodecryption of source files using vault.
dest – Remote absolute path where the file should be copied to. If
srcis a directory, this must be a directory too. Use for path separators or \ when in “double quotes”. Ifdestends with then source or the contents of source will be copied to the directory without renaming. Ifdestis a nonexistent path, it will only be created ifdestends with “/” or “", orsrcis a directory. Ifsrcanddestare files and if the parent directory ofdestdoesn’t exist, then the task will fail.backup – Determine whether a backup should be created. When set to
true, create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. No backup is taken whenremote_src=Falseand multiple files are being copied.force – If set to
true, the file will only be transferred if the content is different than destination. If set tofalse, the file will only be transferred if the destination does not exist. If set tofalse, no checksuming of the content is performed which can help improve performance on larger files.local_follow – This flag indicates that filesystem links in the source tree, if they exist, should be followed.
remote_src – If
false, it will search for src at originating/controller machine. Iftrue, it will go to the remote/target machine for the src.src – Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied (including the source folder name) recursively to
dest. If path is a directory and ends with “/”, only the inside contents of that directory are copied to the destination. Otherwise, if it does not end with “/”, the directory itself with all contents is copied. If path is a file and dest ends with “", the file is copied to the folder with the same filename. Required unless usingcontent.
- win_credential(*, alias: str = ..., attributes: Sequence[Mapping[str, Incomplete]] = ..., comment: str = ..., name: str, persistence: Literal['enterprise', 'local'] = 'local', secret: str = ..., secret_format: Literal['base64', 'text'] = 'text', state: Literal['absent', 'present'] = 'present', type: Literal['domain_certificate', 'domain_password', 'generic_certificate', 'generic_password'], update_secret: Literal['always', 'on_create'] = 'always', username: str = ...) WinCredentialResults
Manages Windows Credentials in the Credential Manager.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
alias – Adds an alias for the credential. Typically this is the NetBIOS name of a host if name is set to the DNS name.
attributes – A list of dicts that set application specific attributes for a credential. When set, existing attributes will be compared to the list as a whole, any differences means all attributes will be replaced.
comment – A user defined comment for the credential.
name – The target that identifies the server or servers that the credential is to be used for. If the value can be a NetBIOS name, DNS server name, DNS host name suffix with a wildcard character (
*), a NetBIOS of DNS domain name that contains a wildcard character sequence, or an asterisk. SeeTargetNamein reference for more details on what this value can be. This is used with type to produce a unique credential.persistence – Defines the persistence of the credential. If
local, the credential will persist for all logons of the same user on the same host.enterpriseis the same aslocalbut the credential is visible to the same domain user when running on other hosts and not just localhost.secret – The secret for the credential. When omitted, then no secret is used for the credential if a new credentials is created. When type is a password type, this is the password for username. When type is a certificate type, this is the pin for the certificate.
secret_format – Controls the input type for secret. If
text, secret is a text string that is UTF-16LE encoded to bytes. Ifbase64, secret is a base64 string that is base64 decoded to bytes.state – When
absent, the credential specified by name and type is removed. Whenpresent, the credential specified by name and type is added.type – The type of credential to store. This is used with name to produce a unique credential. When the type is a
domaintype, the credential is used by Microsoft authentication packages like Negotiate. When the type is agenerictype, the credential is not used by any particular authentication package. It is recommended to use adomaintype as only authentication providers can access the secret.update_secret – When
always, the secret will always be updated if they differ. Whenon_create, the secret will only be checked/updated when it is first created. If the secret cannot be retrieved and this is set toalways, the module will always result in a change.username – When type is a password type, then this is the username to store for the credential. When type is a credential type, then this is the thumbprint as a hex string of the certificate to use. When
type=domain_password, this should be in the form of a Netlogon (DOMAINUsername) or a UPN (username@DOMAIN). If using a certificate thumbprint, the certificate must exist in theCurrentUser\Mycertificate store for the executing user.
- win_dhcp_lease(*, type: Literal['reservation', 'lease'] = 'reservation', state: Literal['present', 'absent'] = 'present', ip: str = ..., scope_id: str = ..., mac: str = ..., duration: int = ..., dns_hostname: str = ..., dns_regtype: Literal['aptr', 'a', 'noreg'] = 'aptr', reservation_name: str = ..., description: str = ...) WinDhcpLeaseResults
Manage Windows Server DHCP Leases.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
type – The type of DHCP address. Leases expire as defined by l(duration). When l(duration) is not specified, the server default is used. Reservations are permanent.
state – Specifies the desired state of the DHCP lease or reservation.
ip – The IPv4 address of the client server/computer. This is a required parameter, if l(mac) is not set. Can be used to identify an existing lease/reservation, instead of l(mac).
scope_id – Specifies the scope identifier as defined by the DHCP server. This is a required parameter, if l(state=present) and the reservation or lease doesn’t already exist. Not required if updating an existing lease or reservation.
mac – Specifies the client identifier to be set on the IPv4 address. This is a required parameter, if l(ip) is not set. Windows clients use the MAC address as the client ID. Linux and other operating systems can use other types of identifiers. Can be used to identify an existing lease/reservation, instead of l(ip).
duration – Specifies the duration of the DHCP lease in days. The duration value only applies to l(type=lease). Defaults to the duration specified by the DHCP server configuration. Only applicable to l(type=lease).
dns_hostname – Specifies the DNS hostname of the client for which the IP address lease is to be added.
dns_regtype – Indicates the type of DNS record to be registered by the DHCP. server service for this lease. l(a) results in an A record being registered. l(aptr) results in both A and PTR records to be registered. l(noreg) results in no DNS records being registered.
reservation_name – Specifies the name of the reservation being created. Only applicable to l(type=reservation).
description – Specifies the description for reservation being created. Only applicable to l(type=reservation).
- win_dns_client(*, adapter_names: Sequence[str], dns_servers: Sequence[str]) WinDnsClientResults
Configures DNS lookup on Windows hosts.
See also
- Parameters:
adapter_names – Adapter name or list of adapter names for which to manage DNS settings (‘*’ is supported as a wildcard value). The adapter name used is the connection caption in the Network Control Panel or the InterfaceAlias of
Get-DnsClientServerAddress.dns_servers – Single or ordered list of DNS servers (IPv4 and IPv6 addresses) to configure for lookup. An empty list will configure the adapter to use the DHCP-assigned values on connections where DHCP is enabled, or disable DNS lookup on statically-configured connections. IPv6 DNS servers can only be set on Windows Server 2012 or newer, older hosts can only set IPv4 addresses.
- win_dns_record(*, name: str, port: int = ..., priority: int = ..., state: Literal['absent', 'present'] = 'present', ttl: int = 3600, aging: bool = False, type: Literal['A', 'AAAA', 'CNAME', 'DHCID', 'NS', 'PTR', 'SRV', 'TXT'], value: Sequence[str] = ..., weight: int = ..., zone: str, zone_scope: str = ..., computer_name: str = ...) WinDnsRecordResults
Manage Windows Server DNS records.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – The name of the record.
port – The port number of the record. Required when
type=SRV. Supported only fortype=SRV.priority – The priority number for each service in SRV record. Required when
type=SRV. Supported only fortype=SRV.state – Whether the record should exist or not.
ttl – The “time to live” of the record, in seconds. Ignored when
state=absent. Valid range is 1 - 31557600. Note that an Active Directory forest can specify a minimum TTL, and will dynamically “round up” other values to that minimum.aging – Should aging be activated for the record. If set to
false, the record will be static.type – The type of DNS record to manage.
SRVwas added in the 1.0.0 release of this collection.NSwas added in the 1.1.0 release of this collection.TXTwas added in the 1.6.0 release of this collection.DHCIDwas added in the 1.12.0 release of this collection.value – The value(s) to specify. Required when
state=present. Whentype=PTRonly the partial part of the IP should be given. Multiple values can be passed whentype=NS.weight – Weightage given to each service record in SRV record. Required when
type=SRV. Supported only fortype=SRV.zone – The name of the zone to manage (eg
example.com). The zone must already exist.zone_scope – The name of the zone scope to manage (eg
ScopeAZ). The zone must already exist.computer_name – Specifies a DNS server. You can specify an IP address or any value that resolves to an IP address, such as a fully qualified domain name (FQDN), host name, or NETBIOS name.
- win_dns_zone(*, name: str, type: Literal['primary', 'secondary', 'stub', 'forwarder'] = ..., dynamic_update: Literal['secure', 'none', 'nonsecureandsecure'] = ..., state: Literal['present', 'absent'] = 'present', forwarder_timeout: int = ..., replication: Literal['forest', 'domain', 'legacy', 'none'] = ..., dns_servers: Sequence[str] = ...) WinDnsZoneResults
Manage Windows Server DNS Zones.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – Fully qualified name of the DNS zone.
type – Specifies the type of DNS zone. When l(type=secondary), the DNS server will immediately attempt to perform a zone transfer from the servers in this list. If this initial transfer fails, then the zone will be left in an unworkable state. This module does not verify the initial transfer.
dynamic_update – Specifies how a zone handles dynamic updates. Secure DNS updates are available only for Active Directory-integrated zones. When not specified during new zone creation, Windows will default this to l(none).
state – Specifies the desired state of the DNS zone. When l(state=present) the module will attempt to create the specified DNS zone if it does not already exist. When l(state=absent), the module will remove the specified DNS zone and all subsequent DNS records.
forwarder_timeout – Specifies a length of time, in seconds, that a DNS server waits for a remote DNS server to resolve a query. Accepts integer values between 0 and 15. If the provided value is not valid, it will be omitted and a warning will be issued.
replication – Specifies the replication scope for the DNS zone. l(replication=forest) will replicate the DNS zone to all domain controllers in the Active Directory forest. l(replication=domain) will replicate the DNS zone to all domain controllers in the Active Directory domain. l(replication=none) disables Active Directory integration and creates a local file with the name of the zone. This is the equivalent of selecting l(store the zone in Active Directory) in the GUI.
dns_servers – Specifies an list of IP addresses of the primary servers of the zone. DNS queries for a forwarded zone are sent to primary servers. Required if l(type=secondary), l(type=forwarder) or l(type=stub), otherwise ignored. At least one server is required.
- win_domain(*, dns_domain_name: str, domain_netbios_name: str = ..., safe_mode_password: str, database_path: StrPath = ..., log_path: StrPath = ..., sysvol_path: StrPath = ..., create_dns_delegation: bool = ..., domain_mode: Literal['Win2003', 'Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold'] = ..., forest_mode: Literal['Win2003', 'Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold'] = ..., install_dns: bool = True) WinDomainResults
Ensures the existence of a Windows domain.
See also
- Parameters:
dns_domain_name – The DNS name of the domain which should exist and be reachable or reside on the target Windows host.
domain_netbios_name – The NetBIOS name for the root domain in the new forest. For NetBIOS names to be valid for use with this parameter they must be single label names of 15 characters or less, if not it will fail. If this parameter is not set, then the default is automatically computed from the value of the domain_name parameter.
safe_mode_password – Safe mode password for the domain controller.
database_path – The path to a directory on a fixed disk of the Windows host where the domain database will be created. If not set then the default path is
%SYSTEMROOT%\NTDS.log_path – Specifies the fully qualified, non-UNC path to a directory on a fixed disk of the local computer where the log file for this operation is written. If not set then the default path is
%SYSTEMROOT%\NTDS.sysvol_path – The path to a directory on a fixed disk of the Windows host where the Sysvol file will be created. If not set then the default path is
%SYSTEMROOT%\SYSVOL.create_dns_delegation – Whether to create a DNS delegation that references the new DNS server that you install along with the domain controller. Valid for Active Directory-integrated DNS only. The default is computed automatically based on the environment.
domain_mode – Specifies the domain functional level of the first domain in the creation of a new forest. The domain functional level cannot be lower than the forest functional level, but it can be higher. The default is automatically computed and set.
forest_mode – Specifies the forest functional level for the new forest. The default forest functional level in Windows Server is typically the same as the version you are running.
install_dns – Whether to install the DNS service when creating the domain controller.
- win_domain_controller(*, dns_domain_name: str = ..., domain_admin_user: str, domain_admin_password: str, safe_mode_password: str = ..., local_admin_password: str = ..., read_only: bool = False, site_name: str = ..., state: Literal['domain_controller', 'member_server'], database_path: StrPath = ..., domain_log_path: StrPath = ..., sysvol_path: StrPath = ..., install_media_path: StrPath = ..., install_dns: bool = ..., log_path: str = ...) WinDomainControllerResults
Manage domain controller/member server state for a Windows host.
See also
- Parameters:
dns_domain_name – When
stateisdomain_controller, the DNS name of the domain for which the targeted Windows host should be a DC.domain_admin_user – Username of a domain admin for the target domain (necessary to promote or demote a domain controller).
domain_admin_password – Password for the specified
domain_admin_user.safe_mode_password – Safe mode password for the domain controller (required when
stateisdomain_controller).local_admin_password – Password to be assigned to the local
Administratoruser (required whenstateismember_server).read_only – Whether to install the domain controller as a read only replica for an existing domain.
site_name – Specifies the name of an existing site where you can place the new domain controller. This option is required when read_only is
true.state – Whether the target host should be a domain controller or a member server.
database_path – The path to a directory on a fixed disk of the Windows host where the domain database will be created.. If not set then the default path is
%SYSTEMROOT%\NTDS.domain_log_path – Specified the fully qualified, non-UNC path to a directory on a fixed disk of the local computer that will contain the domain log files.
sysvol_path – The path to a directory on a fixed disk of the Windows host where the Sysvol folder will be created. If not set then the default path is
%SYSTEMROOT%\SYSVOL.install_media_path – The path to a directory on a fixed disk of the Windows host where the Install From Media
IFCdata will be used. See the Install using IFM guide for more information.install_dns – Whether to install the DNS service when creating the domain controller. If not specified then the
-InstallDnsoption is not supplied toInstall-ADDSDomainControllercommand, see reference.log_path – The path to log any debug information when running the module. This option is deprecated and should not be used, it will be removed on the major release after
2022-07-01. This does not relate to the-LogPathparamter of the install controller cmdlet.
- win_domain_membership(*, dns_domain_name: str = ..., domain_admin_user: str, domain_admin_password: str = ..., hostname: str = ..., domain_ou_path: str = ..., state: Literal['domain', 'workgroup'] = ..., workgroup_name: str = ...) WinDomainMembershipResults
Manage domain/workgroup membership for a Windows host.
See also
- Parameters:
dns_domain_name – When
stateisdomain, the DNS name of the domain to which the targeted Windows host should be joined.domain_admin_user – Username of a domain admin for the target domain (required to join or leave the domain).
domain_admin_password – Password for the specified
domain_admin_user.hostname – The desired hostname for the Windows host.
domain_ou_path – The desired OU path for adding the computer object. This is only used when adding the target host to a domain, if it is already a member then it is ignored.
state – Whether the target host should be a member of a domain or workgroup.
workgroup_name – When
stateisworkgroup, the name of the workgroup that the Windows host should be in.
- win_dsc(*, resource_name: str, module_version: str = 'latest') WinDscResults
- win_dsc(arg: str, /) WinDscResults
Invokes a PowerShell DSC configuration.
See also
- Parameters:
resource_name – The name of the DSC Resource to use. Must be accessible to PowerShell using any of the default paths.
module_version – Can be used to configure the exact version of the DSC resource to be invoked. Useful if the target node has multiple versions installed of the module containing the DSC resource. If not specified, the module will follow standard PowerShell convention and use the highest version available.
- win_environment(*, state: Literal['absent', 'present'] = ..., name: str = ..., value: str = ..., variables: Mapping[str, Incomplete] = ..., level: Literal['machine', 'process', 'user']) WinEnvironmentResults
Modify environment variables on windows hosts.
See also
- Parameters:
state – Set to
presentto ensure environment variable is set. Set toabsentto ensure it is removed. When using variables, do not set this option.name – The name of the environment variable. Required when state=absent.
value – The value to store in the environment variable. Must be set when state=present and cannot be an empty string. Should be omitted for state=absent and variables.
variables – A dictionary where multiple environment variables can be defined at once. Not valid when state is set. Variables with a value will be set (
present) and variables with an empty value will be unset (absent). level applies to all vars defined this way.level – The level at which to set the environment variable. Use
machineto set for all users. Useuserto set for the current user that ansible is connected as. Useprocessto set for the current process. Probably not that useful.
- win_eventlog(*, name: str, state: Literal['absent', 'clear', 'present'] = 'present', sources: Sequence[str] = ..., category_file: StrPath = ..., message_file: StrPath = ..., parameter_file: StrPath = ..., maximum_size: str = ..., overflow_action: Literal['DoNotOverwrite', 'OverwriteAsNeeded', 'OverwriteOlder'] = ..., retention_days: int = ...) WinEventlogResults
Manage Windows event logs.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – Name of the event log to manage.
state – Desired state of the log and/or sources. When
sourcesis populated, state is checked for sources. Whensourcesis not populated, state is checked for the specified log itself. Ifstateisclear, event log entries are cleared for the target log.sources – A list of one or more sources to ensure are present/absent in the log. When
category_file,message_fileand/orparameter_fileare specified, these values are applied across all sources.category_file – For one or more sources specified, the path to a custom category resource file.
message_file – For one or more sources specified, the path to a custom event message resource file.
parameter_file – For one or more sources specified, the path to a custom parameter resource file.
maximum_size – The maximum size of the event log. Value must be between 64KB and 4GB, and divisible by 64KB. Size can be specified in KB, MB or GB (e.g. 128KB, 16MB, 2.5GB).
overflow_action – The action for the log to take once it reaches its maximum size. For
DoNotOverwrite, all existing entries are kept and new entries are not retained. ForOverwriteAsNeeded, each new entry overwrites the oldest entry. ForOverwriteOlder, new log entries overwrite those older than theretention_daysvalue.retention_days – The minimum number of days event entries must remain in the log. This option is only used when
overflow_actionisOverwriteOlder.
- win_feature(*, name: Sequence[str], state: Literal['absent', 'present'] = 'present', include_sub_features: bool = False, include_management_tools: bool = False, source: str = ...) WinFeatureResults
Installs and uninstalls Windows Features on Windows Server.
See also
- Parameters:
name – Names of roles or features to install as a single feature or a comma-separated list of features. To list all available features use the PowerShell command
Get-WindowsFeature.state – State of the features or roles on the system.
include_sub_features – Adds all subfeatures of the specified feature.
include_management_tools – Adds the corresponding management tools to the specified feature. Not supported in Windows 2008 R2 and will be ignored.
source – Specify a source to install the feature from. Not supported in Windows 2008 R2 and will be ignored. Can either be
{driveletter}:\sources\sxsor\{IP}\share\sources\sxs.
- win_feature_info(*, name: str = '*') WinFeatureInfoResults
Gather information about Windows features.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – If specified, this is used to match the
nameof the Windows feature to get the info for. Can be a wildcard to match multiple features but the wildcard will only be matched on thenameof the feature. If omitted then all features will returned.
- win_file(*, path: StrPath, state: Literal['absent', 'directory', 'file', 'touch'] = ...) WinFileResults
Creates, touches or removes files or directories.
See also
- Parameters:
path – Path to the file being managed.
state – If
directory, all immediate subdirectories will be created if they do not exist. Iffile, the file will NOT be created if it does not exist, see thewin_copy()orwin_template()method if you want that behavior. Ifabsent, directories will be recursively deleted, and files will be removed. Iftouch, an empty file will be created if thepathdoes not exist, while an existing file or directory will receive updated file access and modification times (similar to the waytouchworks from the command line).
- win_file_compression(*, path: StrPath, state: Literal['absent', 'present'] = 'present', recurse: bool = False, force: bool = True) WinFileCompressionResults
Alters the compression of files and directories on NTFS partitions.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
path – The full path of the file or directory to modify. The path must exist on file system that supports compression like NTFS.
state – Set to
presentto ensure the path is compressed. Set toabsentto ensure the path is not compressed.recurse – Whether to recursively apply changes to all subdirectories and files. This option only has an effect when path is a directory. When set to
false, only applies changes to path. When set totrue, applies changes to path and all subdirectories and files.force – This option only has an effect when recurse is
true. Iftrue, will check the compressed state of all subdirectories and files and make a change if any are different from compressed. Iffalse, will only make a change if the compressed state of path is different from compressed. If the folder structure is complex or contains a lot of files, it is recommended to set this option tofalseso that not every file has to be checked.
- win_find(*, age: str = ..., age_stamp: Literal['atime', 'ctime', 'mtime'] = 'mtime', checksum_algorithm: Literal['md5', 'sha1', 'sha256', 'sha384', 'sha512'] = 'sha1', depth: int = ..., file_type: Literal['directory', 'file'] = 'file', follow: bool = False, get_checksum: bool = True, hidden: bool = False, paths: Sequence[str], patterns: Sequence[str] = ..., recurse: bool = False, size: str = ..., use_regex: bool = False) WinFindResults
Return a list of files based on specific criteria.
See also
- Parameters:
age – Select files or folders whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days or weeks by specifying the first letter of an of those words (e.g., “2s”, “10d”, 1w”).
age_stamp – Choose the file property against which we compare
age. The default attribute we compare with is the last modification time.checksum_algorithm – Algorithm to determine the checksum of a file. Will throw an error if the host is unable to use specified algorithm.
depth – Set the maximum number of levels to descend into. Setting recurse to
falsewill override this value, which is effectively depth 1. Default depth is unlimited.file_type – Type of file to search for.
follow – Set this to
trueto follow symlinks in the path. This needs to be used in conjunction withrecurse.get_checksum – Whether to return a checksum of the file in the return info (default sha1), use
checksum_algorithmto change from the default.hidden – Set this to include hidden files or folders.
paths – List of paths of directories to search for files or folders in. This can be supplied as a single path or a list of paths.
patterns – One or more (powershell or regex) patterns to compare filenames with. The type of pattern matching is controlled by
use_regexoption. The patterns restrict the list of files or folders to be returned based on the filenames. For a file to be matched it only has to match with one pattern in a list provided.recurse – Will recursively descend into the directory looking for files or folders.
size – Select files or folders whose size is equal to or greater than the specified size. Use a negative value to find files equal to or less than the specified size. You can specify the size with a suffix of the byte type i.e. kilo = k, mega = m… Size is not evaluated for symbolic links.
use_regex – Will set patterns to run as a regex check if set to
true.
- win_firewall(*, profiles: Sequence[str] = ..., state: Literal['disabled', 'enabled'], inbound_action: Literal['allow', 'block', 'not_configured'] = ..., outbound_action: Literal['allow', 'block', 'not_configured'] = ...) WinFirewallResults
Enable or disable the Windows Firewall.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
profiles – Specify one or more profiles to change.
state – Set state of firewall for given profile.
inbound_action – Set to
alloworblockinbound network traffic in the profile.not_configuredis valid when configuring a GPO.outbound_action – Set to
alloworblockinbound network traffic in the profile.not_configuredis valid when configuring a GPO.
- win_get_url(*, url: str, dest: StrPath, force: bool = True, checksum: str = ..., checksum_algorithm: Literal['md5', 'sha1', 'sha256', 'sha384', 'sha512'] = 'sha1', checksum_url: str = ..., url_method: str = ..., url_timeout: int = 30, follow_redirects: Literal['all', 'none', 'safe'] = 'safe', headers: Mapping[str, Incomplete] = ..., http_agent: str = 'ansible-httpget', maximum_redirection: int = 50, validate_certs: bool = True, client_cert: str = ..., client_cert_password: str = ..., force_basic_auth: bool = False, url_username: str = ..., url_password: str = ..., use_default_credential: bool = False, use_proxy: bool = True, proxy_url: str = ..., proxy_username: str = ..., proxy_password: str = ..., proxy_use_default_credential: bool = False) WinGetUrlResults
Downloads file from HTTP, HTTPS, or FTP to node.
See also
- Parameters:
url – The full URL of a file to download.
dest – The location to save the file at the URL. Be sure to include a filename and extension as appropriate.
force – If
true, will download the file every time and replace the file if the contents change. Iffalse, will only download the file if it does not exist or the remote file has been modified more recently than the local file. This works by sending an http HEAD request to retrieve last modified time of the requested resource, so for this to work, the remote web server must support HEAD requests.checksum – If a checksum is passed to this parameter, the digest of the destination file will be calculated after it is downloaded to ensure its integrity and verify that the transfer completed successfully. If a checksum is passed in this parameter or via
checksum_urland the file indestexists thenchecksum_destis calculated. Ifchecksum_destequals the checksum no download is done unlessforceistrue. If the checksum does not match the file is always downloaded, as ifforcewas set. This behaviour was added in the2.7.0release of this collection. This option cannot be set with checksum_url.checksum_algorithm – Specifies the hashing algorithm used when calculating the checksum of the remote and destination file.
checksum_url – Specifies a URL that contains the checksum values for the resource at url. Like
checksum, this is used to verify the integrity of the remote transfer. This option cannot be set with checksum.url_method – The HTTP Method of the request.
url_timeout – Specifies how long the request can be pending before it times out (in seconds). Set to
0to specify an infinite timeout.follow_redirects – Whether or the module should follow redirects.
allwill follow all redirect.nonewill not follow any redirect.safewill follow only “safe” redirects, where “safe” means that the client is only doing aGETorHEADon the URI to which it is being redirected. When following a redirected URL, theAuthorizationheader and any credentials set will be dropped and not redirected.headers – Extra headers to set on the request. This should be a dictionary where the key is the header name and the value is the value for that header.
http_agent – Header to identify as, generally appears in web server logs. This is set to the
User-Agentheader on a HTTP request.maximum_redirection – Specify how many times the module will redirect a connection to an alternative URI before the connection fails. If set to
0or follow_redirects is set tonone, orsafewhen not doing aGETorHEADit prevents all redirection.validate_certs – If
False, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.client_cert – The path to the client certificate (.pfx) that is used for X509 authentication. This path can either be the path to the
pfxon the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>. The WinRM connection must be authenticated withCredSSPorbecomeis used on the task if the certificate file is not password protected. Other authentication types can set client_cert_password when the cert is password protected.client_cert_password – The password for client_cert if the cert is password protected.
force_basic_auth – By default the authentication header is only sent when a webservice responses to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon the original request.
url_username – The username to use for authentication.
url_password – The password for url_username.
use_default_credential – Uses the current user’s credentials when authenticating with a server protected with
NTLM,Kerberos, orNegotiateauthentication. Sites that useBasicauth will still require explicit credentials through the url_username and url_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no authentication will occur.use_proxy – If
False, it will not use the proxy defined in IE for the current user.proxy_url – An explicit proxy to use for the request. By default, the request will use the IE defined proxy unless use_proxy is set to
False.proxy_username – The username to use for proxy authentication.
proxy_password – The password for proxy_username.
proxy_use_default_credential – Uses the current user’s credentials when authenticating with a proxy host protected with
NTLM,Kerberos, orNegotiateauthentication. Proxies that useBasicauth will still require explicit credentials through the proxy_username and proxy_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no proxy authentication will occur.
- win_group(*, name: str, description: str = ..., members: Mapping[str, Incomplete] = ..., state: Literal['absent', 'present'] = 'present') WinGroupResults
Add and remove local groups.
See also
- Parameters:
name – Name of the group.
description – Description of the group. Set to an empty string
""to unset the description.members – The members of the group to set. The value is a dictionary that contains 3 keys, add, remove, or set. Each subkey value is a list of users or domain groups to add, remove, or set respectively. The members can either be the username in the form of
SERVER\user,DOMAIN\user,.\userto represent a local user, a UPNuser@DOMAIN.COM, or a security identifierS-1-5-..... A local group member cannot be another local group, it must be either a local user, domain user, or a domain group. The add and remove keys can be set together but set can only be set by itself.state – Create or remove the group.
- win_group_membership(*, name: str, members: Sequence[str], state: Literal['absent', 'present', 'pure'] = 'present') WinGroupMembershipResults
Manage Windows local group membership.
See also
- Parameters:
name – Name of the local group to manage membership on.
members – A list of members to ensure are present/absent from the group. Accepts local users as .username, and SERVERNAMEusername. Accepts domain users and groups as DOMAINusername and username@DOMAIN. Accepts service users as NT AUTHORITYusername. Accepts all local, domain and service user types as username, favoring domain lookups when in a domain.
state – Desired state of the members in the group. When
stateispure, only the members specified will exist, and all other existing members not specified are removed.
- win_hostname(*, name: str) WinHostnameResults
Manages local Windows computer name.
See also
- Parameters:
name – The hostname to set for the computer.
- win_hosts(*, state: Literal['absent', 'present'] = 'present', canonical_name: str = ..., ip_address: str = ..., aliases: Sequence[str] = ..., action: Literal['add', 'remove', 'set'] = 'set') WinHostsResults
Manages hosts file entries on Windows.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
state – Whether the entry should be present or absent. If only canonical_name is provided when
state=absent, then all hosts entries with the canonical name of canonical_name will be removed. If only ip_address is provided whenstate=absent, then all hosts entries with the ip address of ip_address will be removed. If ip_address and canonical_name are both omitted whenstate=absent, then all hosts entries will be removed.canonical_name – A canonical name for the host entry. required for
state=present.ip_address – The ip address for the host entry. Can be either IPv4 (A record) or IPv6 (AAAA record). Required for
state=present.aliases – A list of additional names (cname records) for the host entry. Only applicable when
state=present.action – Controls the behavior of aliases. Only applicable when
state=present. Ifadd, each alias in aliases will be added to the host entry. Ifset, each alias in aliases will be added to the host entry, and other aliases will be removed from the entry.
- win_hotfix(*, hotfix_identifier: str = ..., hotfix_kb: str = ..., state: Literal['absent', 'present'] = 'present', source: StrPath = ...) WinHotfixResults
Install and uninstalls Windows hotfixes.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
hotfix_identifier – The name of the hotfix as shown in DISM, see examples for details. This or
hotfix_kbMUST be set whenstate=absent. Ifstate=presentthen the hotfix atsourcewill be validated against this value, if it does not match an error will occur. You can get the identifier by running ‘Get-WindowsPackage -Online -PackagePath path-to-cab-in-msu’ after expanding the msu file.hotfix_kb – The name of the KB the hotfix relates to, see examples for details. This or
hotfix_identifierMUST be set whenstate=absent. Ifstate=presentthen the hotfix atsourcewill be validated against this value, if it does not match an error will occur. Because DISM uses the identifier as a key and doesn’t refer to a KB in all cases it is recommended to usehotfix_identifierinstead.state – Whether to install or uninstall the hotfix. When
present,sourceMUST be set. Whenabsent,hotfix_identifierorhotfix_kbMUST be set.source – The path to the downloaded hotfix .msu file. This MUST be set if
state=presentand MUST be a .msu hotfix file.
- win_http_proxy(*, bypass: Sequence[str] = ..., proxy: str = ..., source: Literal['ie'] = ...) WinHttpProxyResults
Manages proxy settings for WinHTTP.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
bypass – A list of hosts that will bypass the set proxy when being accessed. Use
<local>to match hostnames that are not fully qualified domain names. This is useful when needing to connect to intranet sites using just the hostname. Omit, set to null or an empty string/list to remove the bypass list. If this is set then proxy must also be set.proxy – A string or dict that specifies the proxy to be set. If setting a string, should be in the form
hostname,hostname:port, orprotocol=hostname:port. If the port is undefined, the default port for the protocol in use is used. If setting a dict, the keys should be the protocol and the values should be the hostname and/or port for that protocol. Valid protocols arehttp,https,ftp, andsocks. Omit, set to null or an empty string to remove the proxy settings.source – Instead of manually specifying the proxy and/or bypass, set this to import the proxy from a set source like Internet Explorer. Using
iewill import the Internet Explorer proxy settings for the current active network connection of the current user. Only IE’s proxy URL and bypass list will be imported into WinHTTP. This is like runningnetsh winhttp import proxy source=ie. The value is imported when the module runs and will not automatically be updated if the IE configuration changes in the future. The module will have to be run again to sync the latest changes.
- win_inet_proxy(*, auto_detect: bool = True, auto_config_url: str = ..., bypass: Sequence[str] = ..., connection: str = ..., proxy: str = ...) WinInetProxyResults
Manages proxy settings for WinINet and Internet Explorer.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
auto_detect – Whether to configure WinINet to automatically detect proxy settings through Web Proxy Auto-Detection
WPAD. This corresponds to the checkbox Automatically detect settings in the connection settings window.auto_config_url – The URL of a proxy configuration script. Proxy configuration scripts are typically JavaScript files with the
.pacextension that implement theFindProxyForURL(url, hostfunction. Omit, set to null or an empty string to remove the auto config URL. This corresponds to the checkbox Use automatic configuration script in the connection settings window.bypass – A list of hosts that will bypass the set proxy when being accessed. Use
<local>to match hostnames that are not fully qualified domain names. This is useful when needing to connect to intranet sites using just the hostname. If defined, this should be the last entry in the bypass list. Use<-loopback>to stop automatically bypassing the proxy when connecting through any loopback address like127.0.0.1,localhost, or the local hostname. Omit, set to null or an empty string/list to remove the bypass list. If this is set then proxy must also be set.connection – The name of the IE connection to set the proxy settings for. These are the connections under the Dial-up and Virtual Private Network header in the IE settings. When omitted, the default LAN connection is used.
proxy – A string or dict that specifies the proxy to be set. If setting a string, should be in the form
hostname,hostname:port, orprotocol=hostname:port. If the port is undefined, the default port for the protocol in use is used. If setting a dict, the keys should be the protocol and the values should be the hostname and/or port for that protocol. Valid protocols arehttp,https,ftp, andsocks. Omit, set to null or an empty string to remove the proxy settings.
- win_listen_ports_facts(*, date_uformat: str = '%c', tcp_filter: Sequence[str] = ...) WinListenPortsFactsResults
Recopilates the facts of the listening ports of the machine.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
date_uformat – The format of the date when the process that owns the port started. The date specification is UFormat.
tcp_filter – Filter for the state of the TCP ports that will be recopilated. Supports multiple states (Bound, Closed, CloseWait, Closing, DeleteTCB, Established, FinWait1, FinWait2, LastAck, Listen, SynReceived, SynSent and TimeWait), that can be used alone or combined. Note that the Bound state is only available on PowerShell version 4.0 or later.
- win_mapped_drive(*, letter: str, password: str = ..., path: StrPath = ..., state: Literal['absent', 'present'] = 'present', username: str = ...) WinMappedDriveResults
Map network drives for users.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
letter – The letter of the network path to map to. This letter must not already be in use with Windows.
password – The password for
usernamethat is used when testing the initial connection. This is never saved with a mapped drive, use thewin_credential()method to persist a username and password for a host.path – The UNC path to map the drive to. If pointing to a WebDAV location this must still be in a UNC path in the format
\hostname\pathand not a URL, see examples for more details. To specify ahttpsWebDAV path, add@SSLafter the hostname. To specify a custom WebDAV port add@<port num>after the@SSLor hostname portion of the UNC path, e.g.\server@SSL@1234or\server@1234. This is required ifstate=present. Ifstate=absentand path is not set, the module will delete the mapped drive regardless of the target. Ifstate=absentand the path is set, the module will throw an error if path does not match the target of the mapped drive.state – If
presentwill ensure the mapped drive exists. Ifabsentwill ensure the mapped drive does not exist.username – The username that is used when testing the initial connection. This is never saved with a mapped drive, the
win_credential()method to persist a username and password for a host. This is required if the mapped drive requires authentication with custom credentials and become, or CredSSP cannot be used. If become or CredSSP is used, any credentials saved withwin_credential()will automatically be used instead.
- win_optional_feature(*, name: Sequence[str], state: Literal['absent', 'present'] = 'present', include_parent: bool = False, source: str = ...) WinOptionalFeatureResults
Manage optional Windows features.
See also
- Parameters:
name – The name(s) of the feature to install. This relates to
FeatureNamein the Powershell cmdlet. To list all available features use the PowerShell commandGet-WindowsOptionalFeature.state – Whether to ensure the feature is absent or present on the system.
include_parent – Whether to enable the parent feature and the parent’s dependencies.
source – Specify a source to install the feature from. Can either be
{driveletter}:\sources\sxsor\{IP}\share\sources\sxs.
- win_owner(*, path: StrPath, user: str, recurse: bool = False) WinOwnerResults
Set owner.
See also
- Parameters:
path – Path to be used for changing owner.
user – Name to be used for changing owner. This value can be in the form of a SecurityIdentifier string, a user or group in the Netlogon
DOMAIN\Useror UPN format (user@DOMAIN.COM).recurse – Indicates if the owner should be changed recursively.
- win_package(*, arguments: str = ..., chdir: StrPath = ..., checksum: str = ..., checksum_algorithm: Literal['md5', 'sha1', 'sha256', 'sha384', 'sha512'] = 'sha1', creates_path: StrPath = ..., creates_service: str = ..., creates_version: str = ..., expected_return_code: Sequence[int] = ..., log_path: StrPath = ..., path: str = ..., product_id: str = ..., provider: Literal['auto', 'msi', 'msix', 'msp', 'registry'] = 'auto', state: Literal['absent', 'present'] = 'present', wait_for_children: bool = False, url_method: str = ..., follow_redirects: Literal['all', 'none', 'safe'] = 'safe', headers: Mapping[str, Incomplete] = ..., http_agent: str = 'ansible-httpget', maximum_redirection: int = 50, url_timeout: int = 30, validate_certs: bool = True, client_cert: str = ..., client_cert_password: str = ..., force_basic_auth: bool = False, url_username: str = ..., url_password: str = ..., use_default_credential: bool = False, use_proxy: bool = True, proxy_url: str = ..., proxy_username: str = ..., proxy_password: str = ..., proxy_use_default_credential: bool = False) WinPackageResults
Installs/uninstalls an installable package.
See also
- Parameters:
arguments – Any arguments the installer needs to either install or uninstall the package. If the package is an MSI do not supply the
/qn,/logor/norestartarguments. This is only used for themsi,msp, andregistryproviders. Can be a list of arguments and the module will escape the arguments as necessary, it is recommended to use a string when dealing with MSI packages due to the unique escaping issues with msiexec. When using a list of arguments each item in the list is considered to be a single argument. As such, if an argument in the list contains a space then Ansible will quote this to ensure that this is seen by Windows as a single argument. Should this behaviour not be what is required, the argument should be split into two separate list items. See the examples section for more detail.chdir – Set the specified path as the current working directory before installing or uninstalling a package. This is only used for the
msi,msp, andregistryproviders.checksum – If a checksum is passed to this parameter, the digest of the package will be calculated before executing it to verify that the path or downloaded file has the expected contents.
checksum_algorithm – Specifies the hashing algorithm used when calculating the checksum of the path provided.
creates_path – Will check the existence of the path specified and use the result to determine whether the package is already installed. You can use this in conjunction with
product_idand othercreates_*.creates_service – Will check the existing of the service specified and use the result to determine whether the package is already installed. You can use this in conjunction with
product_idand othercreates_*.creates_version – Will check the file version property of the file at
creates_pathand use the result to determine whether the package is already installed.creates_pathMUST be set and is a file. You can use this in conjunction withproduct_idand othercreates_*.expected_return_code – One or more return codes from the package installation that indicates success. The return codes are read as a signed integer, any values greater than 2147483647 need to be represented as the signed equivalent, i.e.
4294967295is-1. To convert a unsigned number to the signed equivalent you can run “[Int32](“0x{0:X}” -f ([UInt32]3221225477))”. A return code of3010usually means that a reboot is required, thereboot_requiredreturn value is set if the return code is3010. This is only used for themsi,msp, andregistryproviders.log_path – Specifies the path to a log file that is persisted after a package is installed or uninstalled. This is only used for the
msiormspprovider. When omitted, a temporary log file is used instead for those providers. This is only valid for MSI files, useargumentsfor theregistryprovider.path – Location of the package to be installed or uninstalled. This package can either be on the local file system, network share or a url. When
state=present,product_idis not set and the path is a URL, this file will always be downloaded to a temporary directory for idempotency checks, otherwise the file will only be downloaded if the package has not been installed based on theproduct_idchecks. Ifstate=presentthen this value MUST be set. Ifstate=absentthen this value does not need to be set ifproduct_idis.product_id – The product id of the installed packaged. This is used for checking whether the product is already installed and getting the uninstall information if
state=absent. For msi packages, this is theProductCode(GUID) of the package. This can be found under the same registry paths as theregistryprovider. For msp packages, this is thePatchCode(GUID) of the package which can found under theDetails -> Revision numberof the file’s properties. For msix packages, this is theNameorPackageFullNameof the package found under theGet-AppxPackagecmdlet. For registry (exe) packages, this is the registry key name under the registry paths specified in provider. This value is ignored ifpathis set to a local accesible file path and the package is not anexe. This SHOULD be set when the package is anexe, or the path is a url or a network share and credential delegation is not being used. Thecreates_*options can be used instead but is not recommended.provider – Set the package provider to use when searching for a package. The
autoprovider will select the proper provider if path otherwise it scans all the other providers based on the product_id. Themsiprovider scans for MSI packages installed on a machine wide and current user context based on theProductCodeof the MSI. Themsixprovider is used to install.appx,.msix,.appxbundle, or.msixbundlepackages. These packages are only installed or removed on the current use. The host must be set to allow sideloaded apps or in developer mode. See the examples for how to enable this. If a package is already installed butpathpoints to an updated package, this will be installed over the top of the existing one. Themspprovider scans for all MSP patches installed on a machine wide and current user context based on thePatchCodeof the MSP. Amspwill be applied or removed on allmsiproducts that it applies to and is installed. If the patch is obsoleted or superseded then no action will be taken. Theregistryprovider is used for traditionalexeinstallers and uses the following registry path to determine if a product was installed;HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall,HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall,HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall, andHKCU:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall.state – Whether to install or uninstall the package. The module uses product_id to determine whether the package is installed or not. For all providers but
auto, the path can be used for idempotency checks if it is locally accesible filesystem path.wait_for_children – The module will wait for the process it spawns to finish but any processes spawned in that child process as ignored. Set to
trueto wait for all descendent processes to finish before the module returns. This is useful if the install/uninstaller is just a wrapper which then calls the actual installer as its own child process. When this option istruethen the module will wait for both processes to finish before returning. This should not be required for most installers and setting totruecould result in the module not returning until the process it is waiting for has been stopped manually. Requires Windows Server 2012 or Windows 8 or newer to use.url_method – The HTTP Method of the request.
follow_redirects – Whether or the module should follow redirects.
allwill follow all redirect.nonewill not follow any redirect.safewill follow only “safe” redirects, where “safe” means that the client is only doing aGETorHEADon the URI to which it is being redirected. When following a redirected URL, theAuthorizationheader and any credentials set will be dropped and not redirected.headers – Extra headers to set on the request. This should be a dictionary where the key is the header name and the value is the value for that header.
http_agent – Header to identify as, generally appears in web server logs. This is set to the
User-Agentheader on a HTTP request.maximum_redirection – Specify how many times the module will redirect a connection to an alternative URI before the connection fails. If set to
0or follow_redirects is set tonone, orsafewhen not doing aGETorHEADit prevents all redirection.url_timeout – Specifies how long the request can be pending before it times out (in seconds). Set to
0to specify an infinite timeout.validate_certs – If
False, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.client_cert – The path to the client certificate (.pfx) that is used for X509 authentication. This path can either be the path to the
pfxon the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>. The WinRM connection must be authenticated withCredSSPorbecomeis used on the task if the certificate file is not password protected. Other authentication types can set client_cert_password when the cert is password protected.client_cert_password – The password for client_cert if the cert is password protected.
force_basic_auth – By default the authentication header is only sent when a webservice responses to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon the original request.
url_username – The username to use for authentication.
url_password – The password for url_username.
use_default_credential – Uses the current user’s credentials when authenticating with a server protected with
NTLM,Kerberos, orNegotiateauthentication. Sites that useBasicauth will still require explicit credentials through the url_username and url_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no authentication will occur.use_proxy – If
False, it will not use the proxy defined in IE for the current user.proxy_url – An explicit proxy to use for the request. By default, the request will use the IE defined proxy unless use_proxy is set to
False.proxy_username – The username to use for proxy authentication.
proxy_password – The password for proxy_username.
proxy_use_default_credential – Uses the current user’s credentials when authenticating with a proxy host protected with
NTLM,Kerberos, orNegotiateauthentication. Proxies that useBasicauth will still require explicit credentials through the proxy_username and proxy_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no proxy authentication will occur.
- win_path(*, name: str = 'PATH', elements: Sequence[str], state: Literal['absent', 'present'] = 'present', scope: Literal['machine', 'user'] = 'machine') WinPathResults
Manage Windows path environment variables.
See also
- Parameters:
name – Target path environment variable name.
elements – A single path element, or a list of path elements (ie, directories) to add or remove. When multiple elements are included in the list (and
stateispresent), the elements are guaranteed to appear in the same relative order in the resultant path value. Variable expansions (eg,%VARNAME%) are allowed, and are stored unexpanded in the target path element. Any existing path elements not mentioned inelementsare always preserved in their current order. New path elements are appended to the path, and existing path elements may be moved closer to the end to satisfy the requested ordering. Paths are compared in a case-insensitive fashion, and trailing backslashes are ignored for comparison purposes. However, note that trailing backslashes in YAML require quotes.state – Whether the path elements specified in
elementsshould be present or absent.scope – The level at which the environment variable specified by
nameshould be managed (either for the current user or global machine scope).
- win_ping(*, data: str = 'pong') WinPingResults
A windows version of the classic ping module.
See also
- Parameters:
data – Alternate data to return instead of ‘pong’. If this parameter is set to
crash, the module will cause an exception.
- win_powershell(*, arguments: Sequence[str] = ..., chdir: str = ..., creates: str = ..., depth: int = 2, error_action: Literal['silently_continue', 'continue', 'stop'] = 'continue', executable: str = ..., parameters: Mapping[str, Incomplete] = ..., removes: str = ..., script: str, sensitive_parameters: Sequence[Mapping[str, Incomplete]] = ...) WinPowershellResults
Run PowerShell scripts.
See also
- Parameters:
arguments – A list of arguments to pass to executable when running a script in another PowerShell process. These are not arguments to pass to script, use parameters for that purpose.
chdir – The PowerShell location to set when starting the script. This can be a location in any of the PowerShell providers. The default location is dependent on many factors, if relative paths are used then set this option.
creates – A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped.
depth – How deep the return values are serialized for
result,output, andinformation[x].message_data. This also controls the depth of the diff output set by$Ansible.Diff. Setting this to a higher value can dramatically increase the amount of data that needs to be returned.error_action – The
$ErrorActionPreferenceto set before executing script.silently_continuewill ignore any errors and exceptions raised.continueis the default behaviour in PowerShell, errors are present in the error return value but only terminating exceptions will stop the script from continuing and set it as failed.stopwill treat errors like exceptions, will stop the script and set it as failed.executable – A custom PowerShell executable to run the script in. When not defined the script will run in the current module PowerShell interpreter. Both the remote PowerShell and the one specified by executable must be running on PowerShell v5.1 or newer. Setting this value may change the values returned in the
outputreturn value depending on the underlying .NET type.parameters – Parameters to pass into the script as key value pairs. The key corresponds to the parameter name and the value is the value for that parameter.
removes – A path or path filter pattern; when the referenced path does not exist on the target host, the task will be skipped.
script – The PowerShell script to run.
sensitive_parameters – Parameters to pass into the script as a SecureString or PSCredential. Each sensitive value will be marked with
no_logto ensure they are not exposed in the module invocation args logs. The value suboption can be used to create a SecureString value while username and password can be used to create a PSCredential value.
- win_product_facts() WinProductFactsResults
Provides Windows product and license information.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- win_reboot(*, pre_reboot_delay: int | float = 2, post_reboot_delay: int | float = 0, reboot_timeout: int | float = 600, connect_timeout: int | float = 5, test_command: str = ..., msg: str = ..., boot_time_command: str = ...) WinRebootResults
Reboot a windows machine.
See also
- Parameters:
pre_reboot_delay – Seconds to wait before reboot. Passed as a parameter to the reboot command. The minimum version is
2seconds and cannot be set lower.post_reboot_delay – Seconds to wait after the reboot command was successful before attempting to validate the system rebooted successfully. This is useful if you want wait for something to settle despite your connection already working.
reboot_timeout – Maximum seconds to wait for machine to re-appear on the network and respond to a test command. This timeout is evaluated separately for both reboot verification and test command success so maximum clock time is actually twice this value.
connect_timeout – Maximum seconds to wait for a single successful TCP connection to the WinRM endpoint before trying again.
test_command – Command to expect success for to determine the machine is ready for management. By default this test command is a custom one to detect when the Windows Logon screen is up and ready to accept credentials. Using a custom command will replace this behaviour and just run the command specified.
msg – Message to display to users.
boot_time_command – Command to run that returns a unique string indicating the last time the system was booted. Setting this to a command that has different output each time it is run will cause the task to fail.
- win_reg_stat(*, path: str, name: str = ...) WinRegStatResults
Get information about Windows registry keys.
See also
- Parameters:
path – The full registry key path including the hive to search for.
name – The registry property name to get information for, the return json will not include the sub_keys and properties entries for the key specified. Set to an empty string to target the registry key’s
(Default) property value.
- win_regedit(*, path: str, name: str = ..., data: str = ..., type: Literal['none', 'binary', 'dword', 'expandstring', 'multistring', 'string', 'qword'] = 'string', state: Literal['absent', 'present'] = 'present', delete_key: bool = True, hive: StrPath = ...) WinRegeditResults
Add, change, or remove registry keys and values.
See also
- Parameters:
path – Name of the registry path. Should be in one of the following registry hives: HKCC, HKCR, HKCU, HKLM, HKU.
name – Name of the registry entry in the above
pathparameters. If not provided, or empty then the ‘(Default)’ property for the key will be used.data – Value of the registry entry
nameinpath. If not specified then the value for the property will be null for the correspondingtype. Binary and None data should be expressed in a yaml byte array or as comma separated hex values. An easy way to generate this is to runregedit.exeand use the export option to save the registry values to a file. In the exported file, binary value will look likehex:be,ef,be,ef, thehex:prefix is optional. DWORD and QWORD values should either be represented as a decimal number or a hex value. Multistring values should be passed in as a list. See the examples for more details on how to format this data.type – The registry value data type.
state – The state of the registry entry.
delete_key – When
stateis ‘absent’ then this will delete the entire key. Iffalsethen it will only clear out the ‘(Default)’ property for that key.hive – A path to a hive key like C:UsersDefaultNTUSER.DAT to load in the registry. This hive is loaded under the HKLM:ANSIBLE key which can then be used in name like any other path. This can be used to load the default user profile registry hive or any other hive saved as a file. Using this function requires the user to have the
SeRestorePrivilegeandSeBackupPrivilegeprivileges enabled.
- win_region(*, location: str = ..., format: str = ..., unicode_language: str = ..., copy_settings: bool = False) WinRegionResults
Set the region and format settings.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
location – The location to set for the current user, see reference for a list of GeoIDs you can use and what location it relates to. This needs to be set if
formatorunicode_languageis not set.format – The language format to set for the current user, see reference for a list of culture names to use. This needs to be set if
locationorunicode_languageis not set.unicode_language – The unicode language format to set for all users, see reference for a list of culture names to use. This needs to be set if
locationorformatis not set. After setting this value a reboot is required for it to take effect.copy_settings – This will copy the current format and location values to new user profiles and the welcome screen. This will only run if
location,formatorunicode_languagehas resulted in a change. If this process runs then it will always result in a change.
- win_route(*, destination: str, gateway: str = '0.0.0.0', metric: int = 1, state: Literal['absent', 'present'] = 'present') WinRouteResults
Add or remove a static route.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
destination – Destination IP address in CIDR format (ip address/prefix length).
gateway – The gateway used by the static route. If
gatewayis not provided it will be set to0.0.0.0.metric – Metric used by the static route.
state – If
absent, it removes a network static route. Ifpresent, it adds a network static route.
- win_service(*, dependencies: Sequence[str] = ..., dependency_action: Literal['add', 'remove', 'set'] = 'set', desktop_interact: bool = False, description: str = ..., display_name: str = ..., error_control: Literal['critical', 'ignore', 'normal', 'severe'] = ..., failure_actions: Sequence[Mapping[str, Incomplete]] = ..., failure_actions_on_non_crash_failure: bool = ..., failure_command: str = ..., failure_reboot_msg: str = ..., failure_reset_period_sec: str = ..., force_dependent_services: bool = False, load_order_group: str = ..., name: str, path: str = ..., password: str = ..., pre_shutdown_timeout_ms: str = ..., required_privileges: Sequence[str] = ..., service_type: Literal['user_own_process', 'user_share_process', 'win32_own_process', 'win32_share_process'] = ..., sid_info: Literal['none', 'restricted', 'unrestricted'] = ..., start_mode: Literal['auto', 'delayed', 'disabled', 'manual'] = ..., state: Literal['absent', 'paused', 'started', 'stopped', 'restarted'] = ..., update_password: Literal['always', 'on_create'] = ..., username: str = ...) WinServiceResults
Manage and query Windows services.
See also
- Parameters:
dependencies – A list of service dependencies to set for this particular service. This should be a list of service names and not the display name of the service. This works by
dependency_actionto either add/remove or set the services in this list.dependency_action – Used in conjunction with
dependencyto either add the dependencies to the existing service dependencies. Remove the dependencies to the existing dependencies. Set the dependencies to only the values in the list replacing the existing dependencies.desktop_interact – Whether to allow the service user to interact with the desktop. This can only be set to
truewhen using theLocalSystemusername. This can only be set totruewhen the service_type iswin32_own_processorwin32_share_process.description – The description to set for the service.
display_name – The display name to set for the service.
error_control – The severity of the error and action token if the service fails to start. A new service defaults to
normal.criticalwill log the error and restart the system with the last-known good configuration. If the startup fails on reboot then the system will fail to operate.ignoreignores the error.normallogs the error in the event log but continues.severeis likecriticalbut a failure on the last-known good configuration reboot startup will be ignored.failure_actions – A list of failure actions the service controller should take on each failure of a service. The service manager will run the actions from first to last defined until the service starts. If failure_reset_period_sec has been exceeded then the failure actions will restart from the beginning. If all actions have been performed the the service manager will repeat the last service defined. The existing actions will be replaced with the list defined in the task if there is a mismatch with any of them. Set to an empty list to delete all failure actions on a service otherwise an omitted or null value preserves the existing actions on the service.
failure_actions_on_non_crash_failure – Controls whether failure actions will be performed on non crash failures or not.
failure_command – The command to run for a
run_commandfailure action. Set to an empty string to remove the command.failure_reboot_msg – The message to be broadcast to users logged on the host for a
rebootfailure action. Set to an empty string to remove the message.failure_reset_period_sec – The time in seconds after which the failure action list resets back to the start of the list if there are no failures. To set this value, failure_actions must have at least 1 action present. Specify
'0xFFFFFFFF'to set an infinite reset period.force_dependent_services – If
true, stopping or restarting a service with dependent services will force the dependent services to stop or restart also. Iffalse, stopping or restarting a service with dependent services may fail.load_order_group – The name of the load ordering group of which this service is a member. Specify an empty string to remove the existing load order group of a service.
name – Name of the service. If only the name parameter is specified, the module will report on whether the service exists or not without making any changes.
path – The path to the executable to set for the service.
password – The password to set the service to start as. This and the
usernameargument should be supplied together when using a local or domain account. If omitted then the password will continue to use the existing value password set. If specifyingLocalSystem,NetworkService,LocalService, theNT SERVICE, or a gMSA this field can be omitted as those accounts have no password.pre_shutdown_timeout_ms – The time in which the service manager waits after sending a preshutdown notification to the service until it proceeds to continue with the other shutdown actions.
required_privileges – A list of privileges the service must have when starting up. When set the service will only have the privileges specified on its access token. The username of the service must already have the privileges assigned. The existing privileges will be replace with the list defined in the task if there is a mismatch with any of them. Set to an empty list to remove all required privileges, otherwise an omitted or null value will keep the existing privileges. See privilege text constants for a list of privilege constants that can be used.
service_type – The type of service. The default type of a new service is
win32_own_process. desktop_interact can only be set if the service type iswin32_own_processorwin32_share_process.sid_info – Used to define the behaviour of the service’s access token groups.
nonewill not add any groups to the token.restrictedwill add theNT SERVICE\<service name>SID to the access token’s groups and restricted groups.unrestrictedwill add theNT SERVICE\<service name>SID to the access token’s groups.start_mode – Set the startup type for the service. A newly created service will default to
auto.state – The desired state of the service.
started/stopped/absent/pausedare idempotent actions that will not run commands unless necessary.restartedwill always bounce the service. Only services that support the paused state can be paused, you can check the return valuecan_pause_and_continue. You can only pause a service that is already started. A newly created service will default tostopped.update_password – When set to
alwaysand password is set, the module will always report a change and set the password. Set toon_createto only set the password if the module needs to create the service. If username was specified and the service changed to that username then password will also be changed if specified. The current default ison_createbut this behaviour may change in the future, it is best to be explicit here.username – The username to set the service to start as. Can also be set to
LocalSystemorSYSTEMto use the SYSTEM account. A newly created service will default toLocalSystem. If using a custom user account, it must have theSeServiceLogonRightgranted to be able to start up. You can use thewin_user_right()method to grant this user right for you. Set toNT SERVICE\service nameto run as the NT SERVICE account for that service. This can also be a gMSA in the formDOMAIN\gMSA$.
- win_service_info(*, name: str = ...) WinServiceInfoResults
Gather information about Windows services.
See also
- Parameters:
name – If specified, this is used to match the
nameordisplay_nameof the Windows service to get the info for. Can be a wildcard to match multiple services but the wildcard will only be matched on thenameof the service and notdisplay_name. If omitted then all services will returned.
Manage Windows shares.
See also
- Parameters:
name – Share name.
path – Share directory.
state – Specify whether to add
presentor removeabsentthe specified share.description – Share description.
list – Specify whether to allow or deny file listing, in case user has no permission on share. Also known as Access-Based Enumeration.
read – Specify user list that should get read access on share, separated by comma.
change – Specify user list that should get read and write access on share, separated by comma.
full – Specify user list that should get full access on share, separated by comma.
deny – Specify user list that should get no access, regardless of implied access on share, separated by comma.
caching_mode – Set the CachingMode for this share.
scope_name – Specifies the scope name of the share. For use with Windows Server failover cluster file server resources. When defined, path must be located on a cluster shared volume/disk.
encrypt – Sets whether to encrypt the traffic to the share or not.
rule_action – Whether to add or set (replace) access control entries.
- win_shell(*, creates: StrPath = ..., removes: StrPath = ..., chdir: StrPath = ..., executable: StrPath = ..., stdin: str = ..., no_profile: bool = False, output_encoding_override: str = ...) WinShellResults
- win_shell(arg: str, /) WinShellResults
Execute shell commands on target hosts.
See also
- Parameters:
creates – A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped.
removes – A path or path filter pattern; when the referenced path does not exist on the target host, the task will be skipped.
chdir – Set the specified path as the current working directory before executing a command.
executable – Change the shell used to execute the command (eg,
cmd). The target shell must accept a/cparameter followed by the raw command line to be executed.stdin – Set the stdin of the command directly to the specified value.
no_profile – Do not load the user profile before running a command. This is only valid when using PowerShell as the executable.
output_encoding_override – This option overrides the encoding of stdout/stderr output. You can use this option when you need to run a command which ignore the console’s codepage. You should only need to use this option in very rare circumstances. This value can be any valid encoding
Namebased on the output of[System.Text.Encoding]::GetEncodings(). See reference.
- win_stat(*, path: StrPath, get_checksum: bool = True, get_size: bool = True, checksum_algorithm: Literal['md5', 'sha1', 'sha256', 'sha384', 'sha512'] = 'sha1', follow: bool = False) WinStatResults
Get information about Windows files.
See also
- Parameters:
path – The full path of the file/object to get the facts of; both forward and back slashes are accepted.
get_checksum – Whether to return a checksum of the file (default sha1).
get_size – Whether to return the size of a file or directory.
checksum_algorithm – Algorithm to determine checksum of file. Will throw an error if the host is unable to use specified algorithm.
follow – Whether to follow symlinks or junction points. In the case of
pathpointing to another link, then that will be followed until no more links are found.
- win_tempfile(*, state: Literal['directory', 'file'] = 'file', path: StrPath = '%TEMP%', prefix: str = 'ansible.', suffix: str = ...) WinTempfileResults
Creates temporary files and directories.
See also
- Parameters:
state – Whether to create file or directory.
path – Location where temporary file or directory should be created. If path is not specified default system temporary directory (%TEMP%) will be used.
prefix – Prefix of file/directory name created by module.
suffix – Suffix of file/directory name created by module.
- win_template(*, backup: bool = False, block_end_string: str = '%}', block_start_string: str = '{%', dest: StrPath, force: bool = True, lstrip_blocks: bool = False, newline_sequence: Literal['\\n', '\\r', '\\r\\n'] = '\\r\\n', output_encoding: str = 'utf-8', src: StrPath, trim_blocks: bool = True, variable_end_string: str = '}}', variable_start_string: str = '{{') WinTemplateResults
Template a file out to a remote server.
See also
- Parameters:
backup – Determine whether a backup should be created. When set to
true, create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.block_end_string – The string marking the end of a block.
block_start_string – The string marking the beginning of a block.
dest – Location to render the template to on the remote machine.
force – Determine when the file is being transferred if the destination already exists. When set to
true, replace the remote file when contents are different than the source. When set tofalse, the file will only be transferred if the destination does not exist.lstrip_blocks – Determine when leading spaces and tabs should be stripped. When set to
trueleading spaces and tabs are stripped from the start of a line to a block. This functionality requires Jinja 2.7 or newer.newline_sequence – Specify the newline sequence to use for templating files.
output_encoding – Overrides the encoding used to write the template file defined by
dest. It defaults toutf-8, but any encoding supported by python can be used. The source template file must always be encoded usingutf-8, for homogeneity.src – Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or an absolute path. The file must be encoded with
utf-8but output_encoding can be used to control the encoding of the output template.trim_blocks – Determine when newlines should be removed from blocks. When set to
truethe first newline after a block is removed (block, not variable tag!).variable_end_string – The string marking the end of a print statement.
variable_start_string – The string marking the beginning of a print statement.
- win_timezone(*, timezone: str) WinTimezoneResults
Sets Windows machine timezone.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
timezone – Timezone to set to. Example: Central Standard Time. To disable Daylight Saving time, add the suffix
_dstoffon timezones that support this.
- win_updates(*, accept_list: Sequence[str] = ..., category_names: Sequence[str] = ..., skip_optional: bool = False, reboot: bool = False, reboot_timeout: int = 1200, server_selection: Literal['default', 'managed_server', 'windows_update'] = 'default', state: Literal['installed', 'searched', 'downloaded'] = 'installed', log_path: StrPath = ..., reject_list: Sequence[str] = ..., _operation: Literal['start', 'cancel', 'poll'] = 'start', _operation_options: Mapping[str, Incomplete] = ...) WinUpdatesResults
Download and install Windows updates.
See also
- Parameters:
accept_list – A list of update titles or KB numbers that can be used to specify which updates are to be searched or installed. If an available update does not match one of the entries, then it is skipped and not installed. Each entry can either be the KB article or Update title as a regex according to the PowerShell regex rules. The accept list is only validated on updates that were found based on category_names. It will not force the module to install an update if it was not in the category specified.
category_names – A scalar or list of categories to install updates from. To get the list of categories, run the module with
state=searched. The category must be the full category string, but is case insensitive. Some possible categories are Application, Connectors, Critical Updates, Definition Updates, Developer Kits, Feature Packs, Guidance, Security Updates, Service Packs, Tools, Update Rollups, Updates, and Upgrades. Sincev1.7.0the value*will match all categories.skip_optional – Skip optional updates where the update has BrowseOnly set by Microsoft. Microsoft documents show that BrowseOnly means that the update should not be installed automatically and appear as optional updates.
reboot – Ansible will automatically reboot the remote host if it is required and continue to install updates after the reboot. This can be used instead of using a
win_reboot()task after this one and ensures all updates for that category is installed in one go. Async does not work whenreboot=true.reboot_timeout – The time in seconds to wait until the host is back online from a reboot. This is only used if
reboot=trueand a reboot is required.server_selection – Defines the Windows Update source catalog.
defaultUse the default search source. For many systems default is set to the Microsoft Windows Update catalog. Systems participating in Windows Server Update Services (WSUS) or similar corporate update server environments may default to those managed update sources instead of the Windows Update catalog.managed_serverUse a managed server catalog. For environments utilizing Windows Server Update Services (WSUS) or similar corporate update servers, this option selects the defined corporate update source.windows_updateUse the Microsoft Windows Update catalog.state – Controls whether found updates are downloaded or installed or listed. This module also supports Ansible check mode, which has the same effect as setting state=searched.
log_path – If set,
win_updateswill append update progress to the specified file. The directory must already exist.reject_list – A list of update titles or KB numbers that can be used to specify which updates are to be excluded from installation. If an available update does match one of the entries, then it is skipped and not installed. Each entry can either be the KB article or Update title as a regex according to the PowerShell regex rules.
_operation – Internal use only.
_operation_options – Internal use only.
- win_uri(*, url: str, content_type: str = ..., body: str = ..., dest: StrPath = ..., creates: StrPath = ..., removes: StrPath = ..., return_content: bool = False, status_code: Sequence[int] = ..., url_method: str = 'GET', url_timeout: int = 30, follow_redirects: Literal['all', 'none', 'safe'] = 'safe', headers: Mapping[str, Incomplete] = ..., http_agent: str = 'ansible-httpget', maximum_redirection: int = 50, validate_certs: bool = True, client_cert: str = ..., client_cert_password: str = ..., force_basic_auth: bool = False, url_username: str = ..., url_password: str = ..., use_default_credential: bool = False, use_proxy: bool = True, proxy_url: str = ..., proxy_username: str = ..., proxy_password: str = ..., proxy_use_default_credential: bool = False) WinUriResults
Interacts with webservices.
See also
- Parameters:
url – Supports FTP, HTTP or HTTPS URLs in the form of (ftp|http|https)://host.domain:port/path.
content_type – Sets the “Content-Type” header.
body – The body of the HTTP request/response to the web service.
dest – Output the response body to a file.
creates – A filename, when it already exists, this step will be skipped.
removes – A filename, when it does not exist, this step will be skipped.
return_content – Whether or not to return the body of the response as a “content” key in the dictionary result. If the reported Content-type is “application/json”, then the JSON is additionally loaded into a key called
jsonin the dictionary results.status_code – A valid, numeric, HTTP status code that signifies success of the request. Can also be comma separated list of status codes.
url_method – The HTTP Method of the request.
url_timeout – Specifies how long the request can be pending before it times out (in seconds). Set to
0to specify an infinite timeout.follow_redirects – Whether or the module should follow redirects.
allwill follow all redirect.nonewill not follow any redirect.safewill follow only “safe” redirects, where “safe” means that the client is only doing aGETorHEADon the URI to which it is being redirected. When following a redirected URL, theAuthorizationheader and any credentials set will be dropped and not redirected.headers – Extra headers to set on the request. This should be a dictionary where the key is the header name and the value is the value for that header.
http_agent – Header to identify as, generally appears in web server logs. This is set to the
User-Agentheader on a HTTP request.maximum_redirection – Specify how many times the module will redirect a connection to an alternative URI before the connection fails. If set to
0or follow_redirects is set tonone, orsafewhen not doing aGETorHEADit prevents all redirection.validate_certs – If
False, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.client_cert – The path to the client certificate (.pfx) that is used for X509 authentication. This path can either be the path to the
pfxon the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>. The WinRM connection must be authenticated withCredSSPorbecomeis used on the task if the certificate file is not password protected. Other authentication types can set client_cert_password when the cert is password protected.client_cert_password – The password for client_cert if the cert is password protected.
force_basic_auth – By default the authentication header is only sent when a webservice responses to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon the original request.
url_username – The username to use for authentication.
url_password – The password for url_username.
use_default_credential – Uses the current user’s credentials when authenticating with a server protected with
NTLM,Kerberos, orNegotiateauthentication. Sites that useBasicauth will still require explicit credentials through the url_username and url_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no authentication will occur.use_proxy – If
False, it will not use the proxy defined in IE for the current user.proxy_url – An explicit proxy to use for the request. By default, the request will use the IE defined proxy unless use_proxy is set to
False.proxy_username – The username to use for proxy authentication.
proxy_password – The password for proxy_username.
proxy_use_default_credential – Uses the current user’s credentials when authenticating with a proxy host protected with
NTLM,Kerberos, orNegotiateauthentication. Proxies that useBasicauth will still require explicit credentials through the proxy_username and proxy_password options. The module will only have access to the user’s credentials if usingbecomewith a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSPorKerberos with delegation. If not usingbecomeor a different auth method to the ones stated above, there will be no default credentials available and no proxy authentication will occur.
- win_user(*, account_disabled: bool = ..., account_expires: str = ..., account_locked: bool = ..., description: str = ..., fullname: str = ..., groups: Sequence[str] = ..., groups_action: Literal['add', 'replace', 'remove'] = 'replace', home_directory: str = ..., login_script: str = ..., name: str, password: str = ..., password_expired: bool = ..., password_never_expires: bool = ..., profile: str = ..., state: Literal['absent', 'present', 'query'] = 'present', update_password: Literal['always', 'on_create'] = 'always', user_cannot_change_password: bool = ...) WinUserResults
Manages local Windows user accounts.
See also
- Parameters:
account_disabled –
truewill disable the user account.falsewill clear the disabled flag.account_expires – Set the account expiration date for the user. This value should be in the format
%Y-%m-%dor%Y-%m-%dT%H:%M:%S%z. The timezone can be omitted in the long format and will default to UTC. The format of%zis±HHMM,±HH:MM, orZfor UTC. Set the value toneverto remove the account expiration date.account_locked – Only
falsecan be set and it will unlock the user account if locked.description – Description of the user.
fullname – Full name of the user.
groups – Adds or removes the user from this comma-separated list of groups, depending on the value of groups_action. When groups_action is
replaceand groups is set to the empty string (‘groups=’), the user is removed from all groups. Sinceansible.windows v1.5.0it is possible to specify a group using it’s security identifier.groups_action – If
add, the user is added to each group in groups where not already a member. Ifreplace, the user is added as a member of each group in groups and removed from any other groups. Ifremove, the user is removed from each group in groups.home_directory – The designated home directory of the user.
login_script – The login script of the user.
name – Name of the user to create, remove or modify.
password – Optionally set the user’s password to this (plain text) value.
password_expired –
truewill require the user to change their password at next login.falsewill clear the expired password flag.password_never_expires –
truewill set the password to never expire.falsewill allow the password to expire.profile – The profile path of the user.
state – When
absent, removes the user account if it exists. Whenpresent, creates or updates the user account. Whenquery, retrieves the user account details without making any changes.update_password –
alwayswill update passwords if they differ.on_createwill only set the password for newly created users.user_cannot_change_password –
truewill prevent the user from changing their password.falsewill allow the user to change their password.
- win_user_profile(*, name: str = ..., remove_multiple: bool = False, state: Literal['absent', 'present'] = 'present', username: Incomplete = ...) WinUserProfileResults
Manages the Windows user profiles.
See also
ansible.windows
Warning
The documentation is referring to the module from ansible.windows, there are however other collections with the same module name, so depending on your environment you may be getting one of those instead.
Conflicting collections:
- Parameters:
name – Specifies the base name for the profile path. When state is
presentthis is used to create the profile for username at a specific path within the profile directory. This cannot be used to specify a path outside of the profile directory but rather it specifies a folder(s) within this directory. If a profile for another user already exists at the same path, then a 3 digit incremental number is appended by Windows automatically. When state isabsentand username is not set, then the module will remove all profiles that point to the profile path derived by this value. This is useful if the account no longer exists but the profile still remains.remove_multiple – When state is
absentand the value for name matches multiple profiles the module will fail. Set this value toTrueto force the module to delete all the profiles found.state – Will ensure the profile exists when set to
present. When creating a profile the username option must be set to a valid account. Will remove the profile(s) when set toabsent. When removing a profile either username must be set to a valid account, or name is set to the profile’s base name.username – The account name of security identifier (SID) for the profile. This must be set when state is
presentand must be a valid account or the SID of a valid account. When state isabsentthen this must still be a valid account number but the SID can be a deleted user’s SID.
- win_user_right(*, name: str, users: Sequence[str], action: Literal['add', 'remove', 'set'] = 'set') WinUserRightResults
Manage Windows User Rights.
See also
- Parameters:
name – The name of the User Right as shown by the
Constant Namevalue from reference. The module will return an error if the right is invalid.users – A list of users or groups to add/remove on the User Right. These can be in the form DOMAINuser-group, user-group@DOMAIN.COM for domain users/groups. For local users/groups it can be in the form user-group, .user-group, SERVERNAMEuser-group where SERVERNAME is the name of the remote server. It is highly recommended to use the
.\orSERVERNAME\prefix to avoid any ambiguity with domain account names or errors trying to lookup an account on a domain controller. You can also add special local accounts like SYSTEM and others. Can be set to an empty list with action=set to remove all accounts from the right.action –
addwill add the users/groups to the existing right.removewill remove the users/groups from the existing right.setwill replace the users/groups of the existing right.
- win_wait_for(*, connect_timeout: int = 5, delay: int = ..., exclude_hosts: Sequence[str] = ..., host: str = '127.0.0.1', path: StrPath = ..., port: int = ..., regex: str = ..., sleep: int = 1, state: Literal['absent', 'drained', 'present', 'started', 'stopped'] = 'started', timeout: int = 300) WinWaitForResults
Waits for a condition before continuing.
See also
- Parameters:
connect_timeout – The maximum number of seconds to wait for a connection to happen before closing and retrying.
delay – The number of seconds to wait before starting to poll.
exclude_hosts – The list of hosts or IPs to ignore when looking for active TCP connections when
state=drained.host – A resolvable hostname or IP address to wait for. If
state=drainedthen it will only check for connections on the IP specified, you can use ‘0.0.0.0’ to use all host IPs.path – The path to a file on the filesystem to check. If
stateis present or started then it will wait until the file exists. Ifstateis absent then it will wait until the file does not exist.port – The port number to poll on
host.regex – Can be used to match a string in a file. If
stateis present or started then it will wait until the regex matches. Ifstateis absent then it will wait until the regex does not match. Defaults to a multiline regex.sleep – Number of seconds to sleep between checks.
state – When checking a port,
startedwill ensure the port is open,stoppedwill check that is it closed anddrainedwill check for active connections. When checking for a file or a search stringpresentorstartedwill ensure that the file or string is present,absentwill check that the file or search string is absent or removed.timeout – The maximum number of seconds to wait for.
- win_whoami() WinWhoamiResults
Get information about the current user and process.
See also
- yum(*, use_backend: Literal['auto', 'yum', 'yum4', 'dnf'] = 'auto', name: Sequence[str] = ..., exclude: str = ..., list: str = ..., state: Literal['absent', 'installed', 'latest', 'present', 'removed'] = ..., enablerepo: str = ..., disablerepo: str = ..., conf_file: str = ..., disable_gpg_check: bool = False, skip_broken: bool = False, update_cache: bool = False, validate_certs: bool = True, update_only: bool = False, installroot: str = '/', security: bool = False, bugfix: str = 'no', allow_downgrade: bool = False, enable_plugin: str = ..., disable_plugin: str = ..., releasever: str = ..., autoremove: bool = False, disable_excludes: str = ..., download_only: bool = False, lock_timeout: int = 30, install_weak_deps: bool = True, download_dir: str = ..., install_repoquery: bool = True) YumResults
Manages packages with the yum package manager.
- Parameters:
use_backend – This module supports
yum(as it always has), this is known asyum3/YUM3/yum-deprecatedby upstream yum developers. As of Ansible 2.7+, this module also supportsYUM4, which is the “new yum” and it has andnfbackend. By default, this module will select the backend based on theansible_pkg_mgrfact.name – A package name or package specifier with version, like
name-1.0. If a previous version is specified, the task also needs to turnallow_downgradeon. See theallow_downgradedocumentation for caveats with downgrading packages. When using state=latest, this can be'*'which means runyum -y update. You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages.exclude – Package name(s) to exclude when state=present, or latest.
list – Package name to run the equivalent of yum list –show-duplicates <package> against. In addition to listing packages, use can also list the following:
installed,updates,availableandrepos. This parameter is mutually exclusive withname.state – Whether to install (
presentorinstalled,latest), or remove (absentorremoved) a package.presentandinstalledwill simply ensure that a desired package is installed.latestwill update the specified package if it’s not of the latest available version.absentandremovedwill remove the specified package. Default isNone, however in effect the default action ispresentunless theautoremoveoption is enabled for this module, thenabsentis inferred.enablerepo – Repoid of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a
",". As of Ansible 2.7, this can alternatively be a list instead of","separated string.disablerepo – Repoid of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a
",". As of Ansible 2.7, this can alternatively be a list instead of","separated string.conf_file – The remote yum configuration file to use for the transaction.
disable_gpg_check – Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is present or latest.
skip_broken – Skip packages with broken dependencies(devsolve) and are causing problems.
update_cache – Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is present or latest.
validate_certs – This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to
False, the SSL certificates will not be validated. This should only set toFalseused on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set toTrue.update_only – When using latest, only update installed packages. Do not install packages. Has an effect only if state is latest.
installroot – Specifies an alternative installroot, relative to which all packages will be installed.
security – If set to
True, andstate=latestthen only installs updates that have been marked security related.bugfix – If set to
True, andstate=latestthen only installs updates that have been marked bugfix related.allow_downgrade – Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction).
enable_plugin – Plugin name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.
disable_plugin – Plugin name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.
releasever – Specifies an alternative release from which all packages will be installed.
autoremove – If
True, removes all “leaf” packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is absent. NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+).disable_excludes – Disable the excludes defined in YUM config files. If set to
all, disables all excludes. If set tomain, disable excludes defined in [main] in yum.conf. If set torepoid, disable excludes defined for given repo id.download_only – Only download the packages, do not install them.
lock_timeout – Amount of time to wait for the yum lockfile to be freed.
install_weak_deps – Will also install all packages linked by a weak dependency relation. NOTE: This feature requires yum >= 4 (RHEL/CentOS 8+).
download_dir – Specifies an alternate directory to store packages. Has an effect only if download_only is specified.
install_repoquery – If repoquery is not available, install yum-utils. If the system is registered to RHN or an RHN Satellite, repoquery allows for querying all channels assigned to the system. It is also required to use the ‘list’ parameter. NOTE: This will run and be logged as a separate yum transation which takes place before any other installation or removal. NOTE: This will use the system’s default enabled repositories without regard for disablerepo/enablerepo given to the module.
- yum_repository(*, async_: bool = ..., bandwidth: str = ..., baseurl: Sequence[str] = ..., cost: str = ..., countme: bool = ..., deltarpm_metadata_percentage: str = ..., deltarpm_percentage: str = ..., description: str = ..., enabled: bool = ..., enablegroups: bool = ..., exclude: Sequence[str] = ..., failovermethod: Literal['roundrobin', 'priority'] = ..., file: str = ..., gpgcakey: str = ..., gpgcheck: bool = ..., gpgkey: Sequence[str] = ..., module_hotfixes: bool = ..., http_caching: Literal['all', 'packages', 'none'] = ..., include: str = ..., includepkgs: Sequence[str] = ..., ip_resolve: Literal['4', '6', 'IPv4', 'IPv6', 'whatever'] = ..., keepalive: bool = ..., keepcache: Literal['0', '1'] = ..., metadata_expire: str = ..., metadata_expire_filter: Literal['never', 'read-only:past', 'read-only:present', 'read-only:future'] = ..., metalink: str = ..., mirrorlist: str = ..., mirrorlist_expire: str = ..., name: str, password: str = ..., priority: str = ..., protect: bool = ..., proxy: str = ..., proxy_password: str = ..., proxy_username: str = ..., repo_gpgcheck: bool = ..., reposdir: StrPath = '/etc/yum.repos.d', retries: str = ..., s3_enabled: bool = ..., skip_if_unavailable: bool = ..., ssl_check_cert_permissions: bool = ..., sslcacert: str = ..., sslclientcert: str = ..., sslclientkey: str = ..., sslverify: bool = ..., state: Literal['absent', 'present'] = 'present', throttle: str = ..., timeout: str = ..., ui_repoid_vars: str = ..., username: str = ..., mode: str = ..., owner: str = ..., group: str = ..., seuser: str = ..., serole: str = ..., setype: str = ..., selevel: str = ..., unsafe_writes: bool = False, attributes: str = ...) YumRepositoryResults
Add or remove YUM repositories.
See also
- Parameters:
async – If set to
trueYum will download packages and metadata from this repo in parallel, if possible. In ansible-core 2.11, 2.12, and 2.13 the default value istrue. This option has been removed in RHEL 8. If you’re using one of the versions listed above, you can set this option tonullto avoid passing an unknown configuration option. This parameter is deprecated as it has been removed on systems supported by ansible-core and will be removed in ansible-core 2.22.bandwidth – Maximum available network bandwidth in bytes/second. Used with the
throttleoption. Ifthrottleis a percentage and bandwidth is0then bandwidth throttling will be disabled. Ifthrottleis expressed as a data rate (bytes/sec) then this option is ignored. Default is0(no bandwidth throttling).baseurl – URL to the directory where the yum repository’s ‘repodata’ directory lives. It can also be a list of multiple URLs. This, the
metalinkormirrorlistparameters are required ifstateis set topresent.cost – Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other.
countme – Whether a special flag should be added to a randomly chosen metalink/mirrorlist query each week. This allows the repository owner to estimate the number of systems consuming it. Requires ansible-core >= 2.18
deltarpm_metadata_percentage – When the relative size of deltarpm metadata vs pkgs is larger than this, deltarpm metadata is not downloaded from the repo. Note that you can give values over
100, so200means that the metadata is required to be half the size of the packages. Use0to turn off this check, and always download metadata. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.deltarpm_percentage – When the relative size of delta vs pkg is larger than this, delta is not used. Use
0to turn off delta rpm processing. Local repositories (with file://baseurl) have delta rpms turned off by default.description – A human-readable string describing the repository. This option corresponds to the
nameproperty in the repo file. This parameter is only required ifstate=present.enabled – This tells yum whether or not use this repository. Yum default value is
true.enablegroups – Determines whether yum will allow the use of package groups for this repository. Yum default value is
true.exclude – List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (for example
*and?) are allowed. The list can also be a regular YAML array.excludepkgsalias was added in ansible-core 2.18.failovermethod –
roundrobinrandomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host.prioritystarts from the firstbaseurllisted and reads through them sequentially.file – File name without the
.repoextension to save the repo in. Defaults to the value ofname.gpgcakey – A URL pointing to the ASCII-armored CA key file for the repository. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.
gpgcheck – Tells yum whether or not it should perform a GPG signature check on packages. No default setting. If the value is not set, the system setting from
/etc/yum.confor system default offalsewill be used.gpgkey – A URL pointing to the ASCII-armored GPG key file for the repository. It can also be a list of multiple URLs.
module_hotfixes – Disable module RPM filtering and make all RPMs from the repository available. The default is
null.http_caching – Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does.
allmeans that all HTTP downloads should be cached.packagesmeans that only RPM package downloads should be cached (but not repository metadata downloads).nonemeans that no HTTP downloads should be cached. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.include – Include external configuration file. Both, local path and URL is supported. Configuration file will be inserted at the position of the
include=line. Included files may contain further include lines. Yum will abort with an error if an inclusion loop is detected.includepkgs – List of packages you want to only use from a repository. This should be a space separated list. Shell globs using wildcards (for example
*and?) are allowed. Substitution variables (for example$releasever) are honored here. The list can also be a regular YAML array.ip_resolve – Determines how yum resolves host names.
4orIPv4- resolve to IPv4 addresses only.6orIPv6- resolve to IPv6 addresses only.keepalive – This tells yum whether or not HTTP/1.1 keepalive should be used with this repository. This can improve transfer speeds by using one connection when downloading multiple files from a repository. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.
keepcache – Either
1or0. Determines whether or not yum keeps the cache of headers and packages after successful installation. This parameter is deprecated as it is only valid in the main configuration and will be removed in ansible-core 2.20.metadata_expire – Time (in seconds) after which the metadata will expire. Default value is 6 hours.
metadata_expire_filter – Filter the
metadata_expiretime, allowing a trade of speed for accuracy if a command doesn’t require it. Each yum command can specify that it requires a certain level of timeliness quality from the remote repos. from “I’m about to install/upgrade, so this better be current” to “Anything that’s available is good enough”.never- Nothing is filtered, always obeymetadata_expire.read-only:past- Commands that only care about past information are filtered from metadata expiring. Eg.yum historyinfo (if history needs to lookup anything about a previous transaction, then by definition the remote package was available in the past).read-only:present- Commands that are balanced between past and future. Eg.yum list yum.read-only:future- Commands that are likely to result in running other commands which will require the latest metadata. Eg.yum check-update. Note that this option does not overrideyum clean expire-cache. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.metalink – Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a
baseurl. This, thebaseurlormirrorlistparameters are required ifstateis set topresent.mirrorlist – Specifies a URL to a file containing a list of baseurls. This, the
baseurlormetalinkparameters are required ifstateis set topresent.mirrorlist_expire – Time (in seconds) after which the mirrorlist locally cached will expire. Default value is 6 hours. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.
name – Unique repository ID. This option builds the section name of the repository in the repo file. This parameter is only required if
stateis set topresentorabsent.password – Password to use with the username for basic authentication.
priority – Enforce ordered protection of repositories. The value is an integer from 1 to 99. This option only works if the YUM Priorities plugin is installed.
protect – Protect packages from updates from other repositories. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.
proxy – URL to the proxy server that yum should use. Set to
_none_to disable the global proxy setting.proxy_password – Password for this proxy.
proxy_username – Username to use for proxy.
repo_gpgcheck – This tells yum whether or not it should perform a GPG signature check on the repodata from this repository.
reposdir – Directory where the
.repofiles will be stored.retries – Set the number of times any attempt to retrieve a file should retry before returning an error. Setting this to
0makes yum try forever.s3_enabled – Enables support for S3 repositories. This option only works if the YUM S3 plugin is installed.
skip_if_unavailable – If set to
trueyum will continue running if this repository cannot be contacted for any reason. This should be set carefully as all repos are consulted for any given command.ssl_check_cert_permissions – Whether yum should check the permissions on the paths for the certificates on the repository (both remote and local). If we can’t read any of the files then yum will force
skip_if_unavailableto betrue. This is most useful for non-root processes which use yum on repos that have client cert files which are readable only by root. This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.sslcacert – Path to the directory containing the databases of the certificate authorities yum should use to verify SSL certificates.
sslclientcert – Path to the SSL client certificate yum should use to connect to repos/remote sites.
sslclientkey – Path to the SSL client key yum should use to connect to repos/remote sites.
sslverify – Defines whether yum should verify SSL certificates/hosts at all.
state – State of the repo file.
throttle – Enable bandwidth throttling for downloads. This option can be expressed as a absolute data rate in bytes/sec. An SI prefix (k, M or G) may be appended to the bandwidth value.
timeout – Number of seconds to wait for a connection before timing out.
ui_repoid_vars – When a repository id is displayed, append these yum variables to the string if they are used in the
baseurl/etc. Variables are appended in the order listed (and found). This parameter is deprecated as it has no effect with dnf as an underlying package manager and will be removed in ansible-core 2.22.username – Username to use for basic authentication to a repo or really any url.
mode – The permissions the resulting filesystem object should have. For those used to
/usr/bin/chmodremember that modes are actually octal numbers. You must give Ansible enough information to parse them correctly. For consistent results, quote octal numbers (for example,'644'or'1777') so Ansible receives a string and can do its own conversion from string into number. Adding a leading zero (for example,0755) works sometimes, but can fail in loops and some other circumstances. Giving Ansible a number without following either of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example,u+rwxoru=rw,g=r,o=r). Ifmodeis not specified and the destination filesystem object does not exist, the defaultumaskon the system will be used when setting the mode for the newly created filesystem object. Ifmodeis not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmodeis the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.owner – Name of the user that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current user unless you are root, in which case it can preserve the previous ownership. Specifying a numeric username will be assumed to be a user ID and not a username. Avoid numeric usernames to avoid this confusion.group – Name of the group that should own the filesystem object, as would be fed to
chown. When left unspecified, it uses the current group of the current user unless you are root, in which case it can preserve the previous ownership.seuser – The user part of the SELinux filesystem object context. By default it uses the
systempolicy, where applicable. When set to_default, it will use theuserportion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default, it will use theroleportion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default, it will use thetypeportion of the policy if available.selevel – The level part of the SELinux filesystem object context. This is the MLS/MCS attribute, sometimes known as the
range. When set to_default, it will use thelevelportion of the policy if available.unsafe_writes – Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objects, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
attributes – The attributes the resulting filesystem object should have. To get supported flags look at the man page for
chattron the target system. This string should contain the attributes in the same order as the one displayed bylsattr. The=operator is assumed as default, otherwise+or-operators need to be included in the string.
- suitable.api.install_strategy_plugins(directories: Iterable[StrPath] | str) None[source]
Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon.
As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that’s probably not something we’d ever have much of a use for.
Call this function before using custom strategies on the
Apiclass.