找回密码
 立即注册
首页 业界区 科技 运维工具之Ansible详解(一)

运维工具之Ansible详解(一)

笃迩讦 2025-6-9 18:43:05
一、基础入门

未来主体是传统行业利用互联网技术,以云端用人工智能的方式处理大数据。从早期的All In One(所有应用部署在一台机器上)的简单应用,到后期集群、高可用、缓存、消息队列、配置中心、主从分离、负载均衡、大数据存储等尖端技术的复杂应用,对运维的技术专业度和综合度技能要求越来越高,运维交付的标准不再是以天为单位,而是以分钟为单位。我们需要一套自动化管理工具来帮助运维更高质量、更有效的完成手头工作,以证明运维能创造的价值不止于此,生活不止眼前的苟且,还有诗和远方。
1.1 定义

运维自动化目标:将日常重复性的工作通过规则设定使其遵循预先既定规则,在指定的范围时间内自动化运行。但整个过程无需人工参与。
Ansible是帮助运维人员实现自动化的最重要的工具之一。
Ansible名字来源于其作者喜欢的一本书《安德的游戏》,该书中Ansible是一种能跨越时空的即时通信工具,使用Ansible可以在相距数光年的距离远程实时控制前线的舰队战斗。
Ansible是越来越火的一款运维自动化工具,其主要功能是帮助运维实现IT工作的自动化、降低人为操作失误、提高业务自动化率、提升运维工作效率,常用于软件部署自动化、配置自动化、管理自动化、系统化开发任务、持续集成、零宕机平滑升级等。
Ansible是一款极其简单的IT自动化工具。Ansible操作极其简单,功能却非常丰富,其自身内置的模块数量达五百多个,主要包括:

  • 系统层:支持Linux、Windows等
  • 虚拟化:VMWare、Docker、Openstack等
  • 商业化硬件:F5、ASA等
  • 系统应用层:Apache、Zabbix、Rabbitmq、SVN、GIT
1.2 为什么选择Ansible


  • Ansible基于python开发,运维人员开发门槛低
  • Ansible内置模块丰富,还有专门为商业平台开发的功能模块
  • 去中心化,一个简单的操作即可完成管理配置中心的迁移
  • AgentLess,客户端无需任何配置,由管理端配置好后即可使用
1.3 工作原理

Ansible没有客户端,底层通信依赖于系统软件,Linux系统基于OpenSSH通信,Windows系统基于Powershell,管理端必须是Linux系统,使用者认证通过后在管理节点通过Ansible工具调用各应用模块将指令推送至管理端执行,并在执行完毕后自动删除产生的临时文件。
1.png

Ansible整个工作流程中大致有三类角色:

  • 使用者:Ansible的使用者来源于多个维度,第一种方式,CMDB(Configuration Management Database,配置管理数据库)运维人员可以结合CMDB和Ansible,通过CMDB直接下发指令调用Ansible工具集完成操作者所希望达到的目标;第二种方式是API接口,运维人员可以使用通用开发语言以API接口调用形式完成相应的操作;第三种方式是开发人员以Ad-Hoc临时命令方式完成相应操作;第四种是运维人员使用提前写好的playbook完成相应的操作。
  • Ansible工具集:ansible命令是Ansible的核心,ansible命令通过协调Inventory(命令执行的目标对象配置文件)、API(供第三方应用程序调用的API接口)、M
  • 作用对象:Ansible的作用对象,不仅仅是Linux和非Linux操作系统的主机,同样也可以作用于公有云和私有云的各个网络设施
    再从Ansible工具集来讲,Ansible主要有以下几部分组成:
  • Ansible Playbook:任务集,编排定义Ansible任务集的配置文件,顺序依次执行,一般为yaml或json文件
  • Inventory:主机清单
  • Modules:Ansible执行命令的功能模块,多数为内置的核心模块
  • Plugins:模块功能的补充,如连接类型插件、循环插件、变量插件
  • API:供第三方应用程序调用的应用程序接口
    Ansible执行时,这些组件的调用关系如下:

