[root@master ansible]# ansible-doc -s command
- name: Executes a command on a remote node
command:
argv: # Allows the user to provide the command as a list vs. a string. Only the string or the list form can be provided, not both. One or the other must be
provided.
chdir: # Change into this directory before running the command.
creates: # A filename or (since 2.0) glob pattern, when it already exists, this step will *not* be run.
free_form: # (required) The command module takes a free form command to run. There is no parameter actually named 'free form'. See the examples!
removes: # A filename or (since 2.0) glob pattern, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
warn: # If command_warnings are onin ansible.cfg, donot warn about this particular line ifsetto `no'.
command 模块
help
[root@master ~]# ansible-doc -s command
- name: Executes a command on a remote node
command:
argv: # Allows the user to provide the command as a list vs. a string. Only the string or the list form can be provided, not both. One or the other must be
provided.
chdir: # Change into this directory before running the command.
creates: # A filename or (since 2.0) glob pattern, when it already exists, this step will *not* be run.
free_form: # (required) The command module takes a free form command to run. There is no parameter actually named 'free form'. See the examples!
removes: # A filename or (since 2.0) glob pattern, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
warn: # If command_warnings are onin ansible.cfg, donot warn about this particular line ifsetto `no'.
[root@master ~]# ansible-doc -s cron
- name: Manage cron.d and crontab entries
cron:
backup: # If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file' variable by this module.
cron_file: # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to /etc/cron.d. (If it is
absolute, it will typically be /etc/crontab). Many linux distros expect (and some require) the filename portion to consist
solely of upper- and lower-case letters, digits, underscores, and hyphens. Touse the `cron_file' parameter you must specify
the `user' as well.
day: # Day of the month the job should run ( 1-31, *, */2, etc )
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"and"value" parameters are the name and the value of
environment variable.
hour: # Hour when the job should run ( 0-23, *, */2, etc )
insertafter: # Used with `state=present' and `env'. If specified, the environment variable will be inserted after the declaration of specified environment variable.
insertbefore: # Used with `state=present' and `env'. If specified, the environment variable will be inserted before the declaration of specified environment variable.
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.
minute: # Minute when the job should run ( 0-59, *, */2, etc )
month: # Month of the year the job should run ( 1-12, *, */2, etc )
name: # Description of a crontab entry or, if env is set, the name of environment variable. Required if state=absent. Note that if name isnot set and state=present,
then a new crontab entry will always be created, regardless of existing ones.
reboot: # If the job should be run at reboot. This option is deprecated. Users should use special_time.
special_time: # Special time specification nickname.
state: # Whether to ensure the job or environment variableis present or absent.
user: # The specific user whose crontab should be modified.
weekday: # Day of the week that the job should run ( 0-6for Sunday-Saturday, *, etc )
[root@master ~]# ansible-doc -s user
- name: Manage user accounts
user:
append: # If `yes', add the user to the groups specified in `groups'. If `no', user will only be added to the groups specified in `groups', removing them from all
other groups.
comment: # Optionally sets the description (aka `GECOS') of user account.
create_home: # Unless set to `no', a home directory will be made for the user when the account is created orif the home directory does not exist. Changed from `createhome'
to `create_home' in version 2.5.
expires: # An expiry timefor the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD.
Since version 2.6 you can remove the expiry time specify a negative value. Currently supported on GNU/Linux and FreeBSD.
force: # This only affects `state=absent', it forces removal of the user and associated directories on supported platforms. The behavior is the same as `userdel
--force', check the man page for `userdel' on your system for details and support.
generate_ssh_key: # Whether togenerate a SSH key for the user in question. This will *not* overwrite an existing SSH key.
group: # Optionally sets the user's primary group (takes a group name).
groups: # List of groups user will be added to. When set to an empty string `''', `null', or `~', the user is removed from all groups except the primary group. (`~'
means `null' in YAML) Before version 2.3, the only input format allowed was a comma separated string. Now this parameter
accepts a list as well as a comma separated string.
hidden: # Darwin/OS X only, optionally hide the user from the login window and system preferences. The default will be 'True' if the `system' option is used.
home: # Optionally set the user's home directory.
local: # Forces the useof"local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you
want to manipulate the local users. I.E. it uses `luseradd` instead of `useradd`. This requires that these commands exist on
the targeted host, otherwise it will be a fatal error.
login_class: # Optionally sets the user's login class, a feature of most BSD OSs.
move_home: # If set to `yes' when used with `home=', attempt to move the user's old home directory to the specified directory if it isn't there already and the old home
exists.
name: # (required) Name of the user to create, remove or modify.
non_unique: # Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.
password: # Optionally set the user's password to this crypted value. On Darwin/OS X systems, this value has to be cleartext. Beware of security issues. See
https://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for-the-user-module for details on various ways
togenerate these password values.
password_lock: # Lock the password (usermod -L, pw lock, usermod -C). BUT implementation differs on different platforms, this option does not always mean the user cannot
login via other methods. This option does not disable the user, only lock the password. Do not change the password in the same
task. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD.
remove: # This only affects `state=absent', it attempts to remove directories associated with the user. The behavior is the same as `userdel --remove', check the man
page for details and support.
seuser: # Optionally sets the seuser type (user_u) on selinux enabled systems.
shell: # Optionally set the user's shell. On Mac OS X, before version 2.5, the default shell for non-system users was /usr/bin/false. Since 2.5, the default shell for
non-system users on Mac OS X is /bin/bash.
skeleton: # Optionally set a home skeleton directory. Requires create_home option!
ssh_key_bits: # Optionally specify number of bits in SSH key to create.
ssh_key_comment: # Optionally define the comment for the SSH key.
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.
ssh_key_passphrase: # Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will defaultto having no passphrase.
ssh_key_type: # Optionally specify the typeof SSH key togenerate. Available SSH key types will depend on implementation present on target host.
state: # Whether the account should exist ornot, taking action if the state is different from what is stated.
system: # When creating an account `state=present', setting this to `yes' makes the user a system account. This setting cannot be changed on existing users.
uid: # Optionally sets the `UID' of the user.
update_password: # `always' will update passwords if they differ. `on_create' will only set the password for newly created users.
[root@master ~]# ansible slave1 -a "tail -2 /etc/passwd"192.168.27.111 | SUCCESS | rc=0 >>
postfix:x:89:89::/var/spool/postfix:/sbin/nologinsshd:x:74:74:Privilege-separatedSSH:/var/empty/sshd:/sbin/nologin
[root@master ~]# ansible slave1 -a "ls -l /home"192.168.27.111 | SUCCESS | rc=0 >>
total 0
group 模块【针对用户的组进行管理】
help
[root@master ~]# ansible-doc -s group
- name: Add or remove groups
group:
gid: # Optional `GID' to set for the group.
local: # Forces the useof"local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you
want to manipulate the local groups. I.E. it uses `lgroupadd` instead of `useradd`. This requires that these commands exist on
the targeted host, otherwise it will be a fatal error.
name: # (required) Name of the groupto manage.
state: # Whether the group should be present ornoton the remote host.
system: # If `yes', indicates that the group created is a system group.
[root@master ~]# ansible-doc -s copy
- name: Copies files to remote locations
copy:
attributes: # Attributes the fileor directory 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'.
backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
checksum: # SHA1 checksum of the file being transferred. Used to validate that the copy of the file was successful. If this isnot provided, ansible will use the local
calculated checksum of the src file.
content: # When used instead of `src', sets the contents of a file directly to the specified value. For anything advanced orwith formatting also look at the template
module.
decrypt: # This option controls the autodecryption of source files using vault.
dest: # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this must be a directory too. If `dest' is a nonexistent path
andif either `dest' ends with"/"or `src' is a directory, `dest' is created. If `src' and `dest' are files, the parent
directory of `dest' isn't created: the task fails if it doesn't already exist.
directory_mode: # When doing a recursive copy set the mode for the directories. If this isnot set we will use the system defaults. The mode is only set on directories which
are newly created, and will not affect those that already existed.
follow: # This flag indicates that filesystem links in the destination, if they exist, should be followed.
force: # the defaultis `yes', which will replace the remote filewhen contents are different than the source. If `no', the file will only be transferred if the
destination does not exist.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
local_follow: # This flag indicates that filesystem links in the source tree, if they exist, should be followed.
mode: # Mode the fileor directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either specify the leading
zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'0644''
so Ansible receives a stringand 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 version 1.8, the mode may be
specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r'). As of version 2.3, the mode may also be the special
string `preserve'. `preserve' means that the file will be given the same permissions as the source file.
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
remote_src: # If `no', it will search for `src' at originating/master machine. If `yes' it will go to the remote/target machine for the `src'. Defaultis `no'. Currently
`remote_src' does not support recursive copying. `remote_src' only works with `mode=preserve' as of version 2.6.
selevel: # Level part of the SELinux filecontext. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole: # Role part of SELinux filecontext, `_default' feature works as for `seuser'.
setype: # Type part of SELinux filecontext, `_default' feature works as for `seuser'.
seuser: # User part of SELinux filecontext. Will defaultto system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if
available.
src: # Local path to a fileto copy to the remote server; 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 notendwith"/", the
directory itself withall contents is copied. This behavior is similar to Rsync.
unsafe_writes: # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just
broken in ways that prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done
in an unsafe manner. This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in
which you do not have any other choice. Be aware that this is subject to race conditions and can lead to data corruption.
validate: # The validation command to run before copying into place. The path to the fileto validate is passed in via '%s' which must be present as in the example
below. The command is passed securely so shell features like expansion and pipes won't work.
[root@master ~]# ansible-doc -s file
- name: Sets attributes of files
file:
attributes: # Attributes the fileor directory 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'.
follow: # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was `no' by default.
force: # force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists andis a file (so, we need to
unlink the "path"fileand create symlink to the "src"filein place of it).
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
mode: # Mode the fileor directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either specify the leading
zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'0644''
so Ansible receives a stringand 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 version 1.8, the mode may be
specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
path: # (required) path to the file being managed. Aliases: `dest', `name'
recurse: # recursively set the specified file attributes (applies only to directories)
selevel: # Level part of the SELinux filecontext. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole: # Role part of SELinux filecontext, `_default' feature works as for `seuser'.
setype: # Type part of SELinux filecontext, `_default' feature works as for `seuser'.
seuser: # User part of SELinux filecontext. Will defaultto system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if
available.
src: # path of the fileto link to (applies only to `state=link' and `state=hard'). Will accept absolute, relative and nonexisting paths. Relative paths are
relative to the file being created (`path') which is how the UNIX command `ln -s SRC DEST' treats relative paths.
state: # If `directory', all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions.
If `file', the file will NOT be created if it does not exist; see the `touch' value or the [copy] or [template] module if you
want that behavior. If `link', the symbolic link will be created or changed. Use `hard' for hardlinks. If `absent',
directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent' will not cause `file' to
fail if the `path' does not exist as the state did not change. If `touch' (newin1.4), an empty file will be created if the
`path' does not exist, while an existing fileor directory will receive updated fileaccessand modification times (similar to
the way `touch` works from the command line).
unsafe_writes: # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just
broken in ways that prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done
in an unsafe manner. This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in
which you do not have any other choice. Be aware that this is subject to race conditions and can lead to data corruption.
[root@master ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python andreturn `pong' on success
ping:
data: # Data toreturnfor the `ping' return value. If this parameter is set to `crash', the module will cause an exception.
[root@master ~]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
allow_downgrade: # Specify if the named packageand 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 packageandothers can cause changes to the packages which were in the earlier transaction).
bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related.
conf_file: # The remote yum configurationfiletousefor 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'.
disable_plugin: # `Plugin' name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.
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 ",".
enable_plugin: # `Plugin' name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.
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 ",".
exclude: # Package name(s) to exclude when state=present, or latest
installroot: # Specifies an alternative installroot, relative to which all packages will be installed.
list: # Package name to run the equivalent of yum list <package> against. In addition to listing packages, use can also list the following: `installed', `updates',
`available' and `repos'.
name: # A package name orpackage specifier with version, like `name-1.0'. If a previous version is specified, the task also needs to turn `allow_downgrade' on. See
the `allow_downgrade' documentation for caveats with downgrading packages. When using state=latest, this can be '*' which
means run `yum -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 list of packages or (as of2.0) a list of packages.
security: # If set to `yes', and `state=latest' then only installs updates that have been marked security related.
skip_broken: # Resolve depsolve problems by removing packages that are causing problems from the trans‐ action.
state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. `present' and `installed' will simply ensure that a
desired packageis installed. `latest' will update the specified packageif it'snotof the latest available version. `absent'
and `removed' will remove the specified package.
update_cache: # Force yum to check if cache isoutof date and redownload if needed. Has an effect only if state is `present' or `latest'.
update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest'
validate_certs: # This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to `no', the SSL certificates will not be validated. This
should only set to `no' used on personally controlled sites using self-signed certificates as it avoids verifying the source
site. Prior to2.1 the code worked as if this was set to `yes'.
检测是否已安装
[root@master ~]# ansible slave1 -m command -a 'rpm -qa vim warn=False'192.168.27.111 | SUCCESS | rc=0 >>
[root@master ~]# ansible slave1 -m command -a 'rpm -q httpd warn=False'192.168.27.111 | FAILED | rc=1 >>
package httpd is not installednon-zero return code
[root@master ~]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line
enabled: # Whether the service should start on boot. *At least one of state and enabled are required.*
name: # (required) Name of the service.
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-infor a
status result. If the stringis found, the service will be assumed to be running.
runlevel: # For OpenRC init scripts (ex: Gentoo) only. The runlevel that this service belongs to.
sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to workaround badly behaving init scripts
that exit immediately after signaling a processto stop.
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 isnot already
started, even if your chosen init system wouldn't normally.
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.
查看服务状态
[root@master ~]# ansible slave1 -m command -a 'systemctl status httpd'192.168.27.111 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Docs: man:httpd(8)
man:apachectl(8)non-zero return code
[root@master ~]# ansible-doc -s shell
- name: Execute commands in nodes.
shell:
chdir: # cd into this directory before running the command
creates: # a filename, when it already exists, this step will *not* be run.
executable: # change the shell used toexecute the command. Should be an absolute path to the executable.
free_form: # (required) The shell module takes a free form command to run, as a string. There's not an actual option named "free form". See the examples!
removes: # a filename, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
warn: # if command warnings are onin ansible.cfg, donot warn about this particular line ifsetto no/false.
通过shell对用户进行密码设置
[root@master ~]# ansible slave1 -m shell -a 'echo123456 | passwd --stdin slave1'192.168.27.111 | SUCCESS | rc=0 >>
Changing password for user slave1.
passwd: all authentication tokens updated successfully.
script 模块【将本地脚本复制到被管理主机上进行运行】【使用“相对”路径】
help
[root@master ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # cd into this directory on the remote node before running the script
creates: # a filename, when it already exists, this step will *not* be run.
decrypt: # This option controls the autodecryption of source files using vault.
executable: # Name or path of a executable to invoke the script with
free_form: # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the examples!
removes: # a filename, when it does not exist, this step will *not* be run.
控制主机编写脚本
[root@master ~]# vim test_script.sh#!/bin/bashecho"This is test for ansible script ~ " > /root/testansiscript.txt
[root@master ~]# ansible slave1 -m command -a 'cat /root/testansiscript.txt'192.168.27.111 | SUCCESS | rc=0 >>
This is test for ansible script ~ // 输出结果查看
setup 模块【用于模块收集,查看被管理主机的facts】
help
[root@master ~]# ansible-doc -s setup
- name: Gathers facts about remote hosts
setup:
fact_path: # path used for local ansible facts (*.fact) - files in this dir will be run (if executable) and their results be added to ansible_local facts if a fileisnot
executable it is read. Check notes for Windows options. (from 2.1on) File/results format can be json or ini-format
filter: # if supplied, only return facts that match this shell-style (fnmatch) wildcard.
gather_subset: # if supplied, restrict the additional facts collected to the given subset. Possible values: all, min, hardware, network, virtual, ohai, and facter Can specify
a list of values to specify a larger subset. Values can also be used with an initial `!' to specify that that specific subset
should not be collected. For instance: !hardware, !network, !virtual, !ohai, !facter. If !allis specified then only the min
subset is collected. To avoid collecting even the min subset, specify !alland !min subsets. 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