简介:

自动化运维工具,基于python开发,集合了众多运维工具(puppet、saltstack、chef、func、Fabric)的优点,实现了批量系统配合,批量程序部署,批量运行命令等功能。ansible是基于模块化工作的,本身没有批量 部署能力,真正具有部署能力的是它的模块,ansilble只是提供一种框架。

核心组件:

  • Ansible:核心程序
  • Modules:包含Ansible的自带的核心模块以及自定义模块
  • Plugins:完成模块功能的补充,包括连接插件,邮箱插件等
  • Playbooks:剧本:定理ansible多任务配置文件,由ansible自动执行
    • host
    • role
    • 剧情
  • Inventory:定义ansible管理的机器清单
  • Connection Plugins:负载和被监控端实现通信

    特性:

  • 1.它不需要被管控主机安装任何客户端

  • 2.无服务端,使用时直接使用命令运行即可
  • 3.基于模块工作,可以使用任何语言开发新模块
  • 4.使用yaml语言来定制剧本playbook
  • 5.基于ssh工作
  • 6.可实现多级指挥
  • 7.幂等性:一种操作重复多次结果相同

    安装

  • yum provides ansible

  • yum install ansible-2.8.2-1.el7.noarch

  • /usr/lib/ansible #

    命令说明

  1. [root@localhost ~]# ansible -h
  2. Usage: ansible <host-pattern> [options]
  3. Define and run a single task 'playbook' against a set of hosts
  4. Options:
  5. -a MODULE_ARGS, --args=MODULE_ARGS #指定模块参数
  6. module arguments
  7. --ask-vault-pass ask for vault password
  8. -B SECONDS, --background=SECONDS
  9. run asynchronously, failing after X seconds
  10. (default=N/A)
  11. -C, --check don't make any changes; instead, try to predict some
  12. of the changes that may occur #检查临时命令操作
  13. -D, --diff when changing (small) files and templates, show the
  14. differences in those files; works great with --check
  15. -e EXTRA_VARS, --extra-vars=EXTRA_VARS #设置变量
  16. set additional variables as key=value or YAML/JSON, if
  17. filename prepend with @
  18. -f FORKS, --forks=FORKS
  19. specify number of parallel processes to use
  20. (default=5)
  21. -h, --help show this help message and exit
  22. -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY #查看主机清单
  23. specify inventory host path or comma separated host
  24. list. --inventory-file is deprecated
  25. -l SUBSET, --limit=SUBSET
  26. further limit selected hosts to an additional pattern
  27. --list-hosts outputs a list of matching hosts; does not execute
  28. anything else
  29. -m MODULE_NAME, --module-name=MODULE_NAME #指定模块名
  30. module name to execute (default=command)
  31. -M MODULE_PATH, --module-path=MODULE_PATH
  32. prepend colon-separated path(s) to module library (def
  33. ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
  34. gins/modules) #指定模块路径
  35. -o, --one-line condense output
  36. --playbook-dir=BASEDIR
  37. Since this tool does not use playbooks, use this as a
  38. substitute playbook directory.This sets the relative
  39. path for many features including roles/ group_vars/
  40. etc.
  41. -P POLL_INTERVAL, --poll=POLL_INTERVAL
  42. set the poll interval if using -B (default=15)
  43. --syntax-check perform a syntax check on the playbook, but do not
  44. execute it
  45. -t TREE, --tree=TREE log output to this directory
  46. --vault-id=VAULT_IDS the vault identity to use
  47. --vault-password-file=VAULT_PASSWORD_FILES
  48. vault password file
  49. -v, --verbose verbose mode (-vvv for more, -vvvv to enable
  50. connection debugging)
  51. --version show program's version number, config file location,
  52. configured module search path, module location,
  53. executable location and exit
  54. Privilege Escalation Options:
  55. control how and which user you become as on target hosts
  56. -b, --become run operations with become (does not imply password
  57. prompting)
  58. --become-method=BECOME_METHOD
  59. privilege escalation method to use (default=sudo), use
  60. `ansible-doc -t become -l` to list valid choices.
  61. --become-user=BECOME_USER
  62. run operations as this user (default=root)
  63. -K, --ask-become-pass
  64. ask for privilege escalation password
  65. Connection Options:
  66. control as whom and how to connect to hosts
  67. -k, --ask-pass ask for connection password
  68. --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
  69. use this file to authenticate the connection
  70. -u REMOTE_USER, --user=REMOTE_USER
  71. connect as this user (default=None) #指明连接远程主机的用户
  72. -c CONNECTION, --connection=CONNECTION
  73. connection type to use (default=smart)
  74. -T TIMEOUT, --timeout=TIMEOUT
  75. override the connection timeout in seconds
  76. (default=10)
  77. --ssh-common-args=SSH_COMMON_ARGS
  78. specify common arguments to pass to sftp/scp/ssh (e.g.
  79. ProxyCommand)
  80. --sftp-extra-args=SFTP_EXTRA_ARGS
  81. specify extra arguments to pass to sftp only (e.g. -f,
  82. -l)
  83. --scp-extra-args=SCP_EXTRA_ARGS
  84. specify extra arguments to pass to scp only (e.g. -l)
  85. --ssh-extra-args=SSH_EXTRA_ARGS
  86. specify extra arguments to pass to ssh only (e.g. -R)
  87. Some modules do not make sense in Ad-Hoc (include, meta, etc)

  1. [root@localhost ~]# ansible-doc
  2. Usage: ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]
  3. plugin documentation tool
  4. Options:
  5. -h, --help show this help message and exit
  6. -j, --json **For internal testing only** Dump json metadata for
  7. all plugins.
  8. -l, --list List available plugins #列出可用插件
  9. -F, --list_files Show plugin names and their source files without
  10. summaries (implies --list)
  11. -M MODULE_PATH, --module-path=MODULE_PATH
  12. prepend colon-separated path(s) to module library (def
  13. ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
  14. gins/modules)
  15. -s, --snippet Show playbook snippet for specified plugin(s) #查看该模块(插件)使用手册
  16. -t TYPE, --type=TYPE Choose which plugin type (defaults to "module").
  17. Available plugin types are : ('become', 'cache',
  18. 'callback', 'cliconf', 'connection', 'httpapi',
  19. 'inventory', 'lookup', 'shell', 'module', 'strategy',
  20. 'vars')
  21. -v, --verbose verbose mode (-vvv for more, -vvvv to enable
  22. connection debugging)
  23. --version show program's version number, config file location,
  24. configured module search path, module location,
  25. executable location and exit
  26. See man pages for Ansible CLI options or website for tutorials