1.4 通信方式

从Ansible 1.3版本开始,默认使用OpenSSH通信方式(底层基于SSH协议,window基于Powershell协议),支持密码和SSH认证
1.5 安装

pip安装方式:
  1. // 安装python
  2. yum install python-pip python-devel -y
  3. // 安装gcc glibc开发环境
  4. yum install gcc glibc-devel zlib-devel rpm-build openssl-devel -y
  5. // 升级pip
  6. pip install --upgrade pip
  7. // 安装ansible
  8. pip install ansible -upgrade
复制代码
yum安装方式
  1. rpm
  2. yum install ansible -y
复制代码
安装完后,查看ansible版本号,如果有正确返回,则表示安装成功
  1. [root@192-168-158-100-RedHat-7 ansible]# ansible --version
  2. ansible 2.9.27
  3.   config file = /etc/ansible/ansible.cfg
  4.   configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  5.   ansible python module location = /usr/lib/python2.7/site-packages/ansible
  6.   executable location = /usr/bin/ansible
  7.   python version = 2.7.5 (default, Nov 14 2023, 16:14:06) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
复制代码
1.6 目录结构

使用命令rpm -ql ansible可以查看Ansible的安装目录,该输出较多,但大致可以分为以下几个目录:

  • 配置文件目录:/etc/ansible/
    用于存放Ansible主机清单,工具功能配置等。
  • 执行文件目录:/usr/bin/ansible-xxx
    用于存放Ansible所有可执行文件
  • 库依赖文件目录:/usr/lib/PythonX.X/sitepackage/ansible/
  • help文档目录:/usr/share/doc/ansible-xxxx/
1.7 配置文件详解

