Suitable API Documentation
- class suitable.api.Api(servers: str | list[str] | dict[str, dict[str, Any]], 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 list 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
become
orbecome_user
are 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:
debug
info
(default)warn
error
critical
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
Api
instances 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
Api
instance, 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) NoReturn [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) NoReturn [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
query
state gets the current ACL without changing it, for use inregister
operations.follow – Whether to follow symlinks on the path if a symlink is encountered.
default – If the target is a directory, setting this to
true
will make it the default ACL for entities created inside the directory. Settingdefault
totrue
causes an error if the path is 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
setfacl
documentation 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
. Aliasrecurse
added in version 1.3.0.use_nfsv4_acls – Use NFSv4 ACLs instead of POSIX ACLs.
recalculate_mask – Select if and when to recalculate the effective right masks of the files. See
setfacl
documentation 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.0
orfoo>=1.0
. Name wildcards (fnmatch) likeapt*
and version wildcards likefoo=1.0*
are also supported.state – Indicates the desired package state.
latest
ensures that the latest version is installed.build-dep
ensures the package build dependencies are installed.fixed
attempt to correct a system with broken dependencies in place.update_cache – Run the equivalent of
apt-get update
before 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=absent
orautoremove=yes
.default_release – Corresponds to the
-t
option for apt and sets pin priorities.install_recommends – Corresponds to the
--no-install-recommends
option for apt.true
installs recommended packages.false
does 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-yes
to apt-get and impliesallow_unauthenticated=yes
andallow_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-f
flag to apt-get on 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-get
for more information.clean – Run the equivalent of
apt-get clean
to 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_unauthenticated
is only supported withstate
:install
/present
.allow_downgrade – Corresponds to the
--allow-downgrades
option for apt. This option enables the named package and version to replace an already installed higher version of that package. Note that settingallow_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).allow_downgrade
is only supported byapt
and will be ignored ifaptitude
is 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 dpkg options to apt command. 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 the
xz-utils
package 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, autoclean was also an alias for autoremove, 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, if policy_rc_d=101 the installed package will not trigger a service start. If /usr/sbin/policy-rc.d already exists, it is backed up and restored after the package installation. If
null
, the /usr/sbin/policy-rc.d isn’t created/changed.only_upgrade – Only upgrade a package if it is already installed.
fail_on_autoremove – Corresponds to the
--no-remove
option forapt
. Iftrue
, it is ensured that no packages will be removed or the task will fail.fail_on_autoremove
is only supported withstate
exceptabsent
.fail_on_autoremove
is only supported byapt
and will be ignored ifaptitude
is 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
state
is 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 update
when 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 .list extension 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-apt
for Python 2, andapt-get install python3-apt
for 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=false
and 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 via ‘%s’ which 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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 ‘when’ statement.
fail_msg – The customized message used for a failing assertion. This argument was called ‘msg’ before Ansible 2.7, now it is renamed to ‘fail_msg’ with alias ‘msg’.
success_msg – The customized message used for a successful assertion.
quiet – Set this to
true
to 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) or absent(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 – Alternate path to the authorized_keys file. When unset, this value defaults to ~/.ssh/authorized_keys.
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=false
if 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
key
string 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 tokey
in 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 tofalse
used 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 = 'EOF', 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
,destfile
andname
.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_begin
andmarker_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
state
were specified toabsent
.insertafter – If specified and no begin/ending
marker
lines are found, the block will be inserted after the last match of specified regular expression. A special value is available;EOF
for inserting the block at the end of the file. If specified regular expression has no matches,EOF
will 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
marker
lines are found, the block will be inserted before the last match of specified regular expression. A special value is available;BOF
for 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
state
is 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
state
is set toabsent
. Requires ansible-core >= 2.16mode – The permissions the resulting filesystem object should have. For those used to /usr/bin/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 ‘%s’ which 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, see
handling 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
filename
or default filename as described infilename
options 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 infilename
within 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
prompt
option is matched it won’t check for other prompts. This boolean flag, that when set to True will check for all the prompts mentioned inprompt
option 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
rollback
and 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
commit
argument instructs the module to push the configuration to the device. This is mapped to module check mode.replace – If the
replace
argument is set toTrue
, it will replace the entire running-config of the device with theconfig
argument value. For devices that support replacing running configuration from file on device like NXOS/JUNOS, thereplace
argument takes path to the file on the device that will be used for replacing the entire running-config. The value ofconfig
option 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_options
value is not given, the backup file is written to thebackup
folder 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
rollback
argument 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 therollback
argument to 0. This option is mutually exclusive withconfig
.commit_comment – The
commit_comment
argument specifies a text string to be used when committing the configuration. If thecommit
argument 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_replace
argument 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_match
is set to line, commands are matched line by line. Ifdiff_match
is set to strict, command lines are matched with respect to position. Ifdiff_match
is set to exact, command lines must be an equal match. Finally, ifdiff_match
is 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
backup
is set to True, ifbackup
is 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
$HOME
will be expanded before being passed to the command to run. Set tofalse
to 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
argv
to 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
removes
is checked.removes – A filename or (since 2.0) glob pattern. If a matching file exists, this step will be run. This is checked after
creates
is 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 the
rsync
command line tool.content – When used instead of
src
, sets the contents of a file directly to the specified value. Works only whendest
is a file. Creates the file if it does not exist. For advanced formatting or ifcontent
contains a variable, use thetemplate()
method.dest – Remote absolute path where the file should be copied to. If
src
is a directory, this must be a directory too. Ifdest
is a non-existent path and if eitherdest
ends with “/” orsrc
is a directory,dest
is created. Ifdest
is a relative path, the starting directory is determined by the remote host. Ifsrc
anddest
are files, the parent directory ofdest
is 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/chmod
remember 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 (like0644
or01777
) 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+rwx
oru=rw,g=r,o=r
). As of Ansible 2.3, the mode may also be the special stringpreserve
.preserve
means that the file will be given the same permissions as the source file. When doing a recursive copy, see alsodirectory_mode
. Ifmode
is not specified and the destination file does not exist, the defaultumask
on the system will be used when setting the mode for the newly created file. Ifmode
is not specified and the destination file does exist, the mode of the existing file will be used. Specifyingmode
is 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
mode
for the syntax of accepted values. The target system’s defaults determine permissions when this parameter is not set.remote_src – Influence whether
src
needs to be transferred or already is present remotely. Iffalse
, it will search forsrc
on the controller node. Iftrue
it will search forsrc
on the managed (remote) node.remote_src
supports recursive copying as of version 2.8.remote_src
only works withmode=preserve
as 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 ‘%s’ which 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, see
handling 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 env is 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 env is set, the value of environment variable. The command should not contain line breaks. Required if
state=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 theuser
as well, unlessstate
is notpresent
. Either this parameter orname
is 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_file
variable 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-6
for 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.
name
andvalue
parameters are the name and the value of environment variable.insertafter – Used with
state=present
andenv
. If specified, the environment variable will be inserted after the declaration of specified environment variable.insertbefore – Used with
state=present
andenv
. 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 InRelease file, relative to the normal position of an InRelease file.
languages – Defines which languages information such as translated package descriptions should be downloaded.
name – Name of the repo. Specifically used for
X-Repolib-Name
and in naming the repository and signing key files.pdiffs – Controls if APT should try to use PDiffs to 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.gpg
keyring 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 (e.g. a version codename like disco or artful). 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 e.g. packages are installed from this source.
types – Which types of packages to look for from a given source; either binary
deb
or 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=True
to task while specifyingvtype=password
.seen
was added in Ansible 2.2. After Ansible 2.17, user can specifyvalue
as a list, ifvtype
is set asmultiselect
.value – Value to set the configuration to. After Ansible 2.17,
value
is of type ‘raw’.unseen – Do not set ‘seen’ flag 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
msg
option. 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/ansible
and not playbooks. Usepackage_facts()
instead of thelist
argument as a best practice.state – Whether to install (
present
,latest
), or remove (absent
) a package. Default isNone
, however in effect the default action ispresent
unless theautoremove
option is enabled for this module, thenabsent
is 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
state
ispresent
orlatest
. 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
isabsent
.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-broken option.
update_cache – Force dnf to check if cache is out of date and redownload if needed. Has an effect only if
state
ispresent
orlatest
.update_only – When using latest, only update installed packages. Do not install packages. Has an effect only if
state
islatest
.security – If set to
true
, andstate=latest
then 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=latest
then 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_plugin – Plugin name 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] in dnf.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. e.g. for localinstall. If set to
false
, the SSL certificates will not be validated. This should only set tofalse
used 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
false
if 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=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).
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_only
is specified.allowerasing – If
true
it allows erasing of installed packages to resolve dependencies.nobest – This is the opposite of the
best
option 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 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/ansible
and not playbooks. Usepackage_facts()
instead of thelist
argument as a best practice.state – Whether to install (
present
,latest
), or remove (absent
) a package. Default isNone
, however in effect the default action ispresent
unless theautoremove
option is enabled for this module, thenabsent
is 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
state
ispresent
orlatest
. 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
isabsent
.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-broken option.
update_cache – Force dnf to check if cache is out of date and redownload if needed. Has an effect only if
state
ispresent
orlatest
.update_only – When using latest, only update installed packages. Do not install packages. Has an effect only if
state
islatest
.security – If set to
true
, andstate=latest
then 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=latest
then only installs updates that have been marked bugfix related. Note that, similar todnf upgrade-minimal
, this filter applies to dependencies as well.enable_plugin – This is currently a no-op as dnf5 itself does not implement this feature. Plugin name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.
disable_plugin – This is currently a no-op as dnf5 itself does not implement this feature. Plugin name 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] in dnf.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
false
if 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=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).
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_only
is specified.allowerasing – If
true
it allows erasing of installed packages to resolve dependencies.nobest – This is the opposite of the
best
option 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
responses
is 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
null
to 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 the
dest
directory is/backup
asrc
file named/etc/profile
on hosthost.example.com
, would be saved 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 totrue
in 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
dest
ends 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, ifdiff
is declared, you will see the files and folders deleted listed underpath_contents
. Note thatabsent
will not causefile()
to fail if thepath
does 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 totouch
or 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 waytouch
works from the command line). Default is the current state of the file if it exists,directory
ifrecurse=yes
, orfile
otherwise.src – Path of the file to link to. This applies only to
state=link
andstate=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 DEST
treats relative paths.recurse – Recursively set the specified file attributes on directory contents. This applies only when
state
is set todirectory
.force – Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the
path
file and create a symlink to thesrc
file in place of it).follow – This flag indicates that filesystem links, if they exist, should be followed.
follow=yes
andstate=link
can modifysrc
when combined with parameters such asmode
. Previous to Ansible 2.5, this wasfalse
by default. While creating a symlink with a non-existent destination, setfollow
tofalse
to 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
preserve
when no modification is required,YYYYMMDDHHMM.SS
when using default time format, ornow
. Default is None meaning thatpreserve
is the default forstate=[file,directory,link,hard]
andnow
is 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
preserve
when no modification is required,YYYYMMDDHHMM.SS
when using default time format, ornow
. Default isNone
meaning thatpreserve
is the default forstate=[file,directory,link,hard]
andnow
is 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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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[str], 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 = ...) 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_regex
option. 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.*\.default
as 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_regex
option. Items whose basenames match anexcludes
pattern are culled frompatterns
matches. 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
isfalse
it matches against the beginning of the line (usesre.match(\
)). Ifread_whole_file
istrue
, it searches anywhere for that pattern (usesre.search(\
)). Works only whenfile_type
isfile
.read_whole_file – When doing a
contains
search, 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 totrue
can 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.
file_type – Type of file to select. The ‘link’ and ‘any’ choices 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
true
to 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.chmod
function. 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
true
to follow symlinks in path for systems with python 2.6+.get_checksum – Set this to
true
to 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 to
false
will override this value, which is effectively depth 1. Default is unlimited depth.encoding – When doing a
contains
search, determine the encoding of the files to be searched. Requires ansible-core >= 2.17
- 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 = ..., immediate: bool = False, state: Literal['absent', 'disabled', 'enabled', 'present'], timeout: int = 0, masquerade: str = ..., offline: bool = ..., 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
public
is 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 – Should this configuration be in the running firewalld configuration or persist across reboots. 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 is assumedtrue
.immediate – Should this configuration be applied immediately, if set as permanent.
state – Enable or disable a setting. For ports: Should this port accept (enabled) or reject (disabled) connections. The states
present
andabsent
can 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.
masquerade – The masquerade setting you would like to enable/disable to/from zones within firewalld.
offline – Whether to run this module even when firewalld is offline.
target – firewalld Zone target. If state is set to
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
is set tofalse
.
- 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.
- 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
dest
is 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,force
has no effect. Ifdest
is a directory, the file will always be downloaded (regardless of theforce
andchecksum
option), 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_tmp setting. When run on Ansible prior to 2.5, it defaults to
TMPDIR
,TEMP
orTMP
env variables or a platform specific value. tempfile.tempdir.force – If
true
anddest
is 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 betrue
only for small local files. Prior to 0.6, this module behaved as iftrue
was 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>, e.g. checksum=”sha256:D98291AC[…]B6DC7B97”, 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 Python
hashlib
module is responsible for providing the available algorithms. The choices vary based on Python version and OpenSSL version. On systems running in FIPS compliant mode, themd5
algorithm may be unavailable. Additionally, if a checksum is passed to this parameter, and the file exist under thedest
location, thedestination_checksum
would be calculated, and if checksum equalsdestination_checksum
, the file download would be skipped (unlessforce
istrue
). If the checksum does not equaldestination_checksum
, the destination file is deleted.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_password
for sites that allow empty passwords. Since version 2.8 you can also use theusername
alias for this option.url_password – The password for use in HTTP basic authentication. If the
url_username
parameter is not specified, theurl_password
parameter will not be used. Since version 2.8 you can also use thepassword
alias 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_key
is not required.client_key – PEM formatted file that contains your private key to be used for SSL client authentication. If
client_cert
contains 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
Authorization
here 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_password
or with the GSSAPI env varKRB5CCNAME
that 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
~/.netrc
file. By default .netrc is used with Basic authentication headers. When set to False, .netrc credentials are ignored. Requires ansible-core >= 2.14mode – The permissions the resulting filesystem object should have. For those used to /usr/bin/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 inrepo
is not appended to this path and the destination directory must be empty. This parameter is required, unlessclone
is 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 caserefspec
needs to be specified if the given revision is not already available.accept_hostkey – Will ensure or not that “-o StrictHostKeyChecking=no” is present as an ssh option. Be aware that this disables a protection against MITM attacks. Those using OpenSSH >= 7.5 might want to set
ssh_opts
toStrictHostKeyChecking=accept-new
instead, 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-new” can be used which is safer and will only accepts host keys which are not present or are the same. if
true
, ensure that “-o StrictHostKeyChecking=accept-new” is 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_COMMAND
environment 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_file
andaccept_hostkey
. An example value could be “-o StrictHostKeyChecking=no” (although this particular option is better set byaccept_hostkey
). The module ensures that ‘BatchMode=yes’ is 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=yes’ is present in
ssh_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 fetch
command. 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 alwaystrue
and 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--recursive
option, 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--remote
flag to git submodule update.verify_commit – If
true
, when cloning or checking out aversion
verify 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
archive
to 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--raw
flag toverify-commit
andverify-tag
. Aliasgpg_allowlist
is added in version 2.17. Aliasgpg_whitelist
is 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) 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 –force flag on the group deletion command. Requires ansible-core >= 2.15
system – 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
lgroupadd
instead 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.
- 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-config
from the remote device before any changes are made. If thebackup_options
value is not given, the backup file is written to thebackup
folder 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
backup
is set to True, ifbackup
is 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 ‘systemd’ should be specified for RHEL/EL/CentOS 7+. Older distributions should use ‘redhat’.
- 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
vars
anddefaults
are 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 option default_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
vars
anddefaults
are exposed to the play. If set totrue
the variables will be available to tasks following theinclude_role
task. This functionality differs from standard variable exposure for roles listed under theroles
header 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_behaviour
configuration. This option is self-contained and does not apply to individual files indir
. You can use a loop to applyhash_behaviour
per 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
,SECMARK
orCONNSECMARK
.protocol – The protocol of the rule or of the packet to check. The specified protocol can be one of
tcp
,udp
,udplite
,icmp
,ipv6-icmp
oricmpv6
,esp
,ah
,sctp
or the special keywordall
, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from/etc/protocols
is also allowed. A!
argument before the protocol inverts the test. The number zero is equivalent to all.all
will 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_flags
expects a dict with the two keysflags
andflags_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, i.e. 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
is set toTEE
.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
is set toLOG
.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
,FORWARD
andPREROUTING
chains). 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
,OUTPUT
andPOSTROUTING
chains). 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
,REPLACE
operations).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,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.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
,dccp
orsctp
.to_destination – This specifies a destination address to use with
DNAT
. Without this, the destination address is never altered.to_source – This specifies a source address to use with
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,
jump
is 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,
jump
is 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_flags
parameter. 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_set
parameter. Uses the iptables set extension. Choicesdst,dst
andsrc,src
added 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
,/hour
or/day
, or parts of them (so5/second
is 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
chain
parameter. 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 withjump
parameter.wait – Wait N seconds for the xtables lock to prevent multiple instances of the program from running concurrently.
chain_management – If
true
andstate
ispresent
, the chain will be created if needed. Iftrue
andstate
isabsent
, the chain will be deleted if the only other parameter passed arechain
and 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_hosts
file.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-keygen can find it. Must match with <hostname> or <ip> present in key attribute. For custom SSH port,
name
needs 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,key
needs 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 –
present
to add the host key.absent
to remove it.
- lineinfile(*, path: StrPath, regexp: str = ..., search_string: str = ..., state: Literal['absent', 'present'] = 'present', line: str = ..., backrefs: bool = False, insertafter: str = 'EOF', 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
,destfile
andname
.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 withinsertbefore
orinsertafter
settings. When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement byline
to 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 withinsertbefore
orinsertafter
settings. Mutually exclusive withbackrefs
andregexp
.state – Whether the line should be there or not.
line – The line to insert/replace into the file. Required for
state=present
. Ifbackrefs
is set, may contain backreferences that will get expanded with theregexp
capture groups if the regexp matches.backrefs – Used with
state=present
. If set,line
can contain backreferences (both positional and named) that will get populated if theregexp
matches. This parameter changes the operation of the module slightly;insertbefore
andinsertafter
will be ignored, and if theregexp
does not match anywhere in the file, the file will be left unchanged. If theregexp
does 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;EOF
for inserting the line at the end of the file. If specified regular expression has no matches, EOF will be used instead. Ifinsertbefore
is set, default valueEOF
will be ignored. If regular expressions are passed to bothregexp
andinsertafter
,insertafter
is only honored if no match forregexp
is found. May not be used withbackrefs
orinsertbefore
.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;BOF
for 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 bothregexp
andinsertbefore
,insertbefore
is only honored if no match forregexp
is found. May not be used withbackrefs
orinsertafter
.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
insertafter
orinsertbefore
. If set,insertafter
andinsertbefore
will 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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 ‘%s’ which 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, see
handling complex validation
.
- mount(*, path: StrPath, src: StrPath = ..., fstype: str = ..., opts: str = ..., 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 as dest, destfile and name.src – Device (or NFS volume, or something else) to be mounted on path. Required when state set to
present
,mounted
orephemeral
.fstype – Filesystem type. Required when state is
present
,mounted
orephemeral
.opts – Mount options (see fstab(5), or vfstab(4) on Solaris).
dump – Dump (see fstab(5)). Note that if set to
null
and state set topresent
, it will cease to work and duplicate entries will be made with subsequent runs. Has no effect on Solaris systems or when used withephemeral
.passno – Passno (see fstab(5)). Note that if set to
null
and state set topresent
, it will cease to work and duplicate entries will be made with subsequent runs. Deprecated on Solaris systems. Has no effect when used withephemeral
.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.present
only specifies that the device is to be configured in fstab and does not trigger or require a mount.ephemeral
only specifies that the device is to be mounted, without changing fstab. If it is already mounted, a remount will be triggered. This will always return changed=True. If the mount point path has already a device mounted on, and its source is different than src, 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.absent
specifies that the device mount’s entry will be removed from fstab and will also unmount the device and remove the mount point.remounted
specifies 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 return changed=true. If opts is set, the options will be applied to the remount, but will not change fstab. Additionally, if opts is set, and the remount command fails, the module will error to prevent unexpected mount changes. Try usingmounted
instead to work around this issue.remounted
expects the mount point to be present in the fstab. To remount a mount point not registered in fstab, useephemeral
instead, especially with BSD nodes.absent_from_fstab
specifies 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/fstab or /etc/vfstab on Solaris. This parameter is ignored when state is set toephemeral
.boot – Determines if the filesystem should be mounted on boot. Only applies to Solaris and Linux systems. For Solaris systems,
true
will setTrue
as the value of mount at boot in /etc/vfstab. For Linux, FreeBSD, NetBSD and OpenBSD systems,false
will addnoauto
to mount options in /etc/fstab. To avoid mount option conflicts, ifnoauto
specified inopts
, mount module will ignoreboot
. This parameter is ignored when state is set toephemeral
.backup – Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
- 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
content
option 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
target
option. 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 offormat
options is not given it tries to guess the data format ofcontent
option 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 intarget
option. It the value is never it will not lock thetarget
datastore. The value if-supported lock thetarget
datastore 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
content
option is merged at the corresponding level in thetarget
datastore. If the value is replace the data in thecontent
option completely replaces the configuration in thetarget
datastore. If the value is none thetarget
datastore is unaffected by the configuration in the config option, unless and until the incoming configuration data uses theoperation
operation 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_commit
argument 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
save
argument instructs the module to save the configuration intarget
datastore 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-config
from the remote device before any changes are made. If thebackup_options
value is not given, the backup file is written to thebackup
folder 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
target
datastore.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
target
option. 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
backup
is set to True, ifbackup
is 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
source
option. Theget_filter
value 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
source
value 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
source
option. Thefilter
value 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 insource
option. By setting the option value never it will not lock thesource
datastore. 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_config
option 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.0
orname=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 likelatest
ONLY 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 defaultauto
will 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_use
variable 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 used by the system so we can query the package information. Since 2.8 this is a list and can support multiple package managers per system. The ‘portage’ and ‘pkg’ options were added in version 2.8. The ‘apk’ option was added in version 2.11. The ‘pkg_info’ option was added in version 2.13.
strategy – This option controls how the module queries the package managers on the system.
first
means it will return only information for the first supported package manager available.all
will return information for all supported and available 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
dest
option 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
isfalse
, 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=numbered
to patch, producing numbered backup copies.binary – Setting to
true
will disable patch’s heuristic for transforming CRLF line endings into LF. Line endings of src and dest must match. If set tofalse
,patch
will replace CRLF insrc
files on POSIX.ignore_whitespace – Setting to
true
will 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
seconds=None
andminutes=None
, 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
seconds=None
andminutes=None
.
- ping(*, data: str = 'pong') PingResults
Try to connect to host, verify a usable python and return
pong
on success.See also
- Parameters:
data – Data to return for the
ping
return 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
name
parameter.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 chdir option.
virtualenv – An optional path to a virtualenv directory to install into. It cannot be specified together with the ‘executable’ parameter (added in 2.1). If the virtualenv does not exist, it will be created before installing packages. The optional virtualenv_site_packages, virtualenv_command, and virtualenv_python options affect the creation of the virtualenv.
virtualenv_site_packages – Whether the virtual environment will inherit packages from the global site-packages directory. 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_command
is usingpyvenv
or the-m venv
module.state – The state of module. The ‘forcereinstall’ option 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 pip executable, if different from the Ansible Python interpreter. For example
pip3.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. The setuptools package 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 to pip install packages 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 pip to 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
shutdown
command. Only these paths will be searched for theshutdown
command.PATH
is ignored in the remote node when searching for theshutdown
command.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_paths
on the target system will be searched to find the absolute path. This will causepre_reboot_delay
,post_reboot_delay
, andmsg
to be ignored.
- replace(*, path: StrPath, regexp: str, replace: str = '', after: str = ..., before: str = ..., backup: bool = False, others: str = ..., 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
,destfile
andname
.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.
others – All arguments accepted by the
file()
method also work here.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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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 ‘%s’ which 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, see
handling 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
format
option. Required unlessmethod
is 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
content
is a query parameter that controls how descendant nodes of the requested data nodes inpath
will 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_downgrade
on. See theallow_downgrade
documentation 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.state – Whether to install (
present
orinstalled
,latest
), or remove (absent
orremoved
) a package.present
andinstalled
will simply ensure that a desired package is installed.latest
will update the specified package if it’s not of the latest available version.absent
andremoved
will remove the specified package. Default isNone
, however in effect the default action ispresent
unless theautoremove
option is enabled for this module, thenabsent
is inferred.
- rpm_key(*, key: str, state: Literal['absent', 'present'] = 'present', validate_certs: bool = True, fingerprint: 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
false
and thekey
is 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
true
if 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 if state is notdisabled
.state – The SELinux mode.
update_kernel_param – If set to true, will update also the kernel boot parameters when disabling/enabling SELinux. The
grubby
tool 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
/stopped
are idempotent actions that will not run commands unless necessary.restarted
will always bounce the service.reloaded
will always reload. At least one of state and enabled are required.. Note that reloaded will start the service if it is not already started, even if your chosen init system wouldn’t normally.sleep – If the service is being
restarted
then 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 ps command 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 state and enabled are 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_mgr’ fact and falls back to the old ‘service’ module when none matching is found. The ‘old service module’ still uses autodetection and in no way does it correspond to the
service
command.
- 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=value
pairs 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_facts
as 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
true
or 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
,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!all
is 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_local
facts. If a file is not executable it is read instead. File/results format can be JSON or INI-format. The defaultfact_path
can be specified inansible.cfg
for 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.ps1
which 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,
md5
can 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 ‘file’ utility found on most Linux/Unix systems. This will add both
stat.mimetype
andstat.charset
fields to the return, if possible. In Ansible 2.3 this option changed frommime
toget_mime
and 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 –
--username
parameter passed to svn.password –
--password
parameter 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-stdin
parameter 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-cert
flag to svn. Iftrue
, does not pass the flag.
- synchronize(*, src: str, dest: str, 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, use_ssh_args: bool = False, ssh_connection_multiplexing: bool = False, rsync_opts: Sequence[str] = ..., partial: bool = False, verify_host: bool = False, private_key: StrPath = ..., link_dest: Sequence[str] = ..., delay_updates: bool = True) 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_port inventory var took precedence over this value. This parameter defaults to the value of
ansible_port
, theremote_port
config setting or the value from ssh client configuration if none of the former have been set.mode – Specify the direction of the synchronization. In push mode the localhost or delegate is the source. In pull mode 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 “archive” option is still enabled by default - the “checksum” option 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 dest that do not exist (after transfer, not before) in the src path. This option requires recursive=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-path
on 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
--timeout
for 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 to
false
.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
.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
ControlSocket
tonone
. Set this option totrue
to allow multiplexing and reduce SSH connection overhead. Note that simply setting this option totrue
is not enough; You must also configure SSH connection multiplexing in your SSH client config by setting values forControlMaster
,ControlPersist
andControlPath
.rsync_opts – Specify additional rsync options by passing in an array. Note that an empty string in
rsync_opts
will 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.
- 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 -p if thesysctl_file
is updated. Iffalse
, does not reload sysctl even if thesysctl_file
is 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 -w if 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
.service
as 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
/stopped
are idempotent actions that will not run commands unless necessary.restarted
will always bounce the unit.reloaded
will 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 state and enabled are required.. If set, requires
name
.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-reload before doing any other operations, to make sure systemd has read any changes. When set to
true
, runs daemon-reload even 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 systemctl within a given service manager scope, either as the default system scope
system
, the current user’s scopeuser
, or the scope of all usersglobal
. For systemd to work with ‘user’, 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_DIR
variable, 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
.service
as 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
/stopped
are idempotent actions that will not run commands unless necessary.restarted
will always bounce the unit.reloaded
will 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 state and enabled are required.. If set, requires
name
.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-reload before doing any other operations, to make sure systemd has read any changes. When set to
true
, runs daemon-reload even 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 systemctl within a given service manager scope, either as the default system scope
system
, the current user’s scopeuser
, or the scope of all usersglobal
. For systemd to work with ‘user’, 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_DIR
variable, 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
/stopped
are idempotent actions that will not run commands unless necessary. Not all init scripts supportrestarted
norreloaded
natively, so these will both trigger a stop and start as needed.enabled – Whether the service should start on boot. At least one of state and enabled are required..
sleep – If the service is being
restarted
orreloaded
then 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 ‘status’ option.
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
true
symbolic links will be followed, if they exist. When set tofalse
symbolic 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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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-8
butoutput_encoding
can 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
True
the 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
True
leading 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 ‘%s’ which 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, see
handling 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=yes
andsrc
contains://
, 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
include
is 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
true
to 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
false
used 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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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
dest
is 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_format
is set tojson
it will take an already formatted JSON string or convert a data structure into JSON. Ifbody_format
is set toform-urlencoded
it will convert a dictionary or list of tuples into an ‘application/x-www-form-urlencoded’ string. (Added in v2.7). Ifbody_format
is set toform-multipart
it will convert a dictionary into ‘multipart/form-multipart’ body. (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 the Content-Type header accordingly. As of v2.3 it is possible to override theContent-Type
header, when set tojson
orform-urlencoded
via theheaders
option. The ‘Content-Type’ header cannot be overridden when usingform-multipart
.form-urlencoded
was added in v2.7.form-multipart
was 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-type is “application/json”, then the JSON is always loaded into a key called
ignore:json
in 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 401
error, 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-Type
here will override the header generated by supplyingjson
orform-urlencoded
forbody_format
.validate_certs – If
false
, SSL certificates will not be validated. This should only set tofalse
used 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_key
is not required.client_key – PEM formatted file that contains your private key to be used for SSL client authentication. If
client_cert
contains 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_auth
to ensure success when the remote end sends a 401.remote_src – If
false
, the module will search for thesrc
on the controller node. Iftrue
, the module will search for thesrc
on the managed (remote) node.force – If
true
do 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
Authorization
here 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_password
or with the GSSAPI env varKRB5CCNAME
that 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
~/.netrc
file. By default .netrc is used with Basic authentication headers. When set to False, .netrc credentials are ignored. Requires ansible-core >= 2.14mode – The permissions the resulting filesystem object should have. For those used to /usr/bin/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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: str = ..., 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 = ...) 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
name
option.hidden – macOS only, optionally hide the user from the login window and system preferences. The default will be
true
if thesystem
option is used.non_unique – Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.
seuser – Optionally sets the seuser type (user_u) on 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
append
to 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.home – Optionally set the user’s home directory.
skeleton – Optionally set a home skeleton directory. Requires
create_home
option!.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 thepassword
option will always be set, regardless of whether the user account already exists or not. When the password is passed as an argument, theuser
module will always return changed totrue
for 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 fromcreatehome
tocreate_home
in Ansible 2.5.move_home – If set to
true
when 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 totrue
makes 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 foruserdel
on your system for details and support. When used withgenerate_ssh_key=yes
this 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 –
always
will update passwords if they differ.on_create
will 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 toFalse
in 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
luseradd
instead ofuseradd
). This will check/etc/passwd
for 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/passwd
must 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
local
is omitted orFalse
.
- 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.
path
andport
are 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 portstarted
will ensure the port is open,stopped
will check that it is closed,drained
will check for active connections. When checking for a file or a search stringpresent
orstarted
will ensure that the file or string is present before continuing,absent
will check that file is absent or removed.path – Path to a file on the filesystem that must exist before continuing.
path
andport
are 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
drained
state.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
present
or removeabsent
the 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
. Ifpath
is a file or directory, rights can be any right under MSDN FileSystemRights reference. Ifpath
is a registry key, rights can be any right under MSDN RegistryRights reference. If path is a certificate key, rights can beRead
and/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, ObjectInherit
for 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_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
present
orexported
. When state isabsent
and 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
CurrentUser
orLocalMachine
whenstore_type=system
. Defaults toLocalMachine
whenstore_type=system
. Must be set to any service name whenstore_type=service
.store_type – The store type to manage. Use
system
to manage locations in the system store,LocalMachine
andCurrentUser
. Useservice
to 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=exported
andfile_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=present
only.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=present
only and cannot be changed once imported. See reference for more details.file_type – The file type to export the certificate as when
state=exported
.der
is a binary ASN.1 encoded file.pem
is 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. Whenpkcs12
is 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_command
module takes a free form command to run. This is mutually exclusive with thecmd
andargv
options. 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_params
andargv
options.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
cmd
instead.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
Name
based on the output of[System.Text.Encoding]::GetEncodings(
). See reference.
- 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
src
is a directory, this must be a directory too. Use for path separators or \ when in “double quotes”. Ifdest
ends with then source or the contents of source will be copied to the directory without renaming. Ifdest
is a nonexistent path, it will only be created ifdest
ends with “/” or “", orsrc
is a directory. Ifsrc
anddest
are files and if the parent directory ofdest
doesn’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=False
and 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_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_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
state
isdomain_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
state
isdomain_controller
).local_admin_password – Password to be assigned to the local
Administrator
user (required whenstate
ismember_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
IFC
data 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
-InstallDns
option is not supplied toInstall-ADDSDomainController
command, 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-LogPath
paramter 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
state
isdomain
, 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
state
isworkgroup
, 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
present
to ensure environment variable is set. Set toabsent
to 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
machine
to set for all users. Useuser
to set for the current user that ansible is connected as. Useprocess
to set for the current process. Probably not that useful.
- 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\sxs
or\{IP}\share\sources\sxs
.
- 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 thepath
does not exist, while an existing file or directory will receive updated file access and modification times (similar to the waytouch
works from the command line).
- 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
false
will override this value, which is effectively depth 1. Default depth is unlimited.file_type – Type of file to search for.
follow – Set this to
true
to 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_algorithm
to 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_regex
option. 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_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. 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
0
to specify an infinite timeout.follow_redirects – Whether or the module should follow redirects.
all
will follow all redirect.none
will not follow any redirect.safe
will follow only “safe” redirects, where “safe” means that the client is only doing aGET
orHEAD
on the URI to which it is being redirected. When following a redirected URL, theAuthorization
header 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-Agent
header 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
0
or follow_redirects is set tonone
, orsafe
when not doing aGET
orHEAD
it 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
pfx
on the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>
. The WinRM connection must be authenticated withCredSSP
orbecome
is 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
, orNegotiate
authentication. Sites that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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
, orNegotiate
authentication. Proxies that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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 = ..., state: Literal['absent', 'present'] = 'present') WinGroupResults
Add and remove local groups.
See also
- Parameters:
name – Name of the group.
description – Description of the group.
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
state
ispure
, 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_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
FeatureName
in 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\sxs
or\{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.
recurse – Indicates if the owner should be changed recursively.
- win_package(*, arguments: str = ..., chdir: StrPath = ..., 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
,/log
or/norestart
arguments. This is only used for themsi
,msp
, andregistry
providers. 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
, andregistry
providers.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_id
and 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_id
and othercreates_*
.creates_version – Will check the file version property of the file at
creates_path
and use the result to determine whether the package is already installed.creates_path
MUST be set and is a file. You can use this in conjunction withproduct_id
and 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.
4294967295
is-1
. To convert a unsigned number to the signed equivalent you can run “[Int32](“0x{0:X}” -f ([UInt32]3221225477))”. A return code of3010
usually means that a reboot is required, thereboot_required
return value is set if the return code is3010
. This is only used for themsi
,msp
, andregistry
providers.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
msi
ormsp
provider. When omitted, a temporary log file is used instead for those providers. This is only valid for MSI files, usearguments
for theregistry
provider.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_id
is 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_id
checks. Ifstate=present
then this value MUST be set. Ifstate=absent
then this value does not need to be set ifproduct_id
is.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 theregistry
provider. For msp packages, this is thePatchCode
(GUID) of the package which can found under theDetails -> Revision number
of the file’s properties. For msix packages, this is theName
orPackageFullName
of the package found under theGet-AppxPackage
cmdlet. For registry (exe) packages, this is the registry key name under the registry paths specified in provider. This value is ignored ifpath
is 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
auto
provider will select the proper provider if path otherwise it scans all the other providers based on the product_id. Themsi
provider scans for MSI packages installed on a machine wide and current user context based on theProductCode
of the MSI. Themsix
provider is used to install.appx
,.msix
,.appxbundle
, or.msixbundle
packages. 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 butpath
points to an updated package, this will be installed over the top of the existing one. Themsp
provider scans for all MSP patches installed on a machine wide and current user context based on thePatchCode
of the MSP. Amsp
will be applied or removed on allmsi
products that it applies to and is installed. If the patch is obsoleted or superseded then no action will be taken. Theregistry
provider is used for traditionalexe
installers 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
true
to 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 istrue
then the module will wait for both processes to finish before returning. This should not be required for most installers and setting totrue
could 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.
all
will follow all redirect.none
will not follow any redirect.safe
will follow only “safe” redirects, where “safe” means that the client is only doing aGET
orHEAD
on the URI to which it is being redirected. When following a redirected URL, theAuthorization
header 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-Agent
header 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
0
or follow_redirects is set tonone
, orsafe
when not doing aGET
orHEAD
it prevents all redirection.url_timeout – Specifies how long the request can be pending before it times out (in seconds). Set to
0
to 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
pfx
on the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>
. The WinRM connection must be authenticated withCredSSP
orbecome
is 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
, orNegotiate
authentication. Sites that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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
, orNegotiate
authentication. Proxies that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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
state
ispresent
), 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 inelements
are 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
elements
should be present or absent.scope – The level at which the environment variable specified by
name
should 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
$ErrorActionPreference
to set before executing script.silently_continue
will ignore any errors and exceptions raised.continue
is 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.stop
will 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
output
return 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_log
to 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_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
2
seconds 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
path
parameters. If not provided, or empty then the ‘(Default)’ property for the key will be used.data – Value of the registry entry
name
inpath
. 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.exe
and 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
state
is ‘absent’ then this will delete the entire key. Iffalse
then 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
SeRestorePrivilege
andSeBackupPrivilege
privileges enabled.
- 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_action
to either add/remove or set the services in this list.dependency_action – Used in conjunction with
dependency
to 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
true
when using theLocalSystem
username. This can only be set totrue
when the service_type iswin32_own_process
orwin32_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
.critical
will 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.ignore
ignores the error.normal
logs the error in the event log but continues.severe
is likecritical
but 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_command
failure 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
reboot
failure 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
username
argument 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_process
orwin32_share_process
.sid_info – Used to define the behaviour of the service’s access token groups.
none
will not add any groups to the token.restricted
will add theNT SERVICE\<service name>
SID to the access token’s groups and restricted groups.unrestricted
will 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
/paused
are idempotent actions that will not run commands unless necessary.restarted
will 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
always
and password is set, the module will always report a change and set the password. Set toon_create
to 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_create
but 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
LocalSystem
orSYSTEM
to use the SYSTEM account. A newly created service will default toLocalSystem
. If using a custom user account, it must have theSeServiceLogonRight
granted to be able to start up. You can use thewin_user_right()
method to grant this user right for you. Set toNT SERVICE\service name
to 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
name
ordisplay_name
of the Windows service to get the info for. Can be a wildcard to match multiple services but the wildcard will only be matched on thename
of 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
present
or removeabsent
the 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/c
parameter 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
Name
based 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
path
pointing 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
true
leading 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-8
but 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
true
the 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_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.0
the 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=true
and a reboot is required.server_selection – Defines the Windows Update source catalog.
default
Use 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_server
Use 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_update
Use 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_updates
will 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
json
in 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
0
to specify an infinite timeout.follow_redirects – Whether or the module should follow redirects.
all
will follow all redirect.none
will not follow any redirect.safe
will follow only “safe” redirects, where “safe” means that the client is only doing aGET
orHEAD
on the URI to which it is being redirected. When following a redirected URL, theAuthorization
header 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-Agent
header 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
0
or follow_redirects is set tonone
, orsafe
when not doing aGET
orHEAD
it 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
pfx
on the filesystem or the PowerShell certificate pathCert:\CurrentUser\My\<thumbprint>
. The WinRM connection must be authenticated withCredSSP
orbecome
is 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
, orNegotiate
authentication. Sites that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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
, orNegotiate
authentication. Proxies that useBasic
auth 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 usingbecome
with a password, you are connecting with SSH using a password, or connecting with WinRM usingCredSSP
orKerberos with delegation
. If not usingbecome
or 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 –
true
will disable the user account.false
will clear the disabled flag.account_expires – Set the account expiration date for the user. This value should be in the format
%Y-%m-%d
or%Y-%m-%dT%H:%M:%S%z
. The timezone can be omitted in the long format and will default to UTC. The format of%z
is±HHMM
,±HH:MM
, orZ
for UTC. Set the value tonever
to remove the account expiration date.account_locked – Only
false
can 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
replace
and groups is set to the empty string (‘groups=’), the user is removed from all groups. Sinceansible.windows v1.5.0
it 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 –
true
will require the user to change their password at next login.false
will clear the expired password flag.password_never_expires –
true
will set the password to never expire.false
will 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 –
always
will update passwords if they differ.on_create
will only set the password for newly created users.user_cannot_change_password –
true
will prevent the user from changing their password.false
will allow the user to change their password.
- 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 Name
value 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 –
add
will add the users/groups to the existing right.remove
will remove the users/groups from the existing right.set
will 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=drained
then 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
state
is present or started then it will wait until the file exists. Ifstate
is 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
state
is present or started then it will wait until the regex matches. Ifstate
is 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,
started
will ensure the port is open,stopped
will check that is it closed anddrained
will check for active connections. When checking for a file or a search stringpresent
orstarted
will ensure that the file or string is present,absent
will 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-deprecated
by upstream yum developers. As of Ansible 2.7+, this module also supportsYUM4
, which is the “new yum” and it has andnf
backend. By default, this module will select the backend based on theansible_pkg_mgr
fact.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_downgrade
on. See theallow_downgrade
documentation 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
,available
andrepos
. This parameter is mutually exclusive withname
.state – Whether to install (
present
orinstalled
,latest
), or remove (absent
orremoved
) a package.present
andinstalled
will simply ensure that a desired package is installed.latest
will update the specified package if it’s not of the latest available version.absent
andremoved
will remove the specified package. Default isNone
, however in effect the default action ispresent
unless theautoremove
option is enabled for this module, thenabsent
is 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 toFalse
used 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=latest
then only installs updates that have been marked security related.bugfix – If set to
True
, andstate=latest
then 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 = ..., 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
true
Yum 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 deprecated in RHEL 8. If you’re using one of the versions listed above, you can set this option to None to avoid passing an unknown configuration option.bandwidth – Maximum available network bandwidth in bytes/second. Used with the
throttle
option. Ifthrottle
is a percentage and bandwidth is0
then bandwidth throttling will be disabled. Ifthrottle
is 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
metalink
ormirrorlist
parameters are required ifstate
is set topresent
.cost – Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other.
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
, so200
means that the metadata is required to be half the size of the packages. Use0
to turn off this check, and always download metadata.deltarpm_percentage – When the relative size of delta vs pkg is larger than this, delta is not used. Use
0
to 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 “name” property in the repo file. This parameter is only required if
state
is set topresent
.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.failovermethod –
roundrobin
randomly 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.priority
starts from the firstbaseurl
listed and reads through them sequentially.file – File name without the
.repo
extension to save the repo in. Defaults to the value ofname
.gpgcakey – A URL pointing to the ASCII-armored CA key file for the repository.
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.conf
or system default offalse
will 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
None
.http_caching – Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does.
all
means that all HTTP downloads should be cached.packages
means that only RPM package downloads should be cached (but not repository metadata downloads).none
means that no HTTP downloads should be cached.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.
4
orIPv4
- resolve to IPv4 addresses only.6
orIPv6
- 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.
keepcache – Either
1
or0
. Determines whether or not yum keeps the cache of headers and packages after successful installation. This parameter is deprecated and will be removed in version 2.20.metadata_expire – Time (in seconds) after which the metadata will expire. Default value is 6 hours.
metadata_expire_filter – Filter the
metadata_expire
time, 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 history
info (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 override “yum clean expire-cache”.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, thebaseurl
ormirrorlist
parameters are required ifstate
is set topresent
.mirrorlist – Specifies a URL to a file containing a list of baseurls. This, the
baseurl
ormetalink
parameters are required ifstate
is set topresent
.mirrorlist_expire – Time (in seconds) after which the mirrorlist locally cached will expire. Default value is 6 hours.
name – Unique repository ID. This option builds the section name of the repository in the repo file. This parameter is only required if
state
is set topresent
orabsent
.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.
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
.repo
files will be stored.retries – Set the number of times any attempt to retrieve a file should retry before returning an error. Setting this to
0
makes 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
true
yum 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_unavailable
to 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.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).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/chmod remember 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+rwx
oru=rw,g=r,o=r
). Ifmode
is not specified and the destination filesystem object does not exist, the defaultumask
on the system will be used when setting the mode for the newly created filesystem object. Ifmode
is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used. Specifyingmode
is 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
system
policy, where applicable. When set to_default
, it will use theuser
portion of the policy if available.serole – The role part of the SELinux filesystem object context. When set to
_default
, it will use therole
portion of the policy if available.setype – The type part of the SELinux filesystem object context. When set to
_default
, it will use thetype
portion 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 thelevel
portion 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 chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr. 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
Api
class.