配置文件:

  • 一般来说,主配置文件保持默认就行

    • inventory:主机清单

      • 主机清单的定义方式

        ansible命令执行的过程:

    • 1.加载自己的配置文件,默认:/etc/ansible/ansible/.cfg

    • 2.加载自己对应的模块文件,如command,ping
    • 3.通过ansible模块或命令生成对应的临时py文件,然后将py文件传输至远程服务器
    • 4.~/.ansible/tmp/xx.py添加x权限
    • 5.执行临时py文件返回结果并删除

      常用模块:

      ping模块

  1. [root@localhost ~]# ansible-doc -s ping
  2. - name: Try to connect to host, verify a usable python and return `pong' on
  3. ping:
  4. data: # Data to return for the `ping' return value. I
  5. this parameter is
  6. set to `crash',
  7. the module will
  8. cause an
  9. exception.

ansible的执行状态:
绿色:执行成功且不需要做操作
黄色:执行成功
红色:执行失败

user模块

  1. [root@localhost ~]# ansible-doc -s user
  2. - name: Manage user accounts
  3. user:
  4. append: # If `yes', add the user to the groups specifie
  5. in `groups'. If
  6. `no', user will
  7. only be added to
  8. the groups
  9. specified in
  10. `groups',
  11. removing them
  12. from all other
  13. groups.
  14. authorization: # Sets the authorization of the user. Does noth
  15. when used with
  16. other platforms.
  17. Can set multiple
  18. authorizations
  19. using comma
  20. separation. To
  21. delete all
  22. authorizations,
  23. use `authorizatio
  24. n='''. Currently
  25. supported on
  26. Illumos/Solaris.
  27. comment: # Optionally sets the description (aka `GECOS')
  28. user account.
  29. create_home: # Unless set to `no', a home directory will be
  30. made for the user
  31. when the account
  32. is created or if
  33. the home
  34. directory does
  35. not exist.
  36. Changed from
  37. `createhome' to
  38. `create_home' in
  39. Ansible 2.5.
  40. expires: # An expiry time for the user in epoch, it will
  41. ignored on
  42. platforms that do
  43. not support this.
  44. Currently
  45. supported on
  46. GNU/Linux,
  47. FreeBSD, and
  48. DragonFlyBSD.
  49. Since Ansible 2.6
  50. you can remove
  51. the expiry time
  52. specify a
  53. negative value.
  54. Currently
  55. supported on
  56. GNU/Linux and
  57. FreeBSD.
  58. force: # This only affects `state=absent', it forces
  59. removal of the
  60. user and
  61. associated
  62. directories on
  63. supported
  64. platforms. The
  65. behavior is the
  66. same as `userdel
  67. --force', check
  68. the man page for
  69. `userdel' on your
  70. system for
  71. details and
  72. support. When
  73. used with `genera
  74. te_ssh_key=yes'
  75. this forces an
  76. existing key to
  77. be overwritten.
  78. generate_ssh_key: # Whether to generate a SSH key for the user in
  79. question. This
  80. will *not*
  81. overwrite an
  82. existing SSH key
  83. unless used with
  84. `force=yes'.
  85. group: # Optionally sets the user's primary group (tak
  86. a group name).
  87. groups: # List of groups user will be added to. When se
  88. to an empty
  89. string `''',
  90. `null', or `~',
  91. the user is
  92. removed from all
  93. groups except the
  94. primary group.
  95. (`~' means `null'
  96. in YAML) Before
  97. Ansible 2.3, the
  98. only input format
  99. allowed was a
  100. comma separated
  101. string.
  102. hidden: # macOS only, optionally hide the user from the
  103. login window and
  104. system
  105. preferences. The
  106. default will be
  107. `yes' if the
  108. `system' option
  109. is used.
  110. home: # Optionally set the user's home directory.
  111. local: # Forces the use of "local" command alternative
  112. on platforms that
  113. implement it.
  114. This is useful in
  115. environments that
  116. use centralized
  117. authentification
  118. when you want to
  119. manipulate the
  120. local users (i.e.
  121. it uses
  122. `luseradd'
  123. instead of
  124. `useradd'). This
  125. will check
  126. `/etc/passwd' for
  127. an existing
  128. account before
  129. invoking
  130. commands. If the
  131. local account
  132. database exists
  133. somewhere other
  134. than
  135. `/etc/passwd',
  136. this setting will
  137. not work
  138. properly. This
  139. requires that the
  140. above commands as
  141. well as
  142. `/etc/passwd'
  143. must exist on the
  144. target host,
  145. otherwise it will
  146. be a fatal error.
  147. login_class: # Optionally sets the user's login class, a
  148. feature of most
  149. BSD OSs.
  150. move_home: # If set to `yes' when used with `home: ', atte
  151. to move the
  152. user's old home
  153. directory to the
  154. specified
  155. directory if it
  156. isn't there
  157. already and the
  158. old home exists.
  159. name: # (required) Name of the user to create, remove
  160. modify.
  161. non_unique: # Optionally when used with the -u option, this
  162. option allows to
  163. change the user
  164. ID to a non-
  165. unique value.
  166. password: # Optionally set the user's password to this
  167. crypted value. On
  168. macOS systems,
  169. this value has to
  170. be cleartext.
  171. Beware of
  172. security issues.
  173. To create a
  174. disabled account
  175. on Linux systems,
  176. set this to `'!''
  177. or `'*''. See htt
  178. ps://docs.ansible
  179. .com/ansible/faq.
  180. html#how-do-i
  181. -generate-
  182. crypted-
  183. passwords-for-
  184. the-user-module
  185. for details on
  186. various ways to
  187. generate these
  188. password values.
  189. password_lock: # Lock the password (usermod -L, pw lock, userm
  190. -C). BUT
  191. implementation
  192. differs on
  193. different
  194. platforms, this
  195. option does not
  196. always mean the
  197. user cannot login
  198. via other
  199. methods. This
  200. option does not
  201. disable the user,
  202. only lock the
  203. password. Do not
  204. change the
  205. password in the
  206. same task.
  207. Currently
  208. supported on
  209. Linux, FreeBSD,
  210. DragonFlyBSD,
  211. NetBSD, OpenBSD.
  212. profile: # Sets the profile of the user. Does nothing wh
  213. used with other
  214. platforms. Can
  215. set multiple
  216. profiles using
  217. comma separation.
  218. To delete all the
  219. profiles, use
  220. `profile='''.
  221. Currently
  222. supported on
  223. Illumos/Solaris.
  224. remove: # This only affects `state=absent', it attempts
  225. remove
  226. directories
  227. associated with
  228. the user. The
  229. behavior is the
  230. same as `userdel
  231. --remove', check
  232. the man page for
  233. details and
  234. support.
  235. role: # Sets the role of the user. Does nothing when
  236. used with other
  237. platforms. Can
  238. set multiple
  239. roles using comma
  240. separation. To
  241. delete all roles,
  242. use `role='''.
  243. Currently
  244. supported on
  245. Illumos/Solaris.
  246. seuser: # Optionally sets the seuser type (user_u) on
  247. selinux enabled
  248. systems.
  249. shell: # Optionally set the user's shell. On macOS,
  250. before Ansible
  251. 2.5, the default
  252. shell for non-
  253. system users was
  254. `/usr/bin/false'.
  255. Since Ansible
  256. 2.5, the default
  257. shell for non-
  258. system users on
  259. macOS is
  260. `/bin/bash'. On
  261. other operating
  262. systems, the
  263. default shell is
  264. determined by the
  265. underlying tool
  266. being used. See
  267. Notes for
  268. details.
  269. skeleton: # Optionally set a home skeleton directory.
  270. Requires
  271. `create_home'
  272. option!
  273. ssh_key_bits: # Optionally specify number of bits in SSH key
  274. create.
  275. ssh_key_comment: # Optionally define the comment for the SSH key
  276. ssh_key_file: # Optionally specify the SSH key filename. If t
  277. is a relative
  278. filename then it
  279. will be relative
  280. to the user's
  281. home directory.
  282. This parameter
  283. defaults to
  284. `.ssh/id_rsa'.
  285. ssh_key_passphrase: # Set a passphrase for the SSH key. If no
  286. passphrase is
  287. provided, the SSH
  288. key will default
  289. to having no
  290. passphrase.
  291. ssh_key_type: # Optionally specify the type of SSH key to
  292. generate.
  293. Available SSH key
  294. types will depend
  295. on implementation
  296. present on target
  297. host.
  298. state: # Whether the account should exist or not, taki
  299. action if the
  300. state is
  301. different from
  302. what is stated.
  303. system: # When creating an account `state=present',
  304. setting this to
  305. `yes' makes the
  306. user a system
  307. account. This
  308. setting cannot be
  309. changed on
  310. existing users.
  311. uid: # Optionally sets the `UID' of the user.
  312. update_password: # `always' will update passwords if they differ
  313. `on_create' will
  314. only set the
  315. password for
  316. newly created
  317. users.

1.添加系统,指定uid为1010,

group模块

[root@localhost ~]# ansible-doc -s group
- name: Add or remove groups
  group:
      gid:                   # Optional `GID' to set for the group.
      local:                 # Forces the use of "local" command alternative
                               on platforms that
                               implement it.
                               This is useful in
                               environments that
                               use centralized
                               authentication
                               when you want to
                               manipulate the
                               local groups.
                               (e.g. it uses
                               `lgroupadd'
                               instead of
                               `groupadd'). This
                               requires that
                               these commands
                               exist on the
                               targeted host,
                               otherwise it will
                               be a fatal error.
      name:                  # (required) Name of the group to manage.
      non_unique:            # This option allows to change the group ID to 
                               non-unique value.
                               Requires `gid'.
                               Not supported on
                               macOS or BusyBox
                               distributions.
      state:                 # Whether the group should be present or not on
                               the remote host.
      system:                # If `yes', indicates that the group created is
                               system group

command模块

1.默认使用的模块
2.不支持管道、变量及重定向等操作

shell模块

1.调用shell执行命令

copy模块

[root@localhost ~]# ansible-doc -s copy
- name: Copy files to remote locations
  copy:
      attributes:            # The attributes the resulting file or director
                               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
                               a file directly to the specified
                               value. 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 fil
                               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 
                               directories. If
                               this is not set  #递归设定目录的权限,默认是系统默认权限
                               we will use the
                               system defaults.
                               The mode is only
                               set on
                               directories which
                               are newly
                               created, and will
                               not affect those
                               that already
                               existed.
      follow:                # This flag indicates that filesystem links in 
                               destination, if
                               they exist,
                               should be
                               followed.
      force:                 # Influence whether the remote file must always
                               replaced. If
                               `yes', the remote
                               file will be
                               replaced when
                               contents are
                               different than
                               the source. If
                               `no', the file
                               will only be
                               transferred if
                               the destination
                               does not exist.
      group:                 # Name of the group that should own the
                               file/directory,
                               as would be fed
                               to `chown'.
      local_follow:          # This flag indicates that filesystem links in 
                               source tree, if
                               they exist,
                               should be
                               followed.
      mode:                  # The permissions of the destination file or
                               directory. For
                               those used to
                               `/usr/bin/chmod'
                               remember that
                               modes are
                               actually octal
                               numbers. You must
                               either add a
                               leading zero so
                               that Ansible's
                               YAML parser knows
                               it is an octal
                               number (like
                               `0644' or
                               `01777')or quote
                               it (like `'644''
                               or `'1777'') so
                               Ansible receives
                               a string and can
                               do its own
                               conversion from
                               string into
                               number. Giving
                               Ansible a number
                               without following
                               one of these
                               rules will end up
                               with a decimal
                               number which will
                               have unexpected
                               results. As of
                               Ansible 1.8, the
                               mode may be
                               specified as a
                               symbolic mode
                               (for example,
                               `u+rwx' or
                               `u=rw,g=r,o=r').
                               As of Ansible
                               2.3, the mode may
                               also be the
                               special string
                               `preserve'.
                               `preserve' means
                               that the file
                               will be given the
                               same permissions
                               as the source
                               file.
      owner:                 # Name of the user that should own the
                               file/directory,
                               as would be fed
                               to `chown'.
      remote_src:            # Influence whether `src' needs to be transferr
                               or already is
                               present remotely.
                               If `no', it will
                               search for `src'
                               at originating/ma
                               ster machine. If
                               `yes' it will go
                               to the
                               remote/target
                               machine for the
                               `src'.
                               `remote_src'
                               supports
                               recursive copying
                               as of version
                               2.8. `remote_src'
                               only works with
                               `mode=preserve'
                               as of version
                               2.6.
      selevel:               # The level part of the SELinux file context. T
                               is the MLS/MCS
                               attribute,
                               sometimes known
                               as the `range'.
                               When set to
                               `_default', it
                               will use the
                               `level' portion
                               of the policy if
                               available.
      serole:                # The role part of the SELinux file context. Wh
                               set to
                               `_default', it
                               will use the
                               `role' portion of
                               the policy if
                               available.
      setype:                # The type part of the SELinux file context. Wh
                               set to
                               `_default', it
                               will use the
                               `type' portion of
                               the policy if
                               available.
      seuser:                # The user part of the SELinux file context. By
                               default it uses
                               the `system'
                               policy, where
                               applicable. When
                               set to
                               `_default', it
                               will use the
                               `user' portion of
                               the policy if
                               available.
      src:                   # Local path to a file to copy to the remote   #被复制到远程主机的本机文件
                               server. This can
                               be absolute or
                               relative. If path
                               is a directory,
                               it is copied
                               recursively. In
                               this case, if
                               path ends with
                               "/", only inside
                               contents of that
                               directory are
                               copied to
                               destination.
                               Otherwise, if it
                               does not end with
                               "/", the
                               directory itself
                               with all contents
                               is copied. This
                               behavior is
                               similar to the
                               `rsync' command
                               line tool.
      unsafe_writes:         # Influence when to use atomic operation to
                               prevent data
                               corruption or
                               inconsistent
                               reads from the
                               target file. By
                               default this
                               module uses
                               atomic operations
                               to prevent data
                               corruption or
                               inconsistent
                               reads from the
                               target files, but
                               sometimes systems
                               are configured or
                               just broken in
                               ways that prevent
                               this. One example
                               is docker mounted
                               files, which
                               cannot be updated
                               atomically from
                               inside the
                               container and can
                               only be written
                               in an unsafe
                               manner. This
                               option allows
                               Ansible to fall
                               back to unsafe
                               methods of
                               updating files
                               when atomic
                               operations fail
                               (however, it
                               doesn't force
                               Ansible to
                               perform unsafe
                               writes).
                               IMPORTANT! Unsafe
                               writes are
                               subject to race
                               conditions and
                               can lead to data
                               corruption.
      validate:              # The validation command to run before copying
                               into place. The
                               path to the file
                               to validate is
                               passed in via
                               '%s' which must
                               be present as in
                               the examples
                               below. The
                               command is passed
                               securely so shell
                               features like
                               expansion and
                               pipes will not
                               work.

file模块

state:
state=directory:如果目录不存在即创建目录
file 即使文件不存在,也不会创建
link 创建链接
hard 创建硬链接
touch 如果文件不存在,会创建一个文件夹
absent:删除目录、文件、取消链接
force:

yum模块

name:
update_cache :

service模块

enabled
disabled:
name = 服务名称
state=
started 启动
stopped 停止
restarted 重启
reloaded 重载配置

setup模块

[root@localhost ~]# ansible-doc -s setup
- name: Gathers facts about remote hosts #获取远程主机相关信息
absible

selinux模块

conf:指明配置文件
policy:设置selinux模块

curl模块

ansible-playbook

playbook由一个或多个“play”组成的列表,可以让它们联同起来按照事先编排的机制执行,每个play中由多task,每个task都是调用ansible的一个模块,而模块参数可以使用变量,模块执行是幂等的,这就意味着多次执行是安全的,因为它的结果均是一致的。
特点:
1.yuml可读性好
2.yuml与脚本语言的交互性好
3.yuml使用实现语言的数据类型
4.yum有一个一致的信息模型
5.yuml易于实现
6.yuml可以基于流来处理
7.yuml表达能力强,拓展好
playbook的结构组成:
hosts:执行的远程主机列表
tasks:任务,由模块定义的操作的列表
variables:内置模块或自定义表里在playbook中可以进行调用
templates:模板,使用模板

  • 官方实例
    ```

  • hosts: webservers vars: http_port: 80 max_clients: 200 remote_user: root tasks:

    • name: ensure apache is at the latest version #定义任务名称 yum: #调用yum模块 name: httpd #yum模块的参数 state: latest
    • name: write the apache config file #定义任务名称 template: #模块,模板语法为j2 src: /srv/httpd.j2 dest: /etc/httpd.conf notify: #调用一个触发器(当条件满足的时候)
      • restart apache
    • name: ensure apache is running #定义任务名称 service: #service模块 name: httpd state: started handlers: #触发后的操作
      • name: restart apache service: name: httpd state: restarted ```
  • 运行playbook命令:

ansible-playbook -t:tag指定运行特定任务
ansible-playbook —skip-tags=SKIP_TAGS 跳过指定的标签
ansible-playbook —start-at-task=START_AT_TASK 从哪个任务后执行
ansible-playbook —syntax-check:运行测试,检查语法
ansible-playbook —check:测试运行

  • 变量
    • 变量来源:
      • ansible setup facts远程主机的所有变量都是可用的
    • 自定义变量:
      • 优先级:
        • 1.通过命令行指定变量,优先级最高:
        • 2./etc/ansible/hosts定义变量,在主机组中
        • 3.
        • 4.在playbook中定义变量

          templates模板:

  1. 文本文件,内部嵌套有模板语法脚本(使用模板语言编写)
  2. jinja2是由python编写的,在我们打算使用基于文本的模板语言是,jinja2是很好的解决方案,jinja2是写配置文件模板的
  3. 功能
    1. 将模板文件的变量转换成对应的本机主机的确定值

eg:

  • Jinja2语法
    • 字面量:
      • 字符串:使用单引号或者双引号
      • 数字:整数、浮点数……
      • 列表:
      • 元组
      • 字典:
      • 布尔型:
    • 算术运算符
    • 比较操作:== > < !=
    • 逻辑运算符:and or not
  • 条件判断:
    • -name:restart httpd
  • 循环迭代:
    • 基于字符串列表:
      • tasks:
        • -name:create file

copy:src =

  - with_items 嵌套的子变量
  • 基于字典列表
  • 1.定义变量

port:
index_dir:/var/www/data/

  • 2.使用Jinja2语法配置格式语法:

{{ var }}

角色

/etc/ansible/roles:存放角色