Ansible自身配置文件只有一个,默认存放于/etc/ansible/ansible.cfg路径,Ansible命令执行时,会依次从当前命令执行路径、当前用户家目录、默认安装路径寻找ansible.cfg配置文件,找到哪个就用哪个

  • default
    基础设置项,保持默认即可
  1. [defaults]
  2. # some basic default values...
  3. #inventory      = /etc/ansible/hosts                              # 主机清单
  4. #library        = /usr/share/my_modules/                       # 库文件地址
  5. #module_utils   = /usr/share/my_module_utils/   
  6. #remote_tmp     = ~/.ansible/tmp                                # 远程主机临时文件存放目录
  7. #local_tmp      = ~/.ansible/tmp                                  # 本地临时文件存放目录
  8. #plugin_filters_cfg = /etc/ansible/plugin_filters.yml
  9. #forks          = 5                                                        # 并发数
  10. #poll_interval  = 15
  11. #sudo_user      = root
  12. #ask_sudo_pass = True
  13. #ask_pass      = True
  14. #transport      = smart
  15. #remote_port    = 22
  16. #module_lang    = C
  17. #module_set_locale = False
  18. # plays will gather facts by default, which contain information about
  19. # the remote system.
  20. #
  21. # smart - gather by default, but don't regather if already gathered
  22. # implicit - gather by default, turn off with gather_facts: False
  23. # explicit - do not gather by default, must say gather_facts: True
  24. #gathering = implicit
  25. # This only affects the gathering done by a play's gather_facts directive,
  26. # by default gathering retrieves all facts subsets
  27. # all - gather all subsets
  28. # network - gather min and network facts
  29. # hardware - gather hardware facts (longest facts to retrieve)
  30. # virtual - gather min and virtual facts
  31. # facter - import facts from facter
  32. # ohai - import facts from ohai
  33. # You can combine them using comma (ex: network,virtual)
  34. # You can negate them using ! (ex: !hardware,!facter,!ohai)
  35. # A minimal set of facts is always gathered.
  36. #gather_subset = all
  37. # some hardware related facts are collected
  38. # with a maximum timeout of 10 seconds. This
  39. # option lets you increase or decrease that
  40. # timeout to something more suitable for the
  41. # environment.
  42. # gather_timeout = 10
  43. # Ansible facts are available inside the ansible_facts.* dictionary
  44. # namespace. This setting maintains the behaviour which was the default prior
  45. # to 2.5, duplicating these variables into the main namespace, each with a
  46. # prefix of 'ansible_'.
  47. # This variable is set to True by default for backwards compatibility. It
  48. # will be changed to a default of 'False' in a future release.
  49. # ansible_facts.
  50. # inject_facts_as_vars = True
  51. # additional paths to search for roles in, colon separated
  52. #roles_path    = /etc/ansible/roles
  53. # uncomment this to disable SSH key host checking
  54. #host_key_checking = False
  55. # change the default callback, you can only have one 'stdout' type  enabled at a time.
  56. #stdout_callback = skippy
  57. ## Ansible ships with some plugins that require whitelisting,
  58. ## this is done to avoid running all of a type by default.
  59. ## These setting lists those that you want enabled for your system.
  60. ## Custom plugins should not need this unless plugin author specifies it.
  61. # enable callback plugins, they can output to stdout but cannot be 'stdout' type.
  62. #callback_whitelist = timer, mail
  63. # Determine whether includes in tasks and handlers are "static" by
  64. # default. As of 2.0, includes are dynamic by default. Setting these
  65. # values to True will make includes behave more like they did in the
  66. # 1.x versions.
  67. #task_includes_static = False
  68. #handler_includes_static = False
  69. # Controls if a missing handler for a notification event is an error or a warning
  70. #error_on_missing_handler = True
  71. # change this for alternative sudo implementations
  72. #sudo_exe = sudo
  73. # What flags to pass to sudo
  74. # WARNING: leaving out the defaults might create unexpected behaviours
  75. #sudo_flags = -H -S -n
  76. # SSH timeout
  77. #timeout = 10
  78. # default user to use for playbooks if user is not specified
  79. # (/usr/bin/ansible will use current user as default)
  80. #remote_user = root
  81. # logging is off by default unless this path is defined
  82. # if so defined, consider logrotate
  83. #log_path = /var/log/ansible.log
  84. # default module name for /usr/bin/ansible
  85. #module_name = command
  86. # use this shell for commands executed under sudo
  87. # you may need to change this to bin/bash in rare instances
  88. # if sudo is constrained
  89. #executable = /bin/sh
  90. # if inventory variables overlap, does the higher precedence one win
  91. # or are hash values merged together?  The default is 'replace' but
  92. # this can also be set to 'merge'.
  93. #hash_behaviour = replace
  94. # by default, variables from roles will be visible in the global variable
  95. # scope. To prevent this, the following option can be enabled, and only
  96. # tasks and handlers within the role will see the variables there
  97. #private_role_vars = yes
  98. # list any Jinja2 extensions to enable here:
  99. #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n
  100. # if set, always use this private key file for authentication, same as
  101. # if passing --private-key to ansible or ansible-playbook
  102. #private_key_file = /path/to/file
  103. # If set, configures the path to the Vault password file as an alternative to
  104. # specifying --vault-password-file on the command line.
  105. #vault_password_file = /path/to/vault_password_file
  106. # format of string {{ ansible_managed }} available within Jinja2
  107. # templates indicates to users editing templates files will be replaced.
  108. # replacing {file}, {host} and {uid} and strftime codes with proper values.
  109. #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
  110. # {file}, {host}, {uid}, and the timestamp can all interfere with idempotence
  111. # in some situations so the default is a static string:
  112. #ansible_managed = Ansible managed
  113. # by default, ansible-playbook will display "Skipping [host]" if it determines a task
  114. # should not be run on a host.  Set this to "False" if you don't want to see these "Skipping"
  115. # messages. NOTE: the task header will still be shown regardless of whether or not the
  116. # task is skipped.
  117. #display_skipped_hosts = True
  118. # by default, if a task in a playbook does not include a name: field then
  119. # ansible-playbook will construct a header that includes the task's action but
  120. # not the task's args.  This is a security feature because ansible cannot know
  121. # if the *module* considers an argument to be no_log at the time that the
  122. # header is printed.  If your environment doesn't have a problem securing
  123. # stdout from ansible-playbook (or you have manually specified no_log in your
  124. # playbook on all of the tasks where you have secret information) then you can
  125. # safely set this to True to get more informative messages.
  126. #display_args_to_stdout = False
  127. # by default (as of 1.3), Ansible will raise errors when attempting to dereference
  128. # Jinja2 variables that are not set in templates or action lines. Uncomment this line
  129. # to revert the behavior to pre-1.3.
  130. #error_on_undefined_vars = False
  131. # by default (as of 1.6), Ansible may display warnings based on the configuration of the
  132. # system running ansible itself. This may include warnings about 3rd party packages or
  133. # other conditions that should be resolved if possible.
  134. # to disable these warnings, set the following value to False:
  135. #system_warnings = True
  136. # by default (as of 1.4), Ansible may display deprecation warnings for language
  137. # features that should no longer be used and will be removed in future versions.
  138. # to disable these warnings, set the following value to False:
  139. #deprecation_warnings = True
  140. # (as of 1.8), Ansible can optionally warn when usage of the shell and
  141. # command module appear to be simplified by using a default Ansible module
  142. # instead.  These warnings can be silenced by adjusting the following
  143. # setting or adding warn=yes or warn=no to the end of the command line
  144. # parameter string.  This will for example suggest using the git module
  145. # instead of shelling out to the git command.
  146. # command_warnings = False
  147. # set plugin path directories here, separate with colons
  148. #action_plugins     = /usr/share/ansible/plugins/action
  149. #become_plugins     = /usr/share/ansible/plugins/become
  150. #cache_plugins      = /usr/share/ansible/plugins/cache
  151. #callback_plugins   = /usr/share/ansible/plugins/callback
  152. #connection_plugins = /usr/share/ansible/plugins/connection
  153. #lookup_plugins     = /usr/share/ansible/plugins/lookup
  154. #inventory_plugins  = /usr/share/ansible/plugins/inventory
  155. #vars_plugins       = /usr/share/ansible/plugins/vars
  156. #filter_plugins     = /usr/share/ansible/plugins/filter
  157. #test_plugins       = /usr/share/ansible/plugins/test
  158. #terminal_plugins   = /usr/share/ansible/plugins/terminal
  159. #strategy_plugins   = /usr/share/ansible/plugins/strategy
  160. # by default, ansible will use the 'linear' strategy but you may want to try
  161. # another one
  162. #strategy = free
  163. # by default callbacks are not loaded for /bin/ansible, enable this if you
  164. # want, for example, a notification or logging callback to also apply to
  165. # /bin/ansible runs
  166. #bin_ansible_callbacks = False
  167. # don't like cows?  that's unfortunate.
  168. # set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
  169. #nocows = 1
  170. # set which cowsay stencil you'd like to use by default. When set to 'random',
  171. # a random stencil will be selected for each task. The selection will be filtered
  172. # against the `cow_whitelist` option below.
  173. #cow_selection = default
  174. #cow_selection = random
  175. # when using the 'random' option for cowsay, stencils will be restricted to this list.
  176. # it should be formatted as a comma-separated list with no spaces between names.
  177. # NOTE: line continuations here are for formatting purposes only, as the INI parser
  178. #       in python does not support them.
  179. #cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\
  180. #              hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\
  181. #              stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www
  182. # don't like colors either?
  183. # set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
  184. #nocolor = 1
  185. # if set to a persistent type (not 'memory', for example 'redis') fact values
  186. # from previous runs in Ansible will be stored.  This may be useful when
  187. # wanting to use, for example, IP information from one group of servers
  188. # without having to talk to them in the same playbook run to get their
  189. # current IP information.
  190. #fact_caching = memory
  191. #This option tells Ansible where to cache facts. The value is plugin dependent.
  192. #For the jsonfile plugin, it should be a path to a local directory.
  193. #For the redis plugin, the value is a host:port:database triplet: fact_caching_connection = localhost:6379:0
  194. #fact_caching_connection=/tmp
  195. # retry files
  196. # When a playbook fails a .retry file can be created that will be placed in ~/
  197. # You can enable this feature by setting retry_files_enabled to True
  198. # and you can change the location of the files by setting retry_files_save_path
  199. #retry_files_enabled = False
  200. #retry_files_save_path = ~/.ansible-retry
  201. # squash actions
  202. # Ansible can optimise actions that call modules with list parameters
  203. # when looping. Instead of calling the module once per with_ item, the
  204. # module is called once with all items at once. Currently this only works
  205. # under limited circumstances, and only with parameters named 'name'.
  206. #squash_actions = apk,apt,dnf,homebrew,pacman,pkgng,yum,zypper
  207. # prevents logging of task data, off by default
  208. #no_log = False
  209. # prevents logging of tasks, but only on the targets, data is still logged on the master/controller
  210. #no_target_syslog = False
  211. # controls whether Ansible will raise an error or warning if a task has no
  212. # choice but to create world readable temporary files to execute a module on
  213. # the remote machine.  This option is False by default for security.  Users may
  214. # turn this on to have behaviour more like Ansible prior to 2.1.x.  See
  215. # https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user
  216. # for more secure ways to fix this than enabling this option.
  217. #allow_world_readable_tmpfiles = False
  218. # controls the compression level of variables sent to
  219. # worker processes. At the default of 0, no compression
  220. # is used. This value must be an integer from 0 to 9.
  221. #var_compression_level = 9
  222. # controls what compression method is used for new-style ansible modules when
  223. # they are sent to the remote system.  The compression types depend on having
  224. # support compiled into both the controller's python and the client's python.
  225. # The names should match with the python Zipfile compression types:
  226. # * ZIP_STORED (no compression. available everywhere)
  227. # * ZIP_DEFLATED (uses zlib, the default)
  228. # These values may be set per host via the ansible_module_compression inventory
  229. # variable
  230. #module_compression = 'ZIP_DEFLATED'
  231. # This controls the cutoff point (in bytes) on --diff for files
  232. # set to 0 for unlimited (RAM may suffer!).
  233. #max_diff_size = 1048576
  234. # This controls how ansible handles multiple --tags and --skip-tags arguments
  235. # on the CLI.  If this is True then multiple arguments are merged together.  If
  236. # it is False, then the last specified argument is used and the others are ignored.
  237. # This option will be removed in 2.8.
  238. #merge_multiple_cli_flags = True
  239. # Controls showing custom stats at the end, off by default
  240. #show_custom_stats = True
  241. # Controls which files to ignore when using a directory as inventory with
  242. # possibly multiple sources (both static and dynamic)
  243. #inventory_ignore_extensions = ~, .orig, .bak, .ini, .cfg, .retry, .pyc, .pyo
  244. # This family of modules use an alternative execution path optimized for network appliances
  245. # only update this setting if you know how this works, otherwise it can break module execution
  246. #network_group_modules=eos, nxos, ios, iosxr, junos, vyos
  247. # When enabled, this option allows lookups (via variables like {{lookup('foo')}} or when used as
  248. # a loop with `with_foo`) to return data that is not marked "unsafe". This means the data may contain
  249. # jinja2 templating language which will be run through the templating engine.
  250. # ENABLING THIS COULD BE A SECURITY RISK
  251. #allow_unsafe_lookups = False
  252. # set default errors for all plays
  253. #any_errors_fatal = False
