安装
[root@centos8-1 ~]# dnf install ansible
查看安装后生成的文件
[root@centos8-1 ~]# rpm -ql ansible | less /etc/ansible /etc/ansible/ansible.cfg ---》配置文件 /etc/ansible/hosts -----》被管理主机清单文件 /etc/ansible/roles---》存放角色目录文件 /usr/bin/ansible /usr/bin/ansible-config /usr/bin/ansible-connection /usr/bin/ansible-console /usr/bin/ansible-doc /usr/bin/ansible-galaxy /usr/bin/ansible-inventory /usr/bin/ansible-playbook /usr/bin/ansible-pull /usr/bin/ansible-test /usr/bin/ansible-vault /usr/lib/python3.6/site-packages/ansible /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/PKG-INFO /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/SOURCES.txt /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/dependency_links.txt /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/not-zip-safe /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/requires.txt /usr/lib/python3.6/site-packages/ansible-2.9.18-py3.6.egg-info/top_level.txt /usr/lib/python3.6/site-packages/ansible/__init__.py /usr/lib/python3.6/site-packages/ansible/__pycache__ /usr/lib/python3.6/site-packages/ansible/__pycache__/__init__.cpython-36.opt-1.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/__init__.cpython-36.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/constants.cpython-36.opt-1.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/constants.cpython-36.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/context.cpython-36.opt-1.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/context.cpython-36.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/release.cpython-36.opt-1.pyc /usr/lib/python3.6/site-packages/ansible/__pycache__/release.cpython-36.pyc /usr/lib/python3.6/site-packages/ansible/cli /usr/lib/python3.6/site-packages/ansible/cli/__init__.py /usr/lib/python3.6/site-packages/ansible/cli/__pycache__ /usr/lib/python3.6/site-packages/ansible/cli/__pycache__/__init__.cpython-36.opt-1.pyc /usr/lib/python3.6/site-packages/ansible/cli/__pycache__/__init__.cpython-36.pyc /usr/lib/python3.6/site-packages/ansible/cli/__pycache__/adhoc.cpython-36.opt-1.pyc :
主配文件
[root@centos8-1 ~]# vim /etc/ansible/ansible.cfg # config file for ansible -- https://ansible.com/ # =============================================== # nearly all parameters can be overridden in ansible-playbook # or with command line flags. ansible will read ANSIBLE_CONFIG, # ansible.cfg in the current working directory, .ansible.cfg in # the home directory or /etc/ansible/ansible.cfg, whichever it # finds first [defaults] 默认配置 # some basic default values... #inventory = /etc/ansible/hosts 主机清单 #library = /usr/share/my_modules/ 库文件存放目录 #module_utils = /usr/share/my_module_utils/ 模块 #remote_tmp = ~/.ansible/tmp 临时py目录文件存放的远程主机目录 #local_tmp = ~/.ansible/tmp 本机的临时命令执行目录 #plugin_filters_cfg = /etc/ansible/plugin_filters.yml #forks = 5 并发数 #poll_interval = 15 #sudo_user = root 默认用户 #ask_sudo_pass = True 每次执行是否需要输入密码 #ask_pass = True #transport = smart #remote_port = 22 #module_lang = C #module_set_locale = False # plays will gather facts by default, which contain information about # the remote system. # # smart - gather by default, but don't regather if already gathered # implicit - gather by default, turn off with gather_facts: False # explicit - do not gather by default, must say gather_facts: True #gathering = implicit # This only affects the gathering done by a play's gather_facts directive, # by default gathering retrieves all facts subsets # all - gather all subsets # network - gather min and network facts # hardware - gather hardware facts (longest facts to retrieve) # virtual - gather min and virtual facts # facter - import facts from facter # ohai - import facts from ohai # You can combine them using comma (ex: network,virtual) # You can negate them using ! (ex: !hardware,!facter,!ohai) # A minimal set of facts is always gathered. #gather_subset = all # some hardware related facts are collected # with a maximum timeout of 10 seconds. This # option lets you increase or decrease that # timeout to something more suitable for the # environment. # gather_timeout = 10 # Ansible facts are available inside the ansible_facts.* dictionary # namespace. This setting maintains the behaviour which was the default prior # to 2.5, duplicating these variables into the main namespace, each with a # prefix of 'ansible_'. # This variable is set to True by default for backwards compatibility. It # will be changed to a default of 'False' in a future release. # ansible_facts. # inject_facts_as_vars = True # additional paths to search for roles in, colon separated #roles_path = /etc/ansible/roles # uncomment this to disable SSH key host checking #host_key_checking = False 不检查host key建议取消 # change the default callback, you can only have one 'stdout' type enabled at a time. #stdout_callback = skippy ## Ansible ships with some plugins that require whitelisting, ## this is done to avoid running all of a type by default. ## These setting lists those that you want enabled for your system. ## Custom plugins should not need this unless plugin author specifies it. # enable callback plugins, they can output to stdout but cannot be 'stdout' type. #callback_whitelist = timer, mail # Determine whether includes in tasks and handlers are "static" by # default. As of 2.0, includes are dynamic by default. Setting these # values to True will make includes behave more like they did in the # 1.x versions. #task_includes_static = False #handler_includes_static = False # Controls if a missing handler for a notification event is an error or a warning #error_on_missing_handler = True # change this for alternative sudo implementations #sudo_exe = sudo # What flags to pass to sudo # WARNING: leaving out the defaults might create unexpected behaviours #sudo_flags = -H -S -n # SSH timeout #timeout = 10 # default user to use for playbooks if user is not specified # (/usr/bin/ansible will use current user as default) #remote_user = root # logging is off by default unless this path is defined # if so defined, consider logrotate #log_path = /var/log/ansible.log 日志记录操作 # default module name for /usr/bin/ansible #module_name = command 修改默认模块 # use this shell for commands executed under sudo # you may need to change this to bin/bash in rare instances # if sudo is constrained #executable = /bin/sh # if inventory variables overlap, does the higher precedence one win # or are hash values merged together? The default is 'replace' but # this can also be set to 'merge'. #hash_behaviour = replace # by default, variables from roles will be visible in the global variable # scope. To prevent this, the following option can be enabled, and only # tasks and handlers within the role will see the variables there #private_role_vars = yes # list any Jinja2 extensions to enable here: #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n # if set, always use this private key file for authentication, same as # if passing --private-key to ansible or ansible-playbook #private_key_file = /path/to/file # If set, configures the path to the Vault password file as an alternative to # specifying --vault-password-file on the command line. #vault_password_file = /path/to/vault_password_file # format of string {{ ansible_managed }} available within Jinja2 # templates indicates to users editing templates files will be replaced. # replacing {file}, {host} and {uid} and strftime codes with proper values. #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} # {file}, {host}, {uid}, and the timestamp can all interfere with idempotence # in some situations so the default is a static string: #ansible_managed = Ansible managed
配置主机清单文件
[root@centos8-1 ~]# cat /etc/ansible/hosts # This is the default ansible 'hosts' file. # # It should live in /etc/ansible/hosts # # - Comments begin with the '#' character # - Blank lines are ignored # - Groups of hosts are delimited by [header] elements # - You can enter hostnames or ip addresses # - A hostname/ip can be a member of multiple groups # Ex 1: Ungrouped hosts, specify before any group headers. ## green.example.com ## blue.example.com ## 192.168.100.1 ## 192.168.100.10 # Ex 2: A collection of hosts belonging to the 'webservers' group ## [webservers] ## alpha.example.org ## beta.example.org ## 192.168.1.100 ## 192.168.1.110 # If you have multiple hosts following a pattern you can specify # them like this: ## www[001:006].example.com # Ex 3: A collection of database servers in the 'dbservers' group ## [dbservers] ## ## db01.intranet.mydomain.net ## db02.intranet.mydomain.net ## 10.25.1.56 ## 10.25.1.57 # Here's another example of host ranges, this time there are no # leading 0s: ## db-[99:101]-node.example.com [nginx] 192.168.10.29 [mysql] 192.168.10.28 [host] 192.168.10.[28:29]#表示28~29区间所有主机 [root@centos8-1 ~]#
ansible-doc 介绍
ansible-doc -l 列出所有模块 ansible-doc ping 查看模块用法 ansible-doc -s ping 查看用法说明
ansible 用法
ansible <host-pattern> [-m 模块名] [-a args] positional arguments: pattern host pattern optional arguments: --ask-vault-pass ask for vault password --list-hosts outputs a list of matching hosts; does not execute anything else --playbook-dir BASEDIR Since this tool does not use playbooks, use this as a substitute playbook directory.This sets the relative path for many features including roles/ group_vars/ etc. --syntax-check perform a syntax check on the playbook, but do not execute it --vault-id VAULT_IDS the vault identity to use --vault-password-file VAULT_PASSWORD_FILES vault password file --version show program's version number, config file location, configured module search path, module location, executable location and exit -B SECONDS, --background SECONDS run asynchronously, failing after X seconds (default=N/A) -C, --check don't make any changes; instead, try to predict some of the changes that may occur -D, --diff when changing (small) files and templates, show the differences in those files; works great with --check -M MODULE_PATH, --module-path MODULE_PATH prepend colon-separated path(s) to module library (def ault=~/.ansible/plugins/modules:/usr/share/ansible/plu gins/modules) -P POLL_INTERVAL, --poll POLL_INTERVAL set the poll interval if using -B (default=15) -a MODULE_ARGS, --args MODULE_ARGS module arguments -e EXTRA_VARS, --extra-vars EXTRA_VARS set additional variables as key=value or YAML/JSON, if filename prepend with @ -f FORKS, --forks FORKS specify number of parallel processes to use (default=5) -h, --help show this help message and exit -i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY specify inventory host path or comma separated host list. --inventory-file is deprecated -l SUBSET, --limit SUBSET further limit selected hosts to an additional pattern -m MODULE_NAME, --module-name MODULE_NAME module name to execute (default=command) -o, --one-line condense output -t TREE, --tree TREE log output to this directory -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) Privilege Escalation Options: control how and which user you become as on target hosts --become-method BECOME_METHOD privilege escalation method to use (default=sudo), use `ansible-doc -t become -l` to list valid choices. --become-user BECOME_USER run operations as this user (default=root) -K, --ask-become-pass ask for privilege escalation password -b, --become run operations with become (does not imply password prompting) Connection Options: control as whom and how to connect to hosts --private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE use this file to authenticate the connection --scp-extra-args SCP_EXTRA_ARGS specify extra arguments to pass to scp only (e.g. -l) --sftp-extra-args SFTP_EXTRA_ARGS specify extra arguments to pass to sftp only (e.g. -f, -l) --ssh-common-args SSH_COMMON_ARGS specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand) --ssh-extra-args SSH_EXTRA_ARGS specify extra arguments to pass to ssh only (e.g. -R) -T TIMEOUT, --timeout TIMEOUT override the connection timeout in seconds (default=10) -c CONNECTION, --connection CONNECTION connection type to use (default=smart) -k, --ask-pass ask for connection password -u REMOTE_USER, --user REMOTE_USER connect as this user (default=None) Some modules do not make sense in Ad-Hoc (include, meta, etc)
测试失败
[root@centos8-1 ~]# ansible all -m ping 192.168.10.29 | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.10.29' (ECDSA) to the list of known hosts. root@192.168.10.29: Permission denied (publickey,gssapi-keyex,gssapi-with-mi c,password).", "unreachable": true } 192.168.10.28 | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.10.28' (ECDSA) to the list of known hosts. root@192.168.10.28: Permission denied (publickey,gssapi-keyex,gssapi-with-mi c,password).", "unreachable": true }
做密钥认证
[root@centos8-1 ~]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:v1u+6BFKkEr58Oans+9p5NIlg+vsKj89COVnUpj3hZs root@ansible The key's randomart image is: +---[RSA 3072]----+ | | | . . | | +oo . | | .+=o.. . | | o.o+oS+. | | . oo+.Eo.. | | . *.=o+o . | | . o.*o+. * | | oo=*O+.=.o. | +----[SHA256]-----+ [root@centos8-1 ~]# ssh-copy-id 192.168.10.28 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@192.168.10.28's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.10.28'" and check to make sure that only the key(s) you wanted were added. [root@centos8-1 ~]# ssh-copy-id 192.168.10.29 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@192.168.10.29's password: Permission denied, please try again. root@192.168.10.29's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.10.29'" and check to make sure that only the key(s) you wanted were added. [root@centos8-1 ~]# ssh-copy-id 192.168.10.40 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" The authenticity of host '192.168.10.40 (192.168.10.40)' can't be established. ECDSA key fingerprint is SHA256:Pfk6OIfOVci5diYlVynJaixbnJCL9HD0XGIRy4firYo. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@192.168.10.40's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.10.40'" and check to make sure that only the key(s) you wanted were added.
测试
[root@centos8-1 ~]# ansible all -m ping 192.168.10.29 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } 192.168.10.28 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } 192.168.10.40 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false, "ping": "pong" } ansible all -m ping all 表示被管理所有主机 -m 指定模块 ping 模块名字
查看被管理的主机
[root@centos8-1 ~]# ansible all --list-host hosts (3): 192.168.10.29 192.168.10.28 192.168.10.40
查看指定组的机器
[root@centos8-1 ~]# ansible nginx --list-host hosts (1): 192.168.10.29
ansible-galaxy 的介绍
[root@centos8-1 ~]# ansible-galaxy list 查看 # /usr/share/ansible/roles # /etc/ansible/roles [root@centos8-1 ~]# ansible-galaxy install dev-sec.mysql-hardening 安装 - downloading role 'mysql-hardening', owned by dev-sec - downloading role from https://github.com/dev-sec/ansible-mysql-hard ening/archive/2.2.1.tar.gz- extracting dev-sec.mysql-hardening to /root/.ansible/roles/dev-sec. mysql-hardening- dev-sec.mysql-hardening (2.2.1) was installed successfully [root@centos8-1 ~]# ansible-galaxy remove dev-sec.mysql-hardening 删除 - successfully removed dev-sec.mysql-hardening
ansible-vault 加密解密
ansible-vault encrypt yaml文件 加密 ansible-vault decrypt yaml 文件 解密
ansible-console 交互式终端
[root@centos8-1 ~]# ansible-console Welcome to the ansible console. Type help or ? to list commands. root@all (3)[f:5]$ forks 9 调整并发数量 root@all (3)[f:9]$ list 192.168.10.29 192.168.10.28 192.168.10.40 root@all (3)[f:9]$ yum name=epel* 安装 root@all (3)[f:9]$ cd nginx 切换资源组 root@nginx (1)[f:9]$ cd all
command 模块
[root@centos8-1 ~]# ansible nginx -m command -a"touch /root/1.txt" [WARNING]: Consider using the file module with state=touch rather tha n running'touch'. If you need to use command because file 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. 192.168.10.29 | CHANGED | rc=0 >>
介绍
[root@centos8-1 ~]# ansible-doc -s command - name: Execute commands on targets command: 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 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.到指定目录下执行 cmd: # The command to run. 运行的命令 creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run. free_form: # The command module takes a free form command to run. There is no actual parameter named 'free form'. removes: # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run. stdin: # Set the stdin of the command directly to the specified value. stdin_add_newline: # If set to `yes', append a newline to stdin data. strip_empty_ends: # Strip empty lines from the end of stdout/stderr in result. warn: # Enable or disable task warnings. [root@centos8-1 ~]# ansible nginx -m command -a"chdir=/etc cat centos-release" 192.168.10.29 | CHANGED | rc=0 >> CentOS Linux release 7.6.1810 (Core)
shell 模块介绍
[root@centos8-1 ~]# ansible all -m shell -a ">2.txt" 192.168.10.28 | CHANGED | rc=0 >> 192.168.10.29 | CHANGED | rc=0 >> 192.168.10.40 | CHANGED | rc=0 >> 与command 模块用法一样比他多了支持变量重定向功能
批量执行模块script 介绍
[root@centos8-1 ~]# ls 2.txt anaconda-ks.cfg test.sh [root@centos8-1 ~]# ansible all -m script -a '/root/test.sh' -a参数指本机文件 192.168.10.29 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 192.168.10.29 closed. ", "stderr_lines": [ "Shared connection to 192.168.10.29 closed." ], "stdout": "My hostname is node02 ", "stdout_lines": [ "My hostname is node02" ] } 192.168.10.28 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 192.168.10.28 closed. ", "stderr_lines": [ "Shared connection to 192.168.10.28 closed." ], "stdout": "My hostname is node01 ", "stdout_lines": [ "My hostname is node01" ] } 192.168.10.40 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 192.168.10.40 closed. ", "stderr_lines": [ "Shared connection to 192.168.10.40 closed." ], "stdout": "My hostname is ansible ", "stdout_lines": [ "My hostname is ansible" ] }
copy 模块的介绍
功能 从ansible 服务器端 - 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. directory_mode: # When doing a recursive copy set the mode for the directories. If this :
拷贝测试
[root@ansible ~]# ansible nginx -m copy -a "src=/root/anaconda-ks.cfg dest=/root/anaconda-ks.cfg backup=yes" 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "backup_file": "/root/anaconda-ks.cfg.22029.2021-04-26@19:30:08~", "changed": true, "checksum": "4a9eaa9ea371beea6519ebce5d752182fab64fd4", "dest": "/root/anaconda-ks.cfg", "gid": 0, "group": "root", "md5sum": "e7e9041cea17124398ee8755ff40bd5e", "mode": "0600", "owner": "root", "size": 1257, "src": "/root/.ansible/tmp/ansible-tmp-1619436608.151183-27272-120059352334243/source", "state": "file", "uid": 0 }
fetch从远程主机拷贝文件到ansible主机指定目录;暂时不支持拷贝目录
[root@ansible ~]# ansible-doc -s fetch - name: Fetch files from remote nodes fetch: dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.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 `yes', 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 to `yes' in Ansible 2.5. 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. src: # (required) 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. validate_checksum: # Verify that the source and destination checksums match after the files are fetched.
测试
[root@ansible ~]# ansible all -m fetch -a 'src=/etc/redhat-release dest=/data/' 192.168.10.28 | CHANGED => { "changed": true, "checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", "dest": "/data/192.168.10.28/etc/redhat-release", "md5sum": "712356bf79a10f4c45cc0a1772bbeaf6", "remote_checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", "remote_md5sum": null } 192.168.10.29 | CHANGED => { "changed": true, "checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", "dest": "/data/192.168.10.29/etc/redhat-release", "md5sum": "712356bf79a10f4c45cc0a1772bbeaf6", "remote_checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", "remote_md5sum": null } 192.168.10.40 | CHANGED => { "changed": true, "checksum": "9444ac836064ad70ed2e97a5f0bfcd7a62b2a844", "dest": "/data/192.168.10.40/etc/redhat-release", "md5sum": "09c8628375d8fbac27555418f8f62840", "remote_checksum": "9444ac836064ad70ed2e97a5f0bfcd7a62b2a844", "remote_md5sum": null } [root@ansible ~]# ll /data/ 总用量 0 drwxr-xr-x 3 root root 17 4月 26 07:43 192.168.10.28 drwxr-xr-x 3 root root 17 4月 26 07:43 192.168.10.29 drwxr-xr-x 3 root root 17 4月 26 07:43 192.168.10.40 [root@ansible ~]# ll /data/192.168.10.29/ 总用量 0 drwxr-xr-x 2 root root 28 4月 26 07:43 etc [root@ansible ~]# ll /data/192.168.10.29/etc/ 总用量 4 -rw-r--r-- 1 root root 38 4月 26 07:43 redhat-release
file 模块
在指定目录下创建空文件 [root@ansible ~]# ansible all -m file -a 'path=/data/test.txt state=touch' 192.168.10.29 | FAILED! => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "msg": "Error, could not touch target: [Errno 2] 没有那个文件或目录: 指定的目录不存在'/data/test.txt'", "path": "/data/test.txt" } 192.168.10.28 | FAILED! => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "msg": "Error, could not touch target: [Errno 2] 没有那个文件或目录: '/data/test.txt'", "path": "/data/test.txt" } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "dest": "/data/test.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 创建目录并指定属主属组;或者修改属主数组 [root@ansible ~]# ansible all -m file -a 'path=/data/mysql state=directory owner=root group=root' 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/data/mysql", "size": 6, "state": "directory", "uid": 0 } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/data/mysql", "size": 6, "state": "directory", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/data/mysql", "size": 6, "state": "directory", "uid": 0 } 再次创建空文件 [root@ansible ~]# ansible all -m file -a 'path=/data/test.txt state=touch' 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data/test.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data/test.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "dest": "/data/test.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 创建软连接 [root@ansible ~]# ansible all -m file -a 'src=/data/test.txt dest=/data/test-link state=link' 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data/test-link", "gid": 0, "group": "root", "mode": "0777", "owner": "root", "size": 14, "src": "/data/test.txt", "state": "link", "uid": 0 } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data/test-link", "gid": 0, "group": "root", "mode": "0777", "owner": "root", "size": 14, "src": "/data/test.txt", "state": "link", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "dest": "/data/test-link", "gid": 0, "group": "root", "mode": "0777", "owner": "root", "size": 14, "src": "/data/test.txt", "state": "link", "uid": 0 }
解包模块unarchive
功能将ansible主机上压缩包传到远程主机后解压缩至特定目录,设置copy=yes;
将远程主机某个压缩包解压缩到指定的目录,设置copy=no
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果上设置为copy=no,会在远程主机上寻找src源文件
remote:和copy功能一样且互斥,yes表示在远程主机上,不在ansible主机上,no表示文件在ansible主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
dest: 远程主机上的目标路径
mode:设置解压后的文件权限
[root@ansible ~]# tar zcf /data/etc.tar.gz /etc tar: 从成员名中删除开头的“/” [root@ansible ~]# ls /data/ 192.168.10.28 192.168.10.29 192.168.10.40 etc.tar.gz mysql test-link test.txt [root@ansible ~]# ansible all -m shell -a 'ls /data/' 192.168.10.29 | CHANGED | rc=0 >> 192.168.10.28 | CHANGED | rc=0 >> 192.168.10.40 | CHANGED | rc=0 >> 192.168.10.28 192.168.10.29 192.168.10.40 etc.tar.gz mysql test-link test.txt [root@ansible ~]# ansible all -m unarchive -a "src=/data/etc.tar.gz dest=/data " 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/data", "-z", "-f", "/root/.ansible/tmp/ansible-tmp-1619442012.8274248-29620-173808702232603/source" ], "err": "/usr/bin/gtar: etc/resolv.conf: time stamp 2021-04-26 21:02:38 is 143.406660173 s in t he future /usr/bin/gtar: etc/tuned/active_profile: time stamp 2021-04-26 21:02:40 is 145.285857981 s in the future /usr/bin/gtar: etc/tuned/profile_mode: time stamp 2021-04-26 21:02:40 is 145.285783957 s in the future ", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 17, "src": "/root/.ansible/tmp/ansible-tmp-1619442012.8274248-29620-173808702232603/source", "state": "directory", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "dest": "/data", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/data", "-z", "-f", "/root/.ansible/tmp/ansible-tmp-1619442012.8415415-29621-221651239019879/source" ], "err": "/usr/bin/gtar: etc/resolv.conf: time stamp 2021-04-26 09:02:38 is 143.322987465 s in t he future /usr/bin/gtar: etc/tuned/active_profile: time stamp 2021-04-26 09:02:40 is 145.136998991 s in the future /usr/bin/gtar: etc/tuned/profile_mode: time stamp 2021-04-26 09:02:40 is 145.136928443 s in the future ", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 144, "src": "/root/.ansible/tmp/ansible-tmp-1619442012.8415415-29621-221651239019879/source", "state": "directory", "uid": 0 } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/data", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/data", "-z", "-f", "/root/.ansible/tmp/ansible-tmp-1619442012.825808-29619-267449434622727/source" ], "err": "/usr/bin/gtar: etc/resolv.conf: time stamp 2021-04-26 21:02:38 is 142.40548932 s in th e future /usr/bin/gtar: etc/tuned/active_profile: time stamp 2021-04-26 21:02:40 is 144.261515984 s in the future /usr/bin/gtar: etc/tuned/profile_mode: time stamp 2021-04-26 21:02:40 is 144.261429565 s in the future ", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 17, "src": "/root/.ansible/tmp/ansible-tmp-1619442012.825808-29619-267449434622727/source", "state": "directory", "uid": 0 } [root@ansible ~]# ansible all -m shell -a 'ls /data/' 192.168.10.28 | CHANGED | rc=0 >> etc 192.168.10.29 | CHANGED | rc=0 >> etc 192.168.10.40 | CHANGED | rc=0 >> 192.168.10.28 192.168.10.29 192.168.10.40 etc etc.tar.gz mysql test-link test.txt 本地文件解压测试 [root@ansible ~]# ansible all -m copy -a "src=/data/etc.tar.gz dest=/data " 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "checksum": "b1f550bf414452d82770aa1e1dfffe8bea46874b", "dest": "/data/etc.tar.gz", "gid": 0, "group": "root", "md5sum": "9d061744ae9e948555d6c910ec78d6a6", "mode": "0644", "owner": "root", "size": 5184925, "src": "/root/.ansible/tmp/ansible-tmp-1619442183.8658714-30038-40369719469912/source", "state": "file", "uid": 0 } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "checksum": "b1f550bf414452d82770aa1e1dfffe8bea46874b", "dest": "/data/etc.tar.gz", "gid": 0, "group": "root", "md5sum": "9d061744ae9e948555d6c910ec78d6a6", "mode": "0644", "owner": "root", "size": 5184925, "src": "/root/.ansible/tmp/ansible-tmp-1619442183.87328-30037-38848277281850/source", "state": "file", "uid": 0 } 192.168.10.40 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false, "checksum": "b1f550bf414452d82770aa1e1dfffe8bea46874b", "dest": "/data/etc.tar.gz", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "path": "/data/etc.tar.gz", "size": 5184925, "state": "file", "uid": 0 } [root@ansible ~]# ansible all -m unarchive -a "src=/data/etc.tar.gz dest=/opt copy=no " 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/opt", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/opt", "-z", "-f", "/data/etc.tar.gz" ], "err": "", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 17, "src": "/data/etc.tar.gz", "state": "directory", "uid": 0 } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/opt", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/opt", "-z", "-f", "/data/etc.tar.gz" ], "err": "", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 17, "src": "/data/etc.tar.gz", "state": "directory", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "dest": "/opt", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/opt", "-z", "-f", "/data/etc.tar.gz" ], "err": "", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 17, "src": "/data/etc.tar.gz", "state": "directory", "uid": 0 } [root@ansible ~]# ansible all -m shell -a 'ls /opt' 192.168.10.29 | CHANGED | rc=0 >> etc 192.168.10.28 | CHANGED | rc=0 >> etc 192.168.10.40 | CHANGED | rc=0 >> etc
Archive模块 打包压缩
archive 模块 [root@ansible ~]# ansible all -m archive -a 'path=/var/log dest=/data/log.tar.gz' 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "archived": [ "/var/log/tallylog", "/var/log/grubby_prune_debug", "/var/log/lastlog", "/var/log/wtmp", "/var/log/boot.log", "/var/log/firewalld", "/var/log/dmesg.old", "/var/log/yum.log", "/var/log/dmesg", "/var/log/boot.log-20210426", "/var/log/cron-20210426", "/var/log/cron", "/var/log/maillog-20210426", "/var/log/maillog", "/var/log/messages-20210426", "/var/log/messages", "/var/log/secure-20210426", "/var/log/secure", "/var/log/spooler-20210426", "/var/log/spooler", "/var/log/btmp-20210426", "/var/log/btmp", "/var/log/tuned/tuned.log", "/var/log/audit/audit.log", "/var/log/anaconda/anaconda.log", "/var/log/anaconda/syslog", "/var/log/anaconda/X.log", "/var/log/anaconda/program.log", "/var/log/anaconda/packaging.log", "/var/log/anaconda/storage.log", "/var/log/anaconda/ifcfg.log", "/var/log/anaconda/ks-script-J0euOb.log", "/var/log/anaconda/journal.log" ], "arcroot": "/var/", "changed": true, "dest": "/data/log.tar.gz", "expanded_exclude_paths": [], "expanded_paths": [ "/var/log" ], "gid": 0, "group": "root", "missing": [], "mode": "0644", "owner": "root", "size": 479844, "state": "file", "uid": 0 } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "archived": [ "/var/log/tallylog", "/var/log/grubby_prune_debug", "/var/log/lastlog", "/var/log/wtmp", "/var/log/boot.log", "/var/log/firewalld", "/var/log/dmesg.old", "/var/log/yum.log", "/var/log/dmesg", "/var/log/boot.log-20210426", "/var/log/cron-20210426", "/var/log/cron", "/var/log/maillog-20210426", "/var/log/maillog", "/var/log/messages-20210426", "/var/log/messages", "/var/log/secure-20210426", "/var/log/secure", "/var/log/spooler-20210426", "/var/log/spooler", "/var/log/btmp-20210426", "/var/log/btmp", "/var/log/tuned/tuned.log", "/var/log/audit/audit.log", "/var/log/anaconda/anaconda.log", "/var/log/anaconda/syslog", "/var/log/anaconda/X.log", "/var/log/anaconda/program.log", "/var/log/anaconda/packaging.log", "/var/log/anaconda/storage.log", "/var/log/anaconda/ifcfg.log", "/var/log/anaconda/ks-script-J0euOb.log", "/var/log/anaconda/journal.log" ], "arcroot": "/var/", "changed": true, "dest": "/data/log.tar.gz", "expanded_exclude_paths": [], "expanded_paths": [ "/var/log" ], "gid": 0, "group": "root", "missing": [], "mode": "0644", "owner": "root", "size": 476129, "state": "file", "uid": 0 } 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "archived": [ "/var/log/lastlog", "/var/log/wtmp", "/var/log/btmp", "/var/log/firewalld", "/var/log/dnf.log", "/var/log/dnf.librepo.log", "/var/log/dnf.rpm.log", "/var/log/hawkey.log", "/var/log/ansible.log", "/var/log/sssd/sssd.log", "/var/log/sssd/sssd_implicit_files.log", "/var/log/sssd/sssd_nss.log", "/var/log/sssd/sssd_kcm.log", "/var/log/tuned/tuned.log", "/var/log/audit/audit.log", "/var/log/anaconda/anaconda.log", "/var/log/anaconda/syslog", "/var/log/anaconda/X.log", "/var/log/anaconda/program.log", "/var/log/anaconda/packaging.log", "/var/log/anaconda/storage.log", "/var/log/anaconda/ifcfg.log", "/var/log/anaconda/lvm.log", "/var/log/anaconda/dnf.librepo.log", "/var/log/anaconda/hawkey.log", "/var/log/anaconda/dbus.log", "/var/log/anaconda/ks-script-4vf49ch4.log", "/var/log/anaconda/ks-script-w09jciw0.log", "/var/log/anaconda/journal.log" ], "arcroot": "/var/", "changed": true, "dest": "/data/log.tar.gz", "expanded_exclude_paths": [], "expanded_paths": [ "/var/log" ], "gid": 0, "group": "root", "missing": [], "mode": "0644", "owner": "root", "size": 481308, "state": "file", "uid": 0 } 查看 [root@ansible ~]# ansible all -m shell -a 'ls /data' 192.168.10.29 | CHANGED | rc=0 >> etc etc.tar.gz log.tar.gz 192.168.10.28 | CHANGED | rc=0 >> etc etc.tar.gz log.tar.gz 192.168.10.40 | CHANGED | rc=0 >> 192.168.10.28 192.168.10.29 192.168.10.40 etc etc.tar.gz log.tar.gz mysql test-link test.txt
hostname 模块修改主机名
[root@ansible ~]# ansible-doc -s hostname - name: Manage hostname hostname: name: # (required) Name of the host use: # Which strategy to use to update the hostname. If not set we try to autodetect, but this can be problematic, specially with containers as they can present misleading information. [root@ansible ~]# ansible 192.168.10.40 -m hostname -a 'name=ansible-1' 192.168.10.40 | CHANGED => { "ansible_facts": { "ansible_domain": "", "ansible_fqdn": "ansible-1", "ansible_hostname": "ansible-1", "ansible_nodename": "ansible-1", "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "name": "ansible-1" } [root@ansible ~]# ansible 192.168.10.40 -m shell -a 'hostname' 192.168.10.40 | CHANGED | rc=0 >> ansible-1
计划任务模块
[root@ansible ~]# ansible-doc cron > CRON (/usr/lib/python3.6/site-packages/ansible/modules/system/cron.py) Use this module to manage crontab and environment variables entries. This module allows you to create environment variables and named crontab entries, update, or delete them. When crontab jobs are managed: the module includes one line with the description of the crontab entry `"#Ansible: <name>"' corresponding to the "name" passed to the module, which is used by future ansible/module calls to find/check the state. The "name" parameter should be unique, and changing the "name" value will result in a new cron task being created (or a different one being removed). When environment variables are managed, no comment line is added, but, when the module needs to find/check the state, it uses the "name" parameter to find the environment variable definition line. When using symbols such as %, they must be properly escaped. * This module is maintained by The Ansible Community OPTIONS (= is mandatory): - 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. [Default: False] type: bool - 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. [Default: (null)] type: str - day Day of the month the job should run ( 1-31, *, */2, etc ) (Aliases: dom)[Default: *] type: str - disabled 禁用计划任务设置yes If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'. [Default: False] type: bool version_added: 2.0 - 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. [Default: False] type: bool version_added: 2.1 - hour Hour when the job should run ( 0-23, *, */2, etc ) [Default: *] type: str - insertafter Used with `state=present' and `env'. If specified, the environment variable will be inserted after the declaration of specified environment variable. [Default: (null)] type: str version_added: 2.1 - insertbefore Used with `state=present' and `env'. If specified, the environment variable will be inserted before the declaration of specified environment variable. [Default: (null)] type: str version_added: 2.1 - 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'. (Aliases: value)[Default: (null)] type: str - minute Minute when the job should run ( 0-59, *, */2, etc ) [Default: *] type: str - month Month of the year the job should run ( 1-12, *, */2, etc ) [Default: *] type: str - 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. [Default: (null)] type: str - reboot If the job should be run at reboot. This option is deprecated. Users should use special_time. [Default: False] type: bool version_added: 1.0 - special_time Special time specification nickname. (Choices: annually, daily, hourly, monthly, reboot, weekly, yearly)[Default: (null)] type: str version_added: 1.3 - state Whether to ensure the job or environment variable is present or absent. (Choices: absent, present)[Default: present] type: str - user The specific user whose crontab should be modified. When unset, this parameter defaults to using `root'. [Default: (null)] type: str - weekday Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc ) (Aliases: dow)[Default: *] type: str REQUIREMENTS: cron 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. [Default: (null)] type: str - reboot If the job should be run at reboot. This option is deprecated. Users should use special_time. [Default: False] type: bool version_added: 1.0 - special_time Special time specification nickname. (Choices: annually, daily, hourly, monthly, reboot, weekly, yearly)[Default: (null)] type: str version_added: 1.3 - state absent表示删除计划任务 Whether to ensure the job or environment variable is present or absent. (Choices: absent, present)[Default: present] type: str - user The specific user whose crontab should be modified. When unset, this parameter defaults to using `root'. [Default: (null)] type: str - weekday Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc ) (Aliases: dow)[Default: *] type: str [root@ansible ~]# ansible 192.168.10.40 -m cron -a 'hour=2 minute=30 weekday=1-5 name="test" job=/root/test.sh' 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "envs": [], "jobs": [ "test" ] } 查看设置的计划任务 [root@ansible ~]# ansible 192.168.10.40 -m shell -a 'crontab -l' 192.168.10.40 | CHANGED | rc=0 >> #Ansible: test 30 2 * * 1-5 /root/test.sh 禁用计划任务 [root@ansible ~]# ansible 192.168.10.40 -m cron -a 'hour=2 minute=30 weekday=1-5 name="test" job=/root/test.sh disabled=yes' 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "envs": [], "jobs": [ "test" ] } 禁用后查看 [root@ansible ~]# ansible 192.168.10.40 -m shell -a 'crontab -l' 192.168.10.40 | CHANGED | rc=0 >> #Ansible: test #30 2 * * 1-5 /root/test.sh 启用 [root@ansible ~]# ansible 192.168.10.40 -m shell -a 'crontab -l' 192.168.10.40 | CHANGED | rc=0 >> #Ansible: test 30 2 * * 1-5 /root/test.sh 删除计划任务 [root@ansible ~]# ansible 192.168.10.40 -m cron -a 'name="test" state=absent ' 192.168.10.40 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "envs": [], "jobs": [] } [root@ansible ~]# ansible 192.168.10.40 -m shell -a 'crontab -l' 192.168.10.40 | CHANGED | rc=0 >>
yum模块只针对红帽系统或者centos系统和fedora,不支持ubantu
[root@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: 安装(present' or `installed', `latest')或是卸载(absent' or `removed') # 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@ansible ~]# ansible nginx --list hosts (2): 192.168.10.29 192.168.10.28 安装nginx [root@ansible ~]# ansible nginx -m yum -a 'name=nginx state=present' 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "installed": [ "nginx" ] }, "msg": "", "rc": 0, "results": [ "Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: centos.nethub.com.hk * epel: mirrors.thzhost.com * extras : centos.nethub.com.hk * updates: centos.nethub.com.hk Resolving Dependencies --> Running transaction check ---> Package nginx.x86_64 1:1.16.1-3.el7 will be installed --> Processing Dependency: nginx-all-modules = 1:1.16.1-3.el7 for package: 1:nginx-1.16.1-3.el7.x86_64 --> Running transaction check ---> Package nginx-all-modules.noarch 1:1.16.1-3.el7 will be installed --> Processing Dependency: nginx-mod-http-image-filter = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-http-perl = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-http-xslt-filter = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-mail = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-stream = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Running transaction check ---> Package nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-mail.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-stream.x86_64 1:1.16.1-3.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: nginx x86_64 1:1.16.1-3.el7 epel 563 k Installing for dependencies: nginx-all-modules noarch 1:1.16.1-3.el7 epel 20 k nginx-mod-http-image-filter x86_64 1:1.16.1-3.el7 epel 30 k nginx-mod-http-perl x86_64 1:1.16.1-3.el7 epel 39 k nginx-mod-http-xslt-filter x86_64 1:1.16.1-3.el7 epel 29 k nginx-mod-mail x86_64 1:1.16.1-3.el7 epel 57 k nginx-mod-stream x86_64 1:1.16.1-3.el7 epel 85 k Transaction Summary ================================================================================ Install 1 Package (+6 Dependent packages) Total download size: 824 k Installed size: 2.0 M Downloading packages: -------------------------------------------------------------------------------- Total 59 kB/s | 824 kB 00:13 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 1/7 Installing : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 2/7 Installing : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 3/7 Installing : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 4/7 Installing : 1:nginx-1.16.1-3.el7.x86_64 5/7 Installing : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 6/7 Installing : 1:nginx-all-modules-1.16.1-3.el7.noarch 7/7 Verifying : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 1/7 Verifying : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 2/7 Verifying : 1:nginx-1.16.1-3.el7.x86_64 3/7 Verifying : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 4/7 Verifying : 1:nginx-all-modules-1.16.1-3.el7.noarch 5/7 Verifying : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 6/7 Verifying : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 7/7 Installed: nginx.x86_64 1:1.16.1-3.el7 Dependency Installed: nginx-all-modules.noarch 1:1.16.1-3.el7 nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 nginx-mod-mail.x86_64 1:1.16.1-3.el7 nginx-mod-stream.x86_64 1:1.16.1-3.el7 Complete! " ] } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "installed": [ "nginx" ] }, "msg": "", "rc": 0, "results": [ "Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: ftp.cuhk.edu.hk * epel: ftp.iij.ad.jp * extras: ftp.cuhk. edu.hk * updates: ftp.cuhk.edu.hk Resolving Dependencies --> Running transaction check ---> Package nginx.x86_64 1:1.16.1-3.el7 will be installed --> Processing Dependency: nginx-all-modules = 1:1.16.1-3.el7 for package: 1:nginx-1.16.1-3.el7.x86_64 --> Running transaction check ---> Package nginx-all-modules.noarch 1:1.16.1-3.el7 will be installed --> Processing Dependency: nginx-mod-http-image-filter = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-http-perl = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-http-xslt-filter = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-mail = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Processing Dependency: nginx-mod-stream = 1:1.16.1-3.el7 for package: 1:nginx-all-modules-1.16.1-3.el7.noarch --> Running transaction check ---> Package nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-mail.x86_64 1:1.16.1-3.el7 will be installed ---> Package nginx-mod-stream.x86_64 1:1.16.1-3.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: nginx x86_64 1:1.16.1-3.el7 epel 563 k Installing for dependencies: nginx-all-modules noarch 1:1.16.1-3.el7 epel 20 k nginx-mod-http-image-filter x86_64 1:1.16.1-3.el7 epel 30 k nginx-mod-http-perl x86_64 1:1.16.1-3.el7 epel 39 k nginx-mod-http-xslt-filter x86_64 1:1.16.1-3.el7 epel 29 k nginx-mod-mail x86_64 1:1.16.1-3.el7 epel 57 k nginx-mod-stream x86_64 1:1.16.1-3.el7 epel 85 k Transaction Summary ================================================================================ Install 1 Package (+6 Dependent packages) Total download size: 824 k Installed size: 2.0 M Downloading packages: -------------------------------------------------------------------------------- Total 60 kB/s | 824 kB 00:13 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 1/7 Installing : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 2/7 Installing : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 3/7 Installing : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 4/7 Installing : 1:nginx-1.16.1-3.el7.x86_64 5/7 Installing : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 6/7 Installing : 1:nginx-all-modules-1.16.1-3.el7.noarch 7/7 Verifying : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 1/7 Verifying : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 2/7 Verifying : 1:nginx-1.16.1-3.el7.x86_64 3/7 Verifying : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 4/7 Verifying : 1:nginx-all-modules-1.16.1-3.el7.noarch 5/7 Verifying : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 6/7 Verifying : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 7/7 Installed: nginx.x86_64 1:1.16.1-3.el7 Dependency Installed: nginx-all-modules.noarch 1:1.16.1-3.el7 nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 nginx-mod-mail.x86_64 1:1.16.1-3.el7 nginx-mod-stream.x86_64 1:1.16.1-3.el7 Complete! " ] } 卸载nginx [root@ansible ~]# ansible nginx -m yum -a 'name=nginx state=absent' 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "removed": [ "nginx" ] }, "msg": "", "rc": 0, "results": [ "已加载插件:fastestmirror 正在解决依赖关系 --> 正在检查事务 ---> 软件包 nginx.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在处理依赖关系 nginx,它 被软件包 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-mail-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-stream-1.16.1-3.el7.x86_64 需要 --> 正在检查事务 ---> 软件包 nginx-mod-http-image-filter.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在处理依赖关系 nginx-mod-http-image-filter = 1:1.16.1-3.el7,它被软件包 1:nginx-all-modules-1.16.1-3.el7.noarch 需要 ---> 软件包 nginx-mod-http-perl.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-http-xslt-filter.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-mail.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-stream.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在检查事务 ---> 软件包 nginx-all-modules.noarch.1.1.16.1-3.el7 将被 删除 --> 解决依赖关系完成 依赖关系解决 ================================================================================ Package 架构 版本 源 大小 ================================================================================ 正在删除: nginx x86_64 1:1.16.1-3.el7 @epel 1.6 M 为依赖而移除: nginx-all-modules noarch 1:1.16.1-3.el7 @epel 0.0 nginx-mod-http-image-filter x86_64 1:1.16.1-3.el7 @epel 24 k nginx-mod-http-perl x86_64 1:1.16.1-3.el7 @epel 54 k nginx-mod-http-xslt-filter x86_64 1:1.16.1-3.el7 @epel 24 k nginx-mod-mail x86_64 1:1.16.1-3.el7 @epel 99 k nginx-mod-stream x86_64 1:1.16.1-3.el7 @epel 171 k 事务概要 ================================================================================ 移除 1 软件包 (+6 依赖软件包) 安装大小:2.0 M Downloading packages: Running transaction check Running transaction test Transaction test succeeded Running transaction 正在删除 : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 1/7 正在删除 : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 2/7 正在删除 : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 3/7 正在删除 : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 4/7 正在删除 : 1:nginx-all-modules-1.16.1-3.el7.noarch 5/7 正在删除 : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 6/7 正在删除 : 1:nginx-1.16.1-3.el7.x86_64 7/7 验证中 : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 1/7 验证中 : 1:nginx-all-modules-1.16.1-3.el7.noarch 2/7 验证中 : 1:nginx-1.16.1-3.el7.x86_64 3/7 验证中 : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 4/7 验证中 : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 5/7 验证中 : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 6/7 验证中 : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 7/7 删除: nginx.x86_64 1:1.16.1-3.el7 作为依赖被删除: nginx-all-modules.noarch 1:1.16.1-3.el7 nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 nginx-mod-mail.x86_64 1:1.16.1-3.el7 nginx-mod-stream.x86_64 1:1.16.1-3.el7 完毕! " ] } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "removed": [ "nginx" ] }, "msg": "", "rc": 0, "results": [ "已加载插件:fastestmirror 正在解决依赖关系 --> 正在检查事务 ---> 软件包 nginx.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在处理依赖关系 nginx,它 被软件包 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-mail-1.16.1-3.el7.x86_64 需要 --> 正在处理依赖关系 nginx,它被软件包 1:nginx-mod-stream-1.16.1-3.el7.x86_64 需要 --> 正在检查事务 ---> 软件包 nginx-mod-http-image-filter.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在处理依赖关系 nginx-mod-http-image-filter = 1:1.16.1-3.el7,它被软件包 1:nginx-all-modules-1.16.1-3.el7.noarch 需要 ---> 软件包 nginx-mod-http-perl.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-http-xslt-filter.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-mail.x86_64.1.1.16.1-3.el7 将被 删除 ---> 软件包 nginx-mod-stream.x86_64.1.1.16.1-3.el7 将被 删除 --> 正在检查事务 ---> 软件包 nginx-all-modules.noarch.1.1.16.1-3.el7 将被 删除 --> 解决依赖关系完成 依赖关系解决 ================================================================================ Package 架构 版本 源 大小 ================================================================================ 正在删除: nginx x86_64 1:1.16.1-3.el7 @epel 1.6 M 为依赖而移除: nginx-all-modules noarch 1:1.16.1-3.el7 @epel 0.0 nginx-mod-http-image-filter x86_64 1:1.16.1-3.el7 @epel 24 k nginx-mod-http-perl x86_64 1:1.16.1-3.el7 @epel 54 k nginx-mod-http-xslt-filter x86_64 1:1.16.1-3.el7 @epel 24 k nginx-mod-mail x86_64 1:1.16.1-3.el7 @epel 99 k nginx-mod-stream x86_64 1:1.16.1-3.el7 @epel 171 k 事务概要 ================================================================================ 移除 1 软件包 (+6 依赖软件包) 安装大小:2.0 M Downloading packages: Running transaction check Running transaction test Transaction test succeeded Running transaction 正在删除 : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 1/7 正在删除 : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 2/7 正在删除 : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 3/7 正在删除 : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 4/7 正在删除 : 1:nginx-all-modules-1.16.1-3.el7.noarch 5/7 正在删除 : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 6/7 正在删除 : 1:nginx-1.16.1-3.el7.x86_64 7/7 验证中 : 1:nginx-mod-mail-1.16.1-3.el7.x86_64 1/7 验证中 : 1:nginx-all-modules-1.16.1-3.el7.noarch 2/7 验证中 : 1:nginx-1.16.1-3.el7.x86_64 3/7 验证中 : 1:nginx-mod-http-xslt-filter-1.16.1-3.el7.x86_64 4/7 验证中 : 1:nginx-mod-http-perl-1.16.1-3.el7.x86_64 5/7 验证中 : 1:nginx-mod-http-image-filter-1.16.1-3.el7.x86_64 6/7 验证中 : 1:nginx-mod-stream-1.16.1-3.el7.x86_64 7/7 删除: nginx.x86_64 1:1.16.1-3.el7 作为依赖被删除: nginx-all-modules.noarch 1:1.16.1-3.el7 nginx-mod-http-image-filter.x86_64 1:1.16.1-3.el7 nginx-mod-http-perl.x86_64 1:1.16.1-3.el7 nginx-mod-http-xslt-filter.x86_64 1:1.16.1-3.el7 nginx-mod-mail.x86_64 1:1.16.1-3.el7 nginx-mod-stream.x86_64 1:1.16.1-3.el7 完毕! " ] }
service 服务管理模块
[root@ansible ~]# 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 # `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. 启动nginx [root@ansible ~]# ansible nginx -m service -a "name=nginx state=started" 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "name": "nginx", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "system.slice -.mount remote-fs.target nss-lookup.target systemd-journald.socket network.target tmp.mount basic.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "no", "AssertTimestampMonotonic": "0", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "no", "ConditionTimestampMonotonic": "0", "Conflicts": "shutdown.target", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "0", "ExecMainStartTimestampMonotonic": "0", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; stat us=0/0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestampMonotonic": "0", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "14989", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "14989", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "0", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target -.mount", "RequiresMountsFor": "/var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "dead", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "name": "nginx", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "-.mount remote-fs.target tmp.mount system.slice basic.target network.target nss-lookup.target systemd-journald.socket", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "no", "AssertTimestampMonotonic": "0", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "no", "ConditionTimestampMonotonic": "0", "Conflicts": "shutdown.target", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "0", "ExecMainStartTimestampMonotonic": "0", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; stat us=0/0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestampMonotonic": "0", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "14989", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "14989", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "0", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target -.mount", "RequiresMountsFor": "/var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "dead", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } } 设置开机自启 [root@ansible ~]# ansible nginx -m service -a "name=nginx enabled=yes" 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "enabled": true, "name": "nginx", "status": { "ActiveEnterTimestamp": "一 2021-04-26 22:08:18 CST", "ActiveEnterTimestampMonotonic": "31439937202", "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "system.slice -.mount tmp.mount network.target systemd-journald.socket basic.target remote-fs.target nss-lookup.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "yes", "AssertTimestamp": "一 2021-04-26 22:08:18 CST", "AssertTimestampMonotonic": "31439830024", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "yes", "ConditionTimestamp": "一 2021-04-26 22:08:18 CST", "ConditionTimestampMonotonic": "31439830024", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/nginx.service", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "24481", "ExecMainStartTimestamp": "一 2021-04-26 22:08:18 CST", "ExecMainStartTimestampMonotonic": "31439936971", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }" , "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[一 2021-04-26 22:08:18 CST] ; stop_time=[一 2021-04-26 22:08:18 C ST] ; pid=24479 ; code=exited ; status=0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[一 2021-04-26 22:08:18 CST] ; stop_time=[一 2021-04-26 22:0 8:18 CST] ; pid=24476 ; code=exited ; status=0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestamp": "一 2021-04-26 22:08:18 CST", "InactiveExitTimestampMonotonic": "31439831062", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "14989", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "14989", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "24481", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target -.mount", "RequiresMountsFor": "/var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestamp": "一 2021-04-26 22:08:18 CST", "WatchdogTimestampMonotonic": "31439937125", "WatchdogUSec": "0" } } 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "enabled": true, "name": "nginx", "status": { "ActiveEnterTimestamp": "一 2021-04-26 22:08:18 CST", "ActiveEnterTimestampMonotonic": "31272094078", "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "basic.target system.slice nss-lookup.target -.mount network.target remote-fs.target systemd-journald.socket tmp.mount", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "yes", "AssertTimestamp": "一 2021-04-26 22:08:18 CST", "AssertTimestampMonotonic": "31271983056", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "yes", "ConditionTimestamp": "一 2021-04-26 22:08:18 CST", "ConditionTimestampMonotonic": "31271983055", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/nginx.service", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "24584", "ExecMainStartTimestamp": "一 2021-04-26 22:08:18 CST", "ExecMainStartTimestampMonotonic": "31272093949", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }" , "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[一 2021-04-26 22:08:18 CST] ; stop_time=[一 2021-04-26 22:08:18 C ST] ; pid=24582 ; code=exited ; status=0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[一 2021-04-26 22:08:18 CST] ; stop_time=[一 2021-04-26 22:0 8:18 CST] ; pid=24579 ; code=exited ; status=0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestamp": "一 2021-04-26 22:08:18 CST", "InactiveExitTimestampMonotonic": "31271984130", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "14989", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "14989", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "24584", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target -.mount", "RequiresMountsFor": "/var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestamp": "一 2021-04-26 22:08:18 CST", "WatchdogTimestampMonotonic": "31272094015", "WatchdogUSec": "0" } }
文件操作模块
[root@ansible ~]# ansible nginx -m shell -a "cat /etc/fstab" 192.168.10.29 | CHANGED | rc=0 >> # # /etc/fstab # Created by anaconda on Sun Feb 7 10:14:45 2021 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # /dev/mapper/centos-root / xfs defaults 0 0 UUID=ec65c557-715f-4f2b-beae-ec564c71b66b /boot xfs defaults 0 0 /dev/mapper/centos-swap swap swap defaults 0 0 192.168.10.28 | CHANGED | rc=0 >> # # /etc/fstab # Created by anaconda on Sun Feb 7 10:14:45 2021 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # /dev/mapper/centos-root / xfs defaults 0 0 UUID=ec65c557-715f-4f2b-beae-ec564c71b66b /boot xfs defaults 0 0 /dev/mapper/centos-swap swap swap defaults 0 0 修改/etc/fstab文件,去掉#开头行 [root@ansible ~]# ansible nginx -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"' 192.168.10.28 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "backup": "", "changed": true, "found": 7, "msg": "7 line(s) removed" } 192.168.10.29 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "backup": "", "changed": true, "found": 7, "msg": "7 line(s) removed" } [root@ansible ~]# ansible nginx -m shell -a "cat /etc/fstab" 192.168.10.29 | CHANGED | rc=0 >> /dev/mapper/centos-root / xfs defaults 0 0 UUID=ec65c557-715f-4f2b-beae-ec564c71b66b /boot xfs defaults 0 0 /dev/mapper/centos-swap swap swap defaults 0 0 192.168.10.28 | CHANGED | rc=0 >> /dev/mapper/centos-root / xfs defaults 0 0 UUID=ec65c557-715f-4f2b-beae-ec564c71b66b /boot xfs defaults 0 0 /dev/mapper/centos-swap swap swap defaults 0 0
setup 模块手集主机信息
[root@ansible ~]# 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 `her_facts'. filter: 过滤条件指定key # 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@ansible ~]# ansible mysql -m setup 192.168.10.28 | SUCCESS => { "ansible_facts": { "ansible_all_ipv4_addresses": [ "192.168.10.28" ], "ansible_all_ipv6_addresses": [ "fe80::20c:29ff:febb:4896" ], "ansible_apparmor": { "status": "disabled" }, "ansible_architecture": "x86_64", "ansible_bios_date": "02/27/2020", "ansible_bios_version": "6.00", "ansible_cmdline": { "BOOT_IMAGE": "/vmlinuz-3.10.0-957.el7.x86_64", "LANG": "zh_CN.UTF-8", "crashkernel": "auto", "quiet": true, "rd.lvm.lv": "centos/swap", "rhgb": true, "ro": true, "root": "/dev/mapper/centos-root" }, "ansible_date_time": { "date": "2021-04-26", "day": "26", "epoch": "1619447928", "hour": "22", .... 指定条件过滤 [root@ansible ~]# ansible mysql -m setup -a "filter=ansible_distribution_major_version" 192.168.10.28 | SUCCESS => { "ansible_facts": { "ansible_distribution_major_version": "7", "discovered_interpreter_python": "/usr/bin/python" }, "changed": false }