6.Ansible命令(ad-hoc)
6.1.ansible-doc
6.2.command模块–用于在被管理主机上运行命令
6.3.cron模块
6.4.user模块
6.5.group模块
6.6.copy模块
6.7.file模块
6.8.ping模块
6.9.shell模块
6.10.service模块
6.11.script模块
6.12.yum模块
6.13.setup模块
6.14.字符串处理
7.YAML语法
7.1.基本的YAML
7.2.Gotchas
6.Ansible命令(ad-hoc)
参考:https://blog.51cto.com/u_13630803/2153392
命令格式:ansible [主机] [-m 模块] [-a args]
6.1.ansible-doc
# ansible-doc -l // 列出所有已安装的模块 注:按q退出
[root@node2 ansible]# ansible-doc -l
fortios_router_community_list Configure community lists in Fortinet's FortiOS and FortiGate
azure_rm_devtestlab_info Get Azure DevTest Lab facts
ecs_taskdefinition register a task definition in ecs
avi_alertscriptconfig Module for setup of AlertScriptConfig Avi RESTful Object
tower_receive Receive assets from Ansible Tower
netapp_e_iscsi_target NetApp E-Series manage iSCSI target configuration
azure_rm_acs Manage an Azure Container Service(ACS) instance
fortios_log_syslogd2_filter Filters for remote system server in Fortinet's FortiOS and FortiGate
junos_rpc Runs an arbitrary RPC over NetConf on an Juniper JUNOS device
na_elementsw_vlan NetApp Element Software Manage VLAN
pn_ospf CLI command to add/remove ospf protocol to a vRouter
pn_snmp_vacm CLI command to create/modify/delete snmp-vacm
cp_mgmt_service_sctp Manages service-sctp objects on Check Point over Web Services API
onyx_ospf Manage OSPF protocol on Mellanox ONYX network devices
icx_command Run arbitrary commands on remote Ruckus ICX 7000 series switches
cs_snapshot_policy Manages volume snapshot policies on Apache CloudStack based clouds
nxos_install_os Set boot options like boot, kickstart image and issu
cnos_static_route Manage static IP routes on Lenovo CNOS network devices
win_eventlog Manage Windows event logs
vmware_category Manage VMware categories
vmware_host_feature_info Gathers info about an ESXi host's feature capability information
avi_cluster Module for setup of Cluster Avi RESTful Object
na_ontap_user NetApp ONTAP user configuration and management
aci_l3out Manage Layer 3 Outside (L3Out) objects (l3ext:Out)
memset_server_info Retrieve server information
gcp_compute_subnetwork_info Gather info for GCP Subnetwork
azure_rm_virtualmachinescalesetextension Manage Azure Virtual Machine Scale Set (VMSS) extensions
fortios_report_dataset Report dataset configuration in Fortinet's FortiOS and FortiGate
avi_api_session Avi API Module
avi_networkprofile Module for setup of NetworkProfile Avi RESTful Object
# ansible-doc -s yum // -s列出yum模块描述信息和操作动作
[root@node2 ansible]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
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).
autoremove: # If `yes', 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+)
bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related.
conf_file: # The remote yum configuration file to use for the transaction.
disable_excludes: # Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If set to `main', disable
excludes defined in [main] in yum.conf. If set to `repoid', disable excludes defined
for given repo id.
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 `","'. As of
Ansible 2.7, this can alternatively be a list instead of `","' separated string
download_dir: # Specifies an alternate directory to store packages. Has an effect only if `download_only' is specified.
download_only: # Only download the packages, do not install them.
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 `","'. As of
Ansible 2.7, this can alternatively be a list instead of `","' separated string
exclude: # Package name(s) to exclude when state=present, or latest
install_weak_deps: # Will also install all packages linked by a weak dependency relation. NOTE: This feature requires yum >= 4
(RHEL/CentOS 8+)
installroot: # Specifies an alternative installroot, relative to which all packages will be installed.
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' and
`repos'. This parameter is mutually exclusive with `name'.
lock_timeout: # Amount of time to wait for the yum lockfile to be freed.
name: # A package name or package 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 string of packages or (as of 2.0) a list of packages.
releasever: # Specifies an alternative release from which all packages will be installed.
security: # If set to `yes', and `state=latest' then only installs updates that have been marked security related.
skip_broken: # Skip packages with broken dependencies(devsolve) and are causing problems.
state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. `present' and
`installed' 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'
and `removed' will remove the specified package. Default is `None', however in
effect the default action is `present' unless the `autoremove' option is enabled for
this module, then `absent' is inferred.
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'.
update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest'
use_backend: # This module supports `yum' (as it always has), this is known as `yum3'/`YUM3'/`yum-deprecated' by upstream yum
developers. As of Ansible 2.7+, this module also supports `YUM4', which is the "new
yum" and it has an `dnf' backend. By default, this module will select the backend
based on the `ansible_pkg_mgr' fact.
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 to 2.1 the code worked as if this was set to `yes'.
6.2.command模块–用于在被管理主机上运行命令
# 指定ip执行date
[root@node2 ansible]# ansible 172.17.0.3 -m command -a 'date'
172.17.0.3 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:09:20 CST
[root@node2 ansible]#
# 指定分类执行date
[root@node2 ansible]# ansible abc -m command -a 'date'
172.17.0.3 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:00 CST
[root@node2 ansible]# ansible aaa -m command -a 'date'
172.17.0.4 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:05 CST
[root@node2 ansible]# ansible bbb -m command -a 'date'
172.17.0.6 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:11 CST
172.17.0.5 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:11 CST
所有hosts主机执行date命令
[root@node2 ansible]# ansible abc -m command -a 'date'
172.17.0.3 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:00 CST
[root@node2 ansible]# ansible aaa -m command -a 'date'
172.17.0.4 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:05 CST
[root@node2 ansible]# ansible bbb -m command -a 'date'
172.17.0.6 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:11 CST
172.17.0.5 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:11 CST
[root@node2 ansible]# ansible all -m command -a 'date'
172.17.0.4 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:38 CST
172.17.0.5 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:38 CST
172.17.0.6 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:38 CST
172.17.0.3 | CHANGED | rc=0 >>
2021年 09月 23日 星期四 16:32:38 CST
[root@node2 ansible]#
如果不加-m模块,则默认运行command模块
[root@node2 ansible]# ansible all -a 'ls /'
172.17.0.5 | CHANGED | rc=0 >>
bin
data
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
172.17.0.3 | CHANGED | rc=0 >>
bin
data
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
172.17.0.4 | CHANGED | rc=0 >>
bin
data
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
172.17.0.6 | CHANGED | rc=0 >>
bin
data
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@node2 ansible]#
6.3.cron模块
用于定义任务计划
两种状态(state) : present表示添加(可以省略),absent表示移除。
查看cron模块信息
[root@node2 ansible]# 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.
To use 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 is not set and `state=present', then a new crontab entry will
always be created, regardless of existing ones. This parameter will always be
required in future releases.
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 variable is present or absent.
user: # The specific user whose crontab should be modified. When unset, this parameter defaults to using `root'.
weekday: # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
[root@node2 ansible]#
yum -y install crontabs (Linux上的crontab没有安装的时候执行此命令,若是docker虚拟化出来的机器,则没有crontab)
[root@node2 ansible]# ansible abc -m cron -a 'minute="*/1" job="/usr/bin/echo hello word" name="test cron job"'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"test cron job"
]
}
[root@node2 ansible]#
列出所有的Linux任务调度的配置
[root@node2 ansible]# ansible abc -a 'crontab -l'
172.17.0.3 | CHANGED | rc=0 >>
#Ansible: test cron job
*/1 * * * * /usr/bin/echo hello word
[root@node2 ansible]#
移除计划任务,假设该计划任务没有取名字,name = None即可
[root@node2 ansible]# ansible abc -m cron -a 'name="test cron job" state=absent'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
[root@node2 ansible]# ansible abc -a 'crontab -l'
172.17.0.3 | CHANGED | rc=0 >>
[root@node2 ansible]#
6.4.user模块
- 用于创建新用户和更改、删除已存在的用户
- user模块是请求的是useradd, userdel, usermod三个指令
[root@node2 ansible]# 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. Mutually exclusive with
`local'
authorization: # Sets the authorization of the user. Does nothing when used with other platforms. Can set multiple authorizations
using comma separation. To delete all authorizations, use `authorization='''.
Currently supported on Illumos/Solaris.
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 or if the home directory
does not exist. Changed from `createhome' to `create_home' in Ansible 2.5.
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 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. When used with `generate_ssh_key=yes' this
forces an existing key to be overwritten.
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'.
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 `''', 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. Mutually exclusive with `local'
hidden: # macOS only, optionally hide the user from the login window and system preferences. The default will be `yes' if the
`system' option is used.
home: # Optionally set the user's home directory.
local: # Forces the use of "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 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. Mutually exclusive with `groups' and
`append'
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 macOS systems, this value has to be cleartext. Beware
of security issues. To create a disabled account on Linux systems, set this to `'!''
or `'*''. To create a disabled account on OpenBSD, set this to `'*************''.
See https://docs.ansible.com/ansible/faq.html#how-do-i-generate-encrypted-passwords-
for-the-user-module for details on various ways to generate these password values.
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 to `False' 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.
profile: # Sets the profile of the user. Does nothing when used with other platforms. Can set multiple profiles using comma
separation. To delete all the profiles, use `profile='''. Currently supported on
Illumos/Solaris.
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.
role: # Sets the role of the user. Does nothing when used with other platforms. Can set multiple roles using comma
separation. To delete all roles, use `role='''. Currently supported on
Illumos/Solaris.
seuser: # Optionally sets the seuser type (user_u) on selinux enabled systems.
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 being used. See Notes for details.
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. This parameter defaults to `.ssh/id_rsa'.
ssh_key_passphrase: # Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase.
ssh_key_type: # Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present
on target host.
state: # Whether the account should exist or not, 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@node2 ansible]#
创建用户test01
[root@node2 ansible]# ansible abc -m user -a 'name="test01"'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 1000,
"home": "/home/test01",
"name": "test01",
"shell": "/bin/bash",
"state": "present",
"stderr": "useradd: warning: the home directory already exists.\nNot copying any file from skel directory into it.\nCreating mailbox fi exists\n",
"stderr_lines": [
"useradd: warning: the home directory already exists.",
"Not copying any file from skel directory into it.",
"Creating mailbox file: File exists"
],
"system": false,
"uid": 1000
}
查看有哪些用户
[root@node2 ansible]# ansible abc -m command -a 'tail /etc/passwd'
172.17.0.3 | CHANGED | rc=0 >>
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
test01:x:1000:1000::/home/test01:/bin/bash
删除用户test01
[root@node2 ansible]# ansible abc -m user -a 'name="test01" state=absent'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "test01",
"remove": false,
"state": "absent"
}
[root@node2 ansible]# ansible abc -m command -a 'tail /etc/passwd'
172.17.0.3 | CHANGED | rc=0 >>
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
[root@node2 ansible]#
6.5.group模块
对用户组进行管理
group模块请求的是groupadd, groupdel, groupmod 三个指令。
[root@node2 ansible]# ansible-doc -s group
- name: Add or remove groups
group:
gid: # Optional `GID' to set for the 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. (e.g. it
uses `lgroupadd' instead of `groupadd').
This requires that these commands exist
on the targeted host, otherwise it will
be a fatal error.
name: # (required) Name of the group to manage.
non_unique: # This option allows to change the group ID to a non-unique value.
Requires `gid'. Not supported on macOS
or BusyBox distributions.
state: # Whether the group should be present or not on the remote host.
system: # If `yes', indicates that the group created is a system group.
[root@node2 ansible]#
[root@node2 ansible]# ansible abc -m group -a 'name=mysql gid=306 system=yes'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 306,
"name": "mysql",
"state": "present",
"system": true
}
[root@node2 ansible]# ansible abc -a 'tail /etc/group'
172.17.0.3 | CHANGED | rc=0 >>
users:x:100:
utmp:x:22:
utempter:x:35:
input:x:999:
systemd-journal:x:190:
systemd-network:x:192:
dbus:x:81:
ssh_keys:x:998:
sshd:x:74:
mysql:x:306:
[root@node2 ansible]# ansible abc -m user -a 'name=test01 uid=306 system=yes group=mysql'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 306,
"home": "/home/test01",
"name": "test01",
"shell": "/bin/bash",
"state": "present",
"stderr": "useradd: warning: the home directory already exists.\nNot copying any file from skel directory into it.\n",
"stderr_lines": [
"useradd: warning: the home directory already exists.",
"Not copying any file from skel directory into it."
],
"system": true,
"uid": 306
}
[root@node2 ansible]# ansible abc -a 'tail /etc/passwd'
172.17.0.3 | CHANGED | rc=0 >>
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
test01:x:306:306::/home/test01:/bin/bash
[root@node2 ansible]# ansible abc -a 'id test01'
172.17.0.3 | CHANGED | rc=0 >>
uid=306(test01) gid=306(mysql) groups=306(mysql)
[root@node2 ansible]#
6.6.copy模块
用于实现文件复制和批量下发文件 (src: 本地路径 dest: 被管理主机文件路径)
[root@node2 ansible]# ansible-doc -s copy
- name: Copy files to remote locations
copy:
attributes: # The attributes the resulting file or 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'. The `=' operator is assumed as
default, otherwise `+' or `-' operators
need to be included in the string.
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
is not 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. Works only when `dest'
is a file. Creates the file if it does
not exist. For advanced formatting or if
`content' contains a variable, use 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 non-
existent path and if either `dest' ends
with "/" or `src' is a directory, `dest'
is created. If `dest' is a relative
path, the starting directory is
determined by the remote host. If `src'
and `dest' are files, the parent
directory of `dest' is not created and
the task fails if it does not already
exist.
XXXXXXXXXXXXXXX
[root@node2 ansible]# ansible abc -m copy -a 'src=/etc/profile dest=/opt/profile owner=root mode=640' (属主root 权限640)
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "f0a7d47369ebb1db94615127fe1e49a50a9d6408",
"dest": "/opt/profile",
"gid": 0,
"group": "root",
"md5sum": "86bdbd599798794217c36952f2798056",
"mode": "0640",
"owner": "root",
"size": 1998,
"src": "/root/.ansible/tmp/ansible-tmp-1632446026.09-292-140987703647515/source",
"state": "file",
"uid": 0
}
[root@node2 ansible]#
[root@node2 ansible]# ansible abc -a 'ls -l /opt'
172.17.0.3 | CHANGED | rc=0 >>
total 4
-rw-r----- 1 root root 1998 9月 24 09:13 profile
[root@node2 ansible]# ansible abc -a 'cat /opt/profile'
172.17.0.3 | CHANGED | rc=0 >>
# /etc/profile
# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc
xxxxxxxxxxxxxxxxxxx
unset i
unset -f pathmunge
export LC_ALL=zh_CN.utf8
export JAVA_HOME=/root/installed/jdk1.8.0_301
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
[root@node2 ansible]#
[root@node2 ansible]# ansible abc -m copy -a 'content="hello world!" dest=/opt/profile'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "430ce34d020724ed75a196dfc2ad67c77772d169",
"dest": "/opt/profile",
"gid": 0,
"group": "root",
"md5sum": "fc3ff98e8c6a0d3087d515c0473f8677",
"mode": "0640",
"owner": "root",
"size": 12,
"src": "/root/.ansible/tmp/ansible-tmp-1632446547.71-368-138658873127975/source",
"state": "file",
"uid": 0
}
[root@node2 ansible]# ansible abc -a 'cat /opt/profile'
172.17.0.3 | CHANGED | rc=0 >>
hello world!
[root@node2 ansible]#
6.7.file模块
用于设置文件属性 (path: 文件路径 src: 定义源文件路径)
[root@node2 ansible]# ansible-doc -s file
- name: Manage files and file properties
file:
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, or `now'. Default is `None'
meaning that `preserve' is the default for
`state=[file,directory,link,hard]' and `now'
is default for `state=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).
attributes: # The attributes the resulting file or 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'. The `=' operator is
assumed as default, otherwise `+' or `-'
operators need to be included in the string.
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 and is a file (so, we need to unlink
the `path' file and create symlink to the
`src' file in place of it).
group: # Name of the group that should own the file/directory, as would be fed to
`chown'.
mode: # The permissions the resulting file or directory should have. 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 (like `0644' or
`01777') 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' or
`u=rw,g=r,o=r').
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, or `now'. Default is None
meaning that `preserve' is the default for
`state=[file,directory,link,hard]' and `now'
is default for `state=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).
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.
recurse: # Recursively set the specified file attributes on directory contents. This
applies only when `state' is set to
`directory'.
selevel: # The level part of the SELinux file context. This is the MLS/MCS attribute,
sometimes known as the `range'. When set to
`_default', it will use the `level' portion of
the policy if available.
serole: # The role part of the SELinux file context. When set to `_default', it will
use the `role' portion of the policy if
available.
setype: # The type part of the SELinux file context. When set to `_default', it will
use the `type' portion of the policy if
available.
seuser: # The user part of the SELinux file context. By default it uses the `system'
policy, where applicable. When set to
`_default', it will use the `user' portion of
the policy if available.
src: # Path of the file to link to. This applies only to `state=link' and
`state=hard'. For `state=link', this will also
accept a non-existing path. 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 `absent', directories will be recursively deleted, and files or symlinks
will be unlinked. In the case of a directory,
if `diff' is declared, you will see the files
and folders deleted listed under
`path_contents'. Note that `absent' will not
cause `file' to fail if the `path' does not
exist as the state did not change. 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', without any
other options this works mostly as a 'stat'
and will return the current state of `path'.
Even with other options (i.e `mode'), the file
will be modified but 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 `hard', the hard link will be
created or changed. If `link', the symbolic
link will be created or changed. If `touch'
(new in 1.4), an empty file will be created if
the `path' does not exist, while an existing
file or directory will receive updated file
access and modification times (similar to the
way `touch' works from the command line).
unsafe_writes: # Influence when to use atomic operation to prevent data corruption or
inconsistent reads from the target file. By
default this module uses atomic operations to
prevent data corruption or inconsistent reads
from the target files, but sometimes systems
are configured or just broken in ways that
prevent this. One example is docker mounted
files, 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 files 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.
[root@node2 ansible]#
[root@node2 ansible]# ansible abc -m user -a 'name=mysql system=yes'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 100,
"home": "/home/mysql",
"name": "mysql",
"shell": "/bin/bash",
"state": "present",
"system": true,
"uid": 305
}
[root@node2 ansible]# ansible abc -m group -a 'name=mysql system=yes'
172.17.0.3 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"gid": 306,
"name": "mysql",
"state": "present",
"system": true
}
[root@node2 ansible]# ansible abc -m file -a 'owner=mysql group=mysql mode=644 path=/opt/profile'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 306,
"group": "mysql",
"mode": "0644",
"owner": "mysql",
"path": "/opt/profile",
"size": 12,
"state": "file",
"uid": 305
}
[root@node2 ansible]# ansible abc -a 'ls -l /opt/profile'
172.17.0.3 | CHANGED | rc=0 >>
-rw-r--r-- 1 mysql mysql 12 9月 24 09:22 /opt/profile
[root@node2 ansible]# ansible abc -m file -a 'path=/opt/profile.link src=/opt/profile state=link'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/opt/profile.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 12,
"src": "/opt/profile",
"state": "link",
"uid": 0
}
[root@node2 ansible]# ansible abc -a 'ls -l /opt/'
172.17.0.3 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 mysql mysql 12 9月 24 09:22 profile
lrwxrwxrwx 1 root root 12 9月 24 09:35 profile.link -> /opt/profile
[root@node2 ansible]# ansible abc -m file -a 'path=/opt/profile state=absent'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/opt/profile",
"state": "absent"
}
[root@node2 ansible]# ansible abc -a 'ls -l /opt/'
172.17.0.3 | CHANGED | rc=0 >>
total 0
lrwxrwxrwx 1 root root 12 9月 24 09:35 profile.link -> /opt/profile
[root@node2 ansible]# ansible abc -m file -a "path=/opt/test state=touch"
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/opt/test",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
[root@node2 ansible]#
6.8.ping模块
用于检测指定主机的连通性
[root@node2 ansible]# ansible all -m ping
172.17.0.5 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
172.17.0.4 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
172.17.0.3 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
172.17.0.6 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@node2 ansible]#
6.9.shell模块
可以再被管理主机上运行命令,并支持像管道符号等功能的复杂命令
可以创建用户使用五交互模式给用户设置密码
[root@node2 ansible]# ansible-doc -s shell
- name: Execute shell commands on targets
shell:
chdir: # Change into this directory before running the command.
cmd: # The command to run followed by optional arguments.
creates: # A filename, when it already exists, this step will *not* be run.
executable: # Change the shell used to execute the command. This expects an
absolute path to the executable.
free_form: # The shell module takes a free form command to run, as a string.
There is no actual parameter named
'free form'. See the examples on
how to use this module.
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.
stdin_add_newline: # Whether to append a newline to stdin data.
warn: # Whether to enable task warnings.
[root@node2 ansible]# ansible abc -m shell -a 'echo abc123'
172.17.0.3 | CHANGED | rc=0 >>
abc123
[root@node2 ansible]#
6.10.service模块
- 用来控制管理服务的运行状态
- enabled:开机自启动,取值ture或false ,name:定义服务名称,state指定服务状态取值分别为started 、stoped、restarted
[root@node2 ~]# yum install -y httpd (到abc组的主机装httpd abc需要有httpd服务才能控制)
[root@node2 ~]# 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-in for
a status result. If the string
is found, the service will be
assumed to be started.
runlevel: # For OpenRC init scripts (e.g. 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
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.
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.
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@node2 ~]#
[root@node2 ~]# ansible abc -m service -a 'enabled=true name=httpd state=started'
[root@node2 ~]# ansible abc -a 'systemctl status httpd' //查看web服务器httpd运行状态
6.11.script模块
可以将本地脚本复制到被管理主机上进行执行。需要注意使用相对路径来指定脚本。
[root@node2 ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # Change into this directory on the remote node before running
the script.
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.
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: # Path to the local script file followed by optional arguments.
removes: # A filename on the remote node, when it does not exist, this
step will *not* be run.
[root@node2 ~]# vim test.sh
[root@node2 ~]# chmod +x test.sh
[root@node2 ~]# cat test.sh
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt
[root@node2 ~]# ansible abc -m script -a 'test.sh'
172.17.0.3 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 172.17.0.3 closed.\r\n",
"stderr_lines": [
"Shared connection to 172.17.0.3 closed."
],
"stdout": "",
"stdout_lines": []
}
[root@node2 ~]# ansible abc -a 'cat /opt/script.txt'
172.17.0.3 | CHANGED | rc=0 >>
hello ansible from script
6.12.yum模块
- 负责在被管理主机上安装与卸载软件包,需要提前在每个节点配置自己的YUM仓库。
- name:指定安装的软件包,可以带上版本号,否则安装最新版本。
- state :指定安装的软件包状态 (present、latest 表示安装 , absent 表示卸载)
[root@node2 ~]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
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).
autoremove: # If `yes', 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+)
bugfix: # If set to `yes', and `state=latest' then only installs
updates that have been marked
bugfix related.
conf_file: # The remote yum configuration file to use for the transaction.
disable_excludes: # Disable the excludes defined in YUM config files. If set to
`all', disables all excludes.
If set to `main', disable
excludes defined in [main] in
yum.conf. If set to `repoid',
disable excludes defined for
given repo id.
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 `","'. As of Ansible
2.7, this can alternatively be
a list instead of `","'
separated string
download_dir: # Specifies an alternate directory to store packages. Has an
effect only if `download_only'
is specified.
download_only: # Only download the packages, do not install them.
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 `","'. As of Ansible
2.7, this can alternatively be
a list instead of `","'
separated string
exclude: # Package name(s) to exclude when state=present, or latest
install_weak_deps: # Will also install all packages linked by a weak dependency
relation. NOTE: This feature
requires yum >= 4 (RHEL/CentOS
8+)
installroot: # Specifies an alternative installroot, relative to which all
packages will be installed.
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' and
`repos'. This parameter is
mutually exclusive with
`name'.
lock_timeout: # Amount of time to wait for the yum lockfile to be freed.
name: # A package name or package 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 string of packages
or (as of 2.0) a list of
packages.
releasever: # Specifies an alternative release from which all packages will
be installed.
security: # If set to `yes', and `state=latest' then only installs
updates that have been marked
security related.
skip_broken: # Skip packages with broken dependencies(devsolve) and are
causing problems.
state: # Whether to install (`present' or `installed', `latest'), or
remove (`absent' or `removed')
a package. `present' and
`installed' 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'
and `removed' will remove the
specified package. Default is
`None', however in effect the
default action is `present'
unless the `autoremove' option
is enabled for this module,
then `absent' is inferred.
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'.
update_only: # When using latest, only update installed packages. Do not
install packages. Has an
effect only if state is
`latest'
use_backend: # This module supports `yum' (as it always has), this is known
as `yum3'/`YUM3'/`yum-
deprecated' by upstream yum
developers. As of Ansible
2.7+, this module also
supports `YUM4', which is the
"new yum" and it has an `dnf'
backend. By default, this
module will select the backend
based on the `ansible_pkg_mgr'
fact.
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 to 2.1 the code
worked as if this was set to
`yes'.
[root@node2 ~]#
[root@node2 ~]# ansible abc -m yum -a 'name=zsh'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"zsh"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror, ovl\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.ustc.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n zsh x86_64 5.0.2-34.el7_8.2 base 2.4 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.4 M\nInstalled size: 5.6 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : zsh-5.0.2-34.el7_8.2.x86_64 1/1 \n Verifying : zsh-5.0.2-34.el7_8.2.x86_64 1/1 \n\nInstalled:\n zsh.x86_64 0:5.0.2-34.el7_8.2 \n\nComplete!\n"
]
}
[root@node2 ~]# ansible abc -a 'rpm -q zsh'
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'. If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
172.17.0.3 | CHANGED | rc=0 >>
zsh-5.0.2-34.el7_8.2.x86_64
[root@node2 ~]# ansible abc -m yum -a 'name=zsh state=absent'
172.17.0.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"zsh"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror, ovl\nResolving Dependencies\n--> Running transaction check\n---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n zsh x86_64 5.0.2-34.el7_8.2 @base 5.6 M\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 5.6 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : zsh-5.0.2-34.el7_8.2.x86_64 1/1 \n Verifying : zsh-5.0.2-34.el7_8.2.x86_64 1/1 \n\nRemoved:\n zsh.x86_64 0:5.0.2-34.el7_8.2 \n\nComplete!\n"
]
}
[root@node2 ~]# ansible abc -a 'rpm -q zsh'
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'. If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
172.17.0.3 | FAILED | rc=1 >>
package zsh is not installednon-zero return code
[root@node2 ~]#
6.13.setup模块
用于收集、查看被管理主机的facts(facts是Ansible采集被管理主机设备信息的一个功能)
[root@node2 ~]# 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 file is not
executable it is read. Check notes for
Windows options. (from 2.1 on) File/results
format can be JSON or INI-format. The default
`fact_path' can be specified in `ansible.cfg'
for when setup is automatically called as
part of `gather_facts'.
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 `!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.
[root@node2 ~]# ansible abc -m setup
172.17.0.3 | SUCCESS => {
"ansible_facts": {
"ansible_apparmor": {
"status": "disabled"
},
"ansible_architecture": "x86_64",
"ansible_bios_date": "NA",
"ansible_bios_version": "NA",
"ansible_cmdline": {
"initrd": "\\initrd.img",
"nr_cpus": "8",
"panic": "-1",
"pty.legacy_count": "0"
},
"ansible_date_time": {
"date": "2021-09-27",
"day": "27",
"epoch": "1632704107",
"hour": "08",
"iso8601": "2021-09-27T00:55:07Z",
"iso8601_basic": "20210927T085507771039",
"iso8601_basic_short": "20210927T085507",
"iso8601_micro": "2021-09-27T00:55:07.771039Z",
"minute": "55",
"month": "09",
"second": "07",
"time": "08:55:07",
"tz": "CST",
"tz_offset": "+0800",
"weekday": "星期一",
"weekday_number": "1",
"weeknumber": "39",
"year": "2021"
}
6.14.字符串处理
https://www.zsythink.net/archives/3277
7.YAML语法
转自:https://ansible-tran.readthedocs.io/en/latest/docs/YAMLSyntax.html
这个页面提供一个正确的 YAML 语法的基本概述, 它被用来描述一个 playbooks(我们的配置管理语言).
我们使用 YAML 是因为它像 XML 或 JSON 是一种利于人们读写的数据格式. 此外在大多数变成语言中有使用 YAML 的库.
你可能希望读 Playbooks 实践中如何使用的.
7.1.基本的YAML
对于 Ansible, 每一个 YAML 文件都是从一个列表开始. 列表中的每一项都是一个键值对, 通常它们被称为一个 “哈希” 或 “字典”. 所以, 我们需要知道如何在 YAML 中编写列表和字典.
YAML 还有一个小的怪癖. 所有的 YAML 文件(无论和 Ansible 有没有关系)开始行都应该是 —. 这是 YAML 格式的一部分, 表明一个文件的开始.
列表中的所有成员都开始于相同的缩进级别, 并且使用一个 "- " 作为开头(一个横杠和一个空格):
---
# 一个美味水果的列表
- Apple
- Orange
- Strawberry
- Mango
一个字典是由一个简单的 “键: 值” 的形式组成(这个冒号后面必须是一个空格):
---
# 一位职工的记录
name: Example Developer
job: Developer
skill: Elite
字典也可以使用缩进形式来表示,如果你喜欢这样的话:
---
# 一位职工的记录
{
name: Example Developer, job: Developer, skill: Elite}
Ansible并不是太多的使用这种格式,但是你可以通过以下格式来指定一个布尔值(true/false):
---
create_key: yes
needs_agent: no
knows_oop: True
likes_emacs: TRUE
uses_cvs: false
让我们把目前所学到的 YAML 例子组合在一起. 这些在 Ansible 中什么也干不了, 但这些格式将会给你感觉:
---
# 一位职工记录
name: Example Developer
job: Developer
skill: Elite
employed: True
foods:
- Apple
- Orange
- Strawberry
- Mango
languages:
ruby: Elite
python: Elite
dotnet: Lame
这就是你开始编写 Ansible playbooks 所需要知道的所有 YAML 语法.
7.2.Gotchas
尽管YAML通常是友好的,但是下面将会导致一个YAML语法错误:
foo: somebody said I should put a colon here: so I did
你需要使用引号来包裹任何冒号的哈希值,像这样:
foo: "somebody said I should put a colon here: so I did"
然后这个冒号将会被结尾.
此外, Ansible 使用 “{ { var }}” 来引用变量. 如果一个值以 “{” 开头, YAML 将认为它是一个字典, 所以我们必须引用它, 像这样:
foo: "{
{ variable }}"