复制代码

  • privilege_escalation
    部分公司不希望直接以Root最高管理员权限直接部署应用,往往会开通普通用户并授权sudo权限来进行相关操作,该部分是sudo提升权限的配置
  1. [privilege_escalation]
  2. #become=True
  3. #become_method=sudo
  4. #become_user=root
  5. #become_ask_pass=False
复制代码

  • ssh_connection
    Ansible默认使用SSH协议连接,保持默认即可
  1. [ssh_connection]
  2. # ssh arguments to use
  3. # Leaving off ControlPersist will result in poor performance, so use
  4. # paramiko on older platforms rather than removing it, -C controls compression use
  5. #ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
  6. # The base directory for the ControlPath sockets.
  7. # This is the "%(directory)s" in the control_path option
  8. #
  9. # Example:
  10. # control_path_dir = /tmp/.ansible/cp
  11. #control_path_dir = ~/.ansible/cp
  12. # The path to use for the ControlPath sockets. This defaults to a hashed string of the hostname,
  13. # port and username (empty string in the config). The hash mitigates a common problem users
  14. # found with long hostnames and the conventional %(directory)s/ansible-ssh-%%h-%%p-%%r format.
  15. # In those cases, a "too long for Unix domain socket" ssh error would occur.
  16. #
  17. # Example:
  18. # control_path = %(directory)s/%%h-%%r
  19. #control_path =
  20. # Enabling pipelining reduces the number of SSH operations required to
  21. # execute a module on the remote server. This can result in a significant
  22. # performance improvement when enabled, however when using "sudo:" you must
  23. # first disable 'requiretty' in /etc/sudoers
  24. #
  25. # By default, this option is disabled to preserve compatibility with
  26. # sudoers configurations that have requiretty (the default on many distros).
  27. #
  28. #pipelining = False
  29. # Control the mechanism for transferring files (old)
  30. #   * smart = try sftp and then try scp [default]
  31. #   * True = use scp only
  32. #   * False = use sftp only
  33. #scp_if_ssh = smart
  34. # Control the mechanism for transferring files (new)
  35. # If set, this will override the scp_if_ssh option
  36. #   * sftp  = use sftp to transfer files
  37. #   * scp   = use scp to transfer files
  38. #   * piped = use 'dd' over SSH to transfer files
  39. #   * smart = try sftp, scp, and piped, in that order [default]
  40. #transfer_method = smart
  41. # if False, sftp will not use batch mode to transfer files. This may cause some
  42. # types of file transfer failures impossible to catch however, and should
  43. # only be disabled if your sftp version has problems with batch mode
  44. #sftp_batch_mode = False
  45. # The -tt argument is passed to ssh when pipelining is not enabled because sudo
  46. # requires a tty by default.
  47. #usetty = True
  48. # Number of times to retry an SSH connection to a host, in case of UNREACHABLE.
  49. # For each retry attempt, there is an exponential backoff,
  50. # so after the first attempt there is 1s wait, then 2s, 4s etc. up to 30s (max).
  51. #retries = 3
复制代码

  • accelerate
    加速配置相关
  1. [accelerate]
  2. #accelerate_port = 5099
  3. #accelerate_timeout = 30
  4. #accelerate_connect_timeout = 5.0
  5. # The daemon timeout is measured in minutes. This time is measured
  6. # from the last activity to the accelerate daemon.
  7. #accelerate_daemon_timeout = 30
  8. # If set to yes, accelerate_multi_key will allow multiple
  9. # private keys to be uploaded to it, though each user must
  10. # have access to the system via SSH to add a new key. The default
  11. # is "no".
  12. #accelerate_multi_key = yes
复制代码

  • color
    输出颜色相关配置
  1. [colors]
  2. #highlight = white
  3. #verbose = blue
  4. #warn = bright purple
  5. #error = red
  6. #debug = dark gray
  7. #deprecate = purple
  8. #skip = cyan
  9. #unreachable = red
  10. #ok = green
  11. #changed = yellow
  12. #diff_add = green
  13. #diff_remove = red
  14. #diff_lines = cyan
复制代码
1.8 系列命令和使用场景

前面提到了,ansible相关命令的可执行文件均放在/usr/bin/目录下,如下:
  1. [root@192-168-158-100-RedHat-7 ansible-2.9.27]# ll /usr/bin/ | grep 'ansible'
  2. lrwxrwxrwx    1 root root          20 Jul 26  2023 ansible -> /usr/bin/ansible-2.7
  3. lrwxrwxrwx    1 root root          20 Jul 26  2023 ansible-2 -> /usr/bin/ansible-2.7
  4. -rwxr-xr-x    1 root root        5933 Jan 16  2022 ansible-2.7
  5. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-config -> ansible
  6. -rwxr-xr-x    1 root root       13432 Jan 16  2022 ansible-connection
  7. lrwxrwxrwx    1 root root          28 Jul 26  2023 ansible-console -> /usr/bin/ansible-console-2.7
  8. lrwxrwxrwx    1 root root          28 Jul 26  2023 ansible-console-2 -> /usr/bin/ansible-console-2.7
  9. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-console-2.7 -> ansible
  10. lrwxrwxrwx    1 root root          24 Jul 26  2023 ansible-doc -> /usr/bin/ansible-doc-2.7
  11. lrwxrwxrwx    1 root root          24 Jul 26  2023 ansible-doc-2 -> /usr/bin/ansible-doc-2.7
  12. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-doc-2.7 -> ansible
  13. lrwxrwxrwx    1 root root          27 Jul 26  2023 ansible-galaxy -> /usr/bin/ansible-galaxy-2.7
  14. lrwxrwxrwx    1 root root          27 Jul 26  2023 ansible-galaxy-2 -> /usr/bin/ansible-galaxy-2.7
  15. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-galaxy-2.7 -> ansible
  16. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-inventory -> ansible
  17. lrwxrwxrwx    1 root root          29 Jul 26  2023 ansible-playbook -> /usr/bin/ansible-playbook-2.7
  18. lrwxrwxrwx    1 root root          29 Jul 26  2023 ansible-playbook-2 -> /usr/bin/ansible-playbook-2.7
  19. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-playbook-2.7 -> ansible
  20. lrwxrwxrwx    1 root root          25 Jul 26  2023 ansible-pull -> /usr/bin/ansible-pull-2.7
  21. lrwxrwxrwx    1 root root          25 Jul 26  2023 ansible-pull-2 -> /usr/bin/ansible-pull-2.7
  22. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-pull-2.7 -> ansible
  23. lrwxrwxrwx    1 root root          26 Jul 26  2023 ansible-vault -> /usr/bin/ansible-vault-2.7
  24. lrwxrwxrwx    1 root root          26 Jul 26  2023 ansible-vault-2 -> /usr/bin/ansible-vault-2.7
  25. lrwxrwxrwx    1 root root           7 Jul 26  2023 ansible-vault-2.7 -> ansible
复制代码
大致分为以下几类:
1) ansible命令
日常工作中使用率非常高的命令之一,主要在非固化需求、临时一次性操作、二次开发接口调用场景下使用。命令格式如下:
ansible  [option]
表示inventory中定义的主机或主机组,该参数不可省略
[option]表示该选项的参数任选其一,具体选项可以使用man ansible命令查看
  1. [root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible all -m win_ping
  2. 192.168.158.104 | SUCCESS => {
  3.     "changed": false,
  4.     "ping": "pong"
  5. }
复制代码
ansible命令输出用红绿黄来区分执行结果成功与失败
3.png

2) ansible-doc命令
ansible-doc可以查看ansible各个模块的文档说明,功能类似于man命令
ansible支持的window模块大多以“win_”开头
  1. //查看ansible各个模块,可以看到ansible支持的windows模块大多以"win_"开头,例如,linux中使用的ping模块,windows中为win_ping
  2. ansible-doc -l
  3. //查看某个具体的模块
  4. ansible-doc win_ping
复制代码
3) ansible-galaxy命令
模块管理器,类似python中的pip,可以根据安装量和下载量等信息,查找和安装相应的roles
  1. ansible-galaxy [init|info|list|install|remove] [options]....
复制代码
4) ansible-playbook命令
通过预先编写好的playbook文件实现批量管理,要实现的功能与命令ansible一样,可以理解为按一定条件组成的ansible任务集
5) ansible-pull命令
ansible的另外一种工作模式,默认为push模式
6) ansible-vault命令
用于配置文件加密,如果编写的playbook文件中有敏感信息,可以使用ansible-valut进行加密解密,防止他人随意查看
  1. [root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible-vault encrypt test.yaml
  2. New Vault password:
  3. Confirm New Vault password:
  4. Encryption successful
  5. [root@192-168-158-100-RedHat-7 ansible-2.9.27]# cat test.yaml
  6. $ANSIBLE_VAULT;1.1;AES256
  7. 36353131383762396361623833653734356261666435633335636338333834393535353839383962
  8. 6237316263616662336161353433643435663737323431350a626338393561623639653961656238
  9. 66663031626464343661393732633264366265653734363139343330396430386364343232366138
  10. 3430326166326336630a343062623461633862366266363963376231343732623861666336326533
  11. 65346363386338636161613833646137306562636566633434373037313630636161
  12. [root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible-vault decrypt test.yaml
  13. Vault password:
  14. Decryption successful
复制代码
1.9 Inventory配置文件详解

Inventory是ansible管理主机信息的配置文件,默认存放于/etc/ansible/hosts。Ansible在使用时通过-i或者--inventory-file来制定文件读取,如ansible -i /etc/ansible/hosts webs -m ping,如果只有一个Inventory时可以不用指定路径,默认读取/etc/ansible/hosts。inventory可以同时存在多个,而且支持动态生成。
1)主机和组

Inventory配置文件遵循ini文件风格,中括号里的字符为组名,并且支持将同一个主机同时归并到多个不同的组中。若主机使用了非默认的ssh端口,还可以在主机名称之后使用冒号加端口号来标明
  1. #“#”开头的行表示该行为注释行,即当时行的配置不生效
  2. # Inventory 可以直接为 IP 地址
  3. 192.168.37.149# Inventory 同样支持 Hostname 的方式,后跟冒号加数字表示端口号,默认 22 号端口ntp.magedu.com:2222
  4. nfs .magedu.com
  5. # 中括号内的内容表示一个分组的开始,紧随其后的主机均属于该组成员,空行后的主机亦属于该组,即web2.magedu.com这台主机也属于[websevers]组
  6. [websevers]
  7. web1 .magedu.com
  8. web[10:20].magedu.com #[10:20]表示10~20 之间的所有数字(包括10和20),即表示 web10.magedu.com、web11.magedu.com……web20.magedu.com 的所有主机
  9. web2 .magedu.com[dbservers]
  10. db-a.magedu.com
  11. db-[b:f].magedu.com #[b:f]表示b到f之间的所有数字(包括b和f),即表示 db-b.magedu.com、db-e.magedu.com…db-f.magedu.com的所有主机
复制代码
2) 定义主机变量
  1. [webservers]
  2. web1.magedu.com http_port=808 maxRequestsPerchild=801 #自定义http_port 的端口号为808,配置maxRequestsPerchild为801
复制代码
3) 定义组变量
  1. [groupservers]
  2. webl .magedu.com
  3. web2 .magedu.com
  4. [groupservers:vars]
  5. ntp_server=ntp.magedu.com #定义groupservers 组中所有主机ntp_server 值为 ntp.magedu.com
  6. nfs_server=nfs.magedu.com #定义groupservers 组中所有主机nfs_server 值为 nfs.magedu.com
复制代码
4) 定义组嵌套及变量
  1. [apache]
  2. httpdl.magedu.com
  3. httpd2.magedu.com
  4. [nginx]
  5. ngx1.magedu.com
  6. ngx2.magedu.com
  7. [webservers:children]
  8. apache
  9. nginx
  10. [webservers:vars]
  11. ntp_server=ntp.magedu.com
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册