€¦  · Web...

49
一、Ansible 简简.................................................2 1 .........................................................2 2 .........................................................2 3 Ansible 简简...............................................2 Ansible 简简 CentOS 7.3 .......................................3 1 Pip 简简简简简简简简............................................3 2yum 简简....................................................3 3 ,简简简简简简 ............................................ 4 4 .........................................................6 1Ansible 简简简简简简简简简简....................................6 2hosts 简简简简,简简简简简简....................................15 简简 ...........................................................19 1command/shell...........................................19 2ping....................................................20 3setup...................................................21 4file....................................................21 5copy....................................................24 6user....................................................26 8yum.....................................................28 9service.................................................29 YAML.......................................................30 1YAML 简简..................................................30 2YAML 简简..................................................30 3 ........................................................30 Playbooks..................................................34 1 ........................................................34 2Playbook 简简简简............................................35 3 ........................................................38

Transcript of €¦  · Web...

Page 1: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

一、Ansible 简介...........................................................................................2

1、简介......................................................................................................2

2、特性......................................................................................................2

3、Ansible 架构...........................................................................................2

二、Ansible 安装(CentOS 7.3)以及配置文件................................................3

1、通过 Pip 安装最新发布版本......................................................................3

2、yum 安装..............................................................................................3

3、如果没法连接外网,可通过安装包逐个安装。...............................................4

4、配置文件...............................................................................................6

(1)Ansible 应用程序的主配置文件..........................................................6

(2)hosts 机器清单,进行分组管理..........................................................15

三、常见模块简介以及使用............................................................................19

1、command/shell..................................................................................19

2、ping...................................................................................................20

3、setup.................................................................................................21

4、file.....................................................................................................21

5、copy..................................................................................................24

6、user...................................................................................................26

Page 2: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

8、yum...................................................................................................28

9、service..............................................................................................29

四、YAML...................................................................................................30

1、YAML 概要..........................................................................................30

2、YAML 优点..........................................................................................30

3、语法规范与范例....................................................................................30

五、Playbooks............................................................................................34

1、简介...................................................................................................34

2、Playbook 语言示例..............................................................................35

3、示例...................................................................................................38

一、Ansible 简介

1、简介ansible 是新出现的自动化运维工具,基于 Python 研发。结合了众多老牌运维工

具的优点实现了批量操作系统配置、批量程序的部署、批量运行命令等功能。仅需在管理工作站上安装 ansible 程序以及配置被管控主机的 IP 信息,被管控的主机无客户端。 ansible 应用程序存在于 epel( 第三方社区 ) 源,依赖于很多 python 组件。

Page 3: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

2、特性基于 Python 语言实现,由 Paramiko (python 的一个可并发连接 ssh 主机功能

库 ) , PyYAML 和 Jinja2 ( 模板化 ) 三个关键模块实现;部署简单,客户端无需安装,更新时,只需在操作机上进行一次更新即可;支持 playbook 剧本,连续任务按先后设置顺序完成;

3、Ansible 架构

ansible core : ansible 自身核心模块host inventory: 主机库,定义可管控的主机列表connection plugins: 连接插件,一般默认基于 ssh 协议连接modules:core modules ( 自 带 模 块 ) 、 custom modules ( 自 定 义 模

块 )playbooks :剧本,按照所设定编排的顺序执行完成安排任务

Page 4: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

二、Ansible 安装(CentOS 7.3)以及

配置文件

1、通过 Pip 安装最新发布版本Ansible 可通过 “pip” 安装(安装和管理 Python 包的工具),若你还没有安装 pip,

可执行如下命令安装:easy_install pip然后安装 Ansible:pip install ansible

执行完成后出现下图则说明安装成功

Page 5: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

2、yum 安装配置 yum 源:

vi /etc/yum.repos.d/ansible.repo[ansible]baseurl=http://mirrors.aliyun.com/epel/7/x86_64/gpgcheck=0enabled=1

yum clean allyum repolist all

yum install ansible安装完成

3、如果没法连接外网,可通过安装包逐个安装。(1)、python2.7 安装https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz# tar xvzf Python-2.7.8.tgz# cd Python-2.7.8# ./configure --prefix=/usr/local# make --jobs=`grep processor/proc/cpuinfo | wc -l`# make install

## 将 python 头文件拷贝到标准目录,以避免编译 ansible 时,找不到所需的头文件

# cd /usr/local/include/python2.7# cp -a ./* /usr/local/include/

## 备份旧版本的 python,并符号链接新版本的 python# cd /usr/bin# mv python python2.6# ln -s /usr/local/bin/python

## 修改 yum 脚本,使其指向旧版本的 python,已避免其无法运行# vim /usr/bin/yum#!/usr/bin/python --> #!/usr/bin/python2.6

(2)、setuptools 模块安装https://pypi.python.org/packages/source/s/setuptools/setuptools-

7.0.tar.gz

Page 6: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# tar xvzf setuptools-7.0.tar.gz# cd setuptools-7.0# python setup.py install

(3)、pycrypto 模块安装https://pypi.python.org/packages/source/p/pycrypto/pycrypto-

2.6.1.tar.gz# tar xvzf pycrypto-2.6.1.tar.gz# cd pycrypto-2.6.1# python setup.py install

(4)、PyYAML 模块安装http://pyyaml.org/download/libyaml/yaml-0.1.5.tar.gz# tar xvzf yaml-0.1.5.tar.gz# cd yaml-0.1.5# ./configure --prefix=/usr/local# make --jobs=`grep processor/proc/cpuinfo | wc -l`# make install

https://pypi.python.org/packages/source/P/PyYAML/PyYAML-3.11.tar.gz# tar xvzf PyYAML-3.11.tar.gz# cd PyYAML-3.11# python setup.py install

(5)、Jinja2 模块安装https://pypi.python.org/packages/source/M/MarkupSafe/MarkupSafe-

0.9.3.tar.gz# tar xvzf MarkupSafe-0.9.3.tar.gz# cd MarkupSafe-0.9.3# python setup.py install

https://pypi.python.org/packages/source/J/Jinja2/Jinja2-2.7.3.tar.gz# tar xvzf Jinja2-2.7.3.tar.gz# cd Jinja2-2.7.3# python setup.py install

(6)、paramiko 模块安装https://pypi.python.org/packages/source/e/ecdsa/ecdsa-0.11.tar.gz# tar xvzf ecdsa-0.11.tar.gz# cd ecdsa-0.11# python setup.py install

https://pypi.python.org/packages/source/p/paramiko/paramiko-1.15.1.tar.gz

Page 7: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# tar xvzf paramiko-1.15.1.tar.gz# cd paramiko-1.15.1# python setup.py install

(7)、simplejson 模块安装https://pypi.python.org/packages/source/s/simplejson/simplejson-

3.6.5.tar.gz# tar xvzf simplejson-3.6.5.tar.gz# cd simplejson-3.6.5# python setup.py install

(8)、ansible 安装https://github.com/ansible/ansible/archive/v1.7.2.tar.gz# tar xvzf ansible-1.7.2.tar.gz# cd ansible-1.7.2# python setup.py install

4、配置文件

(1)Ansible 应用程序的主配置文件/etc/ansible/ansible.cfg(ansible.cfg:主要设置一些 ansible 初始化的信息,比

如日志存放路径、模块、插件等配置信息) [root@ansible1 ansible]# more /etc/ansible/ansible.cfg

# config file for ansible -- http://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 (指定默认 hosts 配置的位置)

Page 8: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

#library = /usr/share/my_modules/ (Ansible 默认搜寻模块的位置)#remote_tmp = ~/.ansible/tmp (Ansible 通过远程传输模块到远程主机,然后远程执行,执行后在清理现场.在有些场景下想更换路径 , 这时候你可以使用这个选项, 默认路径是在用户家目录下属的目录.Ansible 会在这个目录中使用一个随机的文件夹名称.)#local_tmp = ~/.ansible/tmp(同上)#forks = 5(在与主机通信时的默认并行进程数,默认是 5)#poll_interval = 15(对于 Ansible 中的异步任务, 这个是设置定义,当具体的 poll interval 没有定义时,多少时间回查一下这些任务的状态, 默认值是一个折中选择 15秒钟)#sudo_user = root(sudo 使用的默认用户 ,默认是 root)#ask_sudo_pass = True (用来控制 Ansible playbook 在执行 sudo之前是否询问sudo密码.默认为 no)#ask_pass = True (控制 Ansible playbook 是否会自动默认弹出密码,默认为no)#transport = smart(通信机制.默认值为 smart)#remote_port = 22 (远程 SSH 端口。默认是 22)#module_lang = C (模块和系统之间通信的计算机语言,默认是 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 ( 控制默 认 facts 收集( 远 程 系 统变量 ) . 默 认值为’implicit’, 每一次 play,facts都会被收集)# by default retrieve 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 (收集 facts 的类型)# 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

Page 9: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# environment. # gather_timeout = 10 (收集 facts 的超时时间)# additional paths to search for roles in, colon separated#roles_path = /etc/ansible/roles (roles 路径是指 roles/下的额外目录,用于playbook 搜索 Ansible roles.比如, 如果我们有个用于 common roles 源代码控制仓库和一个不同的 playbooks仓库,你也许会建立一个惯例去在 /opt/mysite/roles 里面查找 roles.:roles_path = /opt/mysite/roles多余的路径可以用冒号分隔,类似于其他 path字符串:roles_path = /opt/mysite/roles:/opt/othersite/rolesRoles 将会在 playbook 目录中开始搜索.如果 role 没有找到,这个参数指定了其它可能的搜索路径.)# uncomment this to disable SSH key host checking#host_key_checking = False (检查主机密钥)# change the default callback#stdout_callback = skippy# enable additional callbacks#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 = True#handler_includes_static = True

# 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 (如果在其他远程主机上使用另一种方式执 sudo 操作.可以使用该参数进行更换)# What flags to pass to sudo# WARNING: leaving out the defaults might create unexpected behaviours#sudo_flags = -H -S –n (传递 sudo 的一些参数)# SSH timeout#timeout = 10 (SSH超时时间)

Page 10: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# default user to use for playbooks if user is not specified# (/usr/bin/ansible will use current user as default)#remote_user = root (使用/usr/bin/ansible-playbook 链接的默认用户名,如果不指定,会使用当前登录的用户名)# 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 (ansible 命令执行默认的模块)# 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 ( 在 sudo 环境下产生一 个 shell 交互接口 . 用 户 只在/bin/bash 的或者 sudo限制的一些场景中需要修改)# 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 (默认情况下,角色中的变量将在全局变量范围中可见。 为了防止这种情况,可以启用以下选项,只有 tasks 的任务和 handlers得任务可以看到角色变量)# list any Jinja2 extensions to enable here:#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n (允许开启 Jinja2拓展模块)# 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

Page 11: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# 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 (定 义一 个 Jinja2 变量 ,可 以插入到Ansible 配置模版系统生成的文件中)# by default, ansible-playbook will display "Skipping [host]" if it determines a task# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"# messages. NOTE: the task header will still be shown regardless of whether or not the# task is skipped.#display_skipped_hosts = True (显示任何跳过任务的状态 ,默认是显示)# by default, if a task in a playbook does not include a name: field then# ansible-playbook will construct a header that includes the task's action but# not the task's args. This is a security feature because ansible cannot know# if the *module* considers an argument to be no_log at the time that the# header is printed. If your environment doesn't have a problem securing# stdout from ansible-playbook (or you have manually specified no_log in your# playbook on all of the tasks where you have secret information) then you can# safely set this to True to get more informative messages.#display_args_to_stdout = False

# by default (as of 1.3), Ansible will raise errors when attempting to dereference# Jinja2 variables that are not set in templates or action lines. Uncomment this line# to revert the behavior to pre-1.3.#error_on_undefined_vars = False (如果所引用的变量名称错误的话, 将会导致ansible 在执行步骤上失败)# by default (as of 1.6), Ansible may display warnings based on the configuration of the# system running ansible itself. This may include warnings about 3rd party

Page 12: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

packages or# other conditions that should be resolved if possible.# to disable these warnings, set the following value to False:#system_warnings = True (允许禁用系统运行 ansible相关的潜在问题警告,这个包括第三方库或者一些需要解决问题的警告)# by default (as of 1.4), Ansible may display deprecation warnings for language# features that should no longer be used and will be removed in future versions.# to disable these warnings, set the following value to False:#deprecation_warnings = True (允许在 ansible-playbook 输出结果中禁用“不建议使用”警告:“不建议警告”指的是使用一些在新版本中可能会被淘汰的遗留特性.)# (as of 1.8), Ansible can optionally warn when usage of the shell and# command module appear to be simplified by using a default Ansible module# instead. These warnings can be silenced by adjusting the following# setting or adding warn=yes or warn=no to the end of the command line# parameter string. This will for example suggest using the git module# instead of shelling out to the git command.# command_warnings = False ( 当 shell 和 命 令 行 模 块 被 默 认 模 块 简 化 的时,Ansible 将默认发出警告)

# set plugin path directories here, separate with colons#action_plugins = /usr/share/ansible/plugins/action (设 置 模块 的存 放路径)#cache_plugins = /usr/share/ansible/plugins/cache#callback_plugins = /usr/share/ansible/plugins/callback#connection_plugins = /usr/share/ansible/plugins/connection#lookup_plugins = /usr/share/ansible/plugins/lookup#inventory_plugins = /usr/share/ansible/plugins/inventory#vars_plugins = /usr/share/ansible/plugins/vars#filter_plugins = /usr/share/ansible/plugins/filter#test_plugins = /usr/share/ansible/plugins/test#strategy_plugins = /usr/share/ansible/plugins/strategy

# by default callbacks are not loaded for /bin/ansible, enable this if you# want, for example, a notification or logging callback to also apply to# /bin/ansible runs#bin_ansible_callbacks = False ( 用 来 控 制 callback 插 件 是 否 在 运 行 /usr/bin/ansible 的时候被加载. 这个模块将用于命令行的日志系统,发出通知等特性)

Page 13: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# don't like cows? that's unfortunate.# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1#nocows = 1

# set which cowsay stencil you'd like to use by default. When set to 'random',# a random stencil will be selected for each task. The selection will be filtered# against the `cow_whitelist` option below.#cow_selection = default#cow_selection = random

# when using the 'random' option for cowsay, stencils will be restricted to this list.# it should be formatted as a comma-separated list with no spaces between names.# NOTE: line continuations here are for formatting purposes only, as the INI parser# in python does not support them.#cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\# hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\# stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www

# don't like colors either?# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1#nocolor = 1 (输出带上颜色区别, 开启/关闭:0/1)# if set to a persistent type (not 'memory', for example 'redis') fact values# from previous runs in Ansible will be stored. This may be useful when# wanting to use, for example, IP information from one group of servers# without having to talk to them in the same playbook run to get their# current IP information.#fact_caching = memory (fact值默认存储在内存中,可以设置存储在 redis 中,用于持久化存储)

# retry files# When a playbook fails by default a .retry file will be created in ~/# You can disable this feature by setting retry_files_enabled to False# and you can change the location of the files by setting

Page 14: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

retry_files_save_path

#retry_files_enabled = False (当 playbook失败得情况下,一个重试文件将会创建,默认为开启此功能)#retry_files_save_path = ~/.ansible-retry (重试文件的路径,默认为当前目录下.ansible-retry)# squash actions# Ansible can optimise actions that call modules with list parameters# when looping. Instead of calling the module once per with_ item, the# module is called once with all items at once. Currently this only works# under limited circumstances, and only with parameters named 'name'.#squash_actions = apk,apt,dnf,homebrew,package,pacman,pkgng,yum,zypper

# prevents logging of task data, off by default#no_log = False (任务数据的日志记录,默认情况下关闭)# prevents logging of tasks, but only on the targets, data is still logged on the master/controller#no_target_syslog = False

# controls whether Ansible will raise an error or warning if a task has no# choice but to create world readable temporary files to execute a module on# the remote machine. This option is False by default for security. Users may# turn this on to have behaviour more like Ansible prior to 2.1.x. See# https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user# for more secure ways to fix this than enabling this option.#allow_world_readable_tmpfiles = False

# controls the compression level of variables sent to# worker processes. At the default of 0, no compression# is used. This value must be an integer from 0 to 9.#var_compression_level = 9 (控制发送到工作进程的变量的压缩级别。 默认值为0,不使用压缩。 此值必须是从 0 到 9 的整数)# controls what compression method is used for new-style ansible modules when# they are sent to the remote system. The compression types depend on having# support compiled into both the controller's python and the client's

Page 15: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

python.# The names should match with the python Zipfile compression types:# * ZIP_STORED (no compression. available everywhere)# * ZIP_DEFLATED (uses zlib, the default)# These values may be set per host via the ansible_module_compression inventory# variable#module_compression = 'ZIP_DEFLATED' (指定压缩方法,默认使用 zlib压缩,可以通过 ansible_module_compression来为每个主机设置)# This controls the cutoff point (in bytes) on --diff for files# set to 0 for unlimited (RAM may suffer!).#max_diff_size = 1048576

[privilege_escalation]#become=True#become_method=sudo#become_user=root#become_ask_pass=False

[paramiko_connection]

# uncomment this line to cause the paramiko connection plugin to not record new host# keys encountered. Increases performance on new host additions. Setting works independently of the# host key checking setting above.#record_host_keys=False

# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this# line to disable this behaviour.#pty=False

[ssh_connection]

# ssh arguments to use# Leaving off ControlPersist will result in poor performance, so use# paramiko on older platforms rather than removing it, -C controls compression use#ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s (ssh 连接时得参数)# The path to use for the ControlPath sockets. This defaults to

Page 16: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with# very long hostnames or very long path names (caused by long user names or# deeply nested home directories) this can exceed the character limit on# file socket names (108 characters for most platforms). In that case, you# may wish to shorten the string below.## Example:# control_path = %(directory)s/%%h-%%r#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r

# Enabling pipelining reduces the number of SSH operations required to# execute a module on the remote server. This can result in a significant# performance improvement when enabled, however when using "sudo:" you must# first disable 'requiretty' in /etc/sudoers## By default, this option is disabled to preserve compatibility with# sudoers configurations that have requiretty (the default on many distros).##pipelining = False (SSH pipelining 是一个加速 Ansible 执行速度的简单方法ssh pipelining 默认是关闭,之所以默认关闭是为了兼容不同的 sudo 配置,主要是 requiretty 选项。如果不使用 sudo,建议开启。打开此选项可以减少 ansible 执行没有传输时 ssh 在被控机器上执行任务的连接数。不过,如果使用 sudo,必须关闭 requiretty 选项。)# Control the mechanism for transfering files# * smart = try sftp and then try scp [default]# * True = use scp only# * False = use sftp only#scp_if_ssh = smart (设置传输文件的方法)# if False, sftp will not use batch mode to transfer files. This may cause some# types of file transfer failures impossible to catch however, and should# only be disabled if your sftp version has problems with batch mode#sftp_batch_mode = False (该项为 False 时,sftp 不会使用批处理模式传输文件。 这可能导致一些类型的文件传输失败而不可捕获,但应该只有在您的 sftp 版本在批处理模式上有问题时才应禁用)[accelerate]#accelerate_port = 5099

Page 17: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

#accelerate_timeout = 30#accelerate_connect_timeout = 5.0

# The daemon timeout is measured in minutes. This time is measured# from the last activity to the accelerate daemon.#accelerate_daemon_timeout = 30

# If set to yes, accelerate_multi_key will allow multiple# private keys to be uploaded to it, though each user must# have access to the system via SSH to add a new key. The default# is "no".#accelerate_multi_key = yes

[selinux]# file systems that require special treatment when dealing with security context# the default behaviour that copies the existing context or uses the user default# needs to be changed to use the file system dependent context.#special_context_filesystems=nfs,vboxsf,fuse,ramfs (文件系统在处理安全上下文时需要特殊处理,定义复制现有上下文的文件系统)# Set this to yes to allow libvirt_lxc connections to work without SELinux.#libvirt_lxc_noseclabel = yes (将此设置为 yes,以允许 libvirt_lxc 连接在没有SELinux 的情况下工作)[colors] (定义输出颜色)#highlight = white#verbose = blue#warn = bright purple#error = red#debug = dark gray#deprecate = purple#skip = cyan#unreachable = red#ok = green#changed = yellow#diff_add = green#diff_remove = red#diff_lines = cyan

简易配置:[defaults]

Page 18: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

inventory = /etc/ansible/hostssudo_user=rootremote_port=22host_key_checking=Falseremote_user=rootlog_path=/var/log/ansible.logmodule_name=commandprivate_key_file=/root/.ssh/id_rsa

(2)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

Page 19: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

## [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

/etc/ansible/hosts 文件的格式如下:

mail.example.com

[webservers]foo.example.combar.example.com

[dbservers]one.example.comtwo.example.comthree.example.com方括号[]中是组名,用于对系统进行分类,便于对不同系统进行个别的管理.

一个系统可以属于不同的组,比如一台服务器可以同时属于 webserver 组 和 dbserver 组.这时属于两个组的变量都可以为这台主机所用.

如果有主机的 SSH 端口不是标准的 22 端口,可在主机名之后加上端口号,用冒号分隔. 端口号不是默认设置时,可明确的表示为:badwolf.example.com:5309

假设你有一些静态 IP地址,希望设置一些别名,但不是在系统的 host 文件中设置,又或者你是通过隧道在连接,那么可以设置如下:jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50在 这 个 例子中 , 通 过 “ jumper” 别名 , 会 连 接 192.168.1.50:5555.记住 , 这 是 通 过 inventory 文件的特性功能设置的变量. 一般而言,这不是设置变量(描述你的系统策略的变量)的最好方式.后面会说到这个问题.

一组相似的 hostname , 可简写如下:[webservers]www[01:50].example.com

Page 20: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

表示从web1 到 web50

数字的简写模式中,01:50 也可写为 1:50,意义相同.你还可以定义字母范围的简写模式:[databases]db-[a:f].example.com

对于每一个 host,你还可以选择连接类型和连接用户名:[targets]localhost ansible_connection=localother1.example.com ansible_connection=ssh ansible_ssh_user=mpdehaanother2.example.com ansible_connection=ssh ansible_ssh_user=mdehaan

主机变量 可以在 inventory 中定义主机时为其添加主机变量以便于在 playbook 中使用。例如: [webservers] www1.magedu.com http_port=801 maxRequestsPerChild=808

# 自定义 http_port 的端口号为 801,配置 maxRequestsPerChild为 808 组变量 组变量是指赋予给指定组内所有主机上的在 playbook 中可用的变量。例如: [webservers] www1.magedu.com www2.magedu.com [webservers:vars] ntp_server=ntp.magedu.com nfs_server=nfs.magedu.com #webservers 组中所有主机定义 ntp_server值为 ntp.magedu.com ,nfs_server的值为 nfs.magedu.com

组嵌套 inventory 中,组还可以包含其它的组,并且也可以向组中的主机指定变量。不过,这些变量只能在 ansible-playbook 中使用,而 ansible 不支持。例如: [apache] httpd1.magedu.com httpd2.magedu.com [nginx] ngx1.magedu.com ngx2.magedu.com [webservers:children] apache

Page 21: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

nginx [webservers:vars]

ntp_server=ntp.magedu.com

Inventory 常见参数的说明如同前面提到的,通过设置下面的参数,可以控制 ansible 与远程主机的交互方式:ansible_ssh_host 将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.

ansible_ssh_port ssh 端口号.如果不是默认的端口号,通过此变量设置.

ansible_ssh_user 默认的 ssh 用户名ansible_ssh_pass ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)

ansible_sudo_pass sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)

ansible_sudo_exe (new in version 1.8) sudo 命令路径(适用于 1.8 及以上版本)

ansible_connection 与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用

paramiko.1.2 以后默认使用 'smart','smart' 方式会根据是否支持 ControlPersist, 来判断'ssh' 方式是否可行.

ansible_ssh_private_key_file ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.

ansible_shell_type 目标系统的 shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为 'csh' 或

'fish'.

ansible_python_interpreter 目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不

是"/usr/bin/python",比如 \*BSD, 或者 /usr/bin/python 不是 2.X 版本的 Python.我们不使用 "/usr/bin/env" 机制,因为这要求远程用户

的路径设置正确,且要求 "python" 可执行程序名不可为 python 以外的名字(实际有可能名为 python26).

Page 22: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

ansible_ruby_interpreter 与 ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路

径....

一个主机文件的例子:some_host ansible_ssh_port=2222 ansible_ssh_user=manageraws_host

ansible_ssh_private_key_file=/home/example/.ssh/aws.pemfreebsd_host ansible_python_interpreter=/usr/local/bin/pythonruby_module_host ansible_ruby_interpreter=/usr/bin/ruby.1.9.3

测试机配置(新增如下几行):[test]192.168.67.138192.168.67.137

三、常见模块简介以及使用

1、command/shell

用于在各被管理节点运行指定的命令查看帮助:ansible-doc –s commandshell 和 command 的区别:shell 模块可以特殊字符,而 command 是不支持ansible all -m command -a "/bin/echo hello" -k

查看远程主机文件系统:ansible test -m command -a "df -h" –k

Page 23: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

如果管理主机和其它客户端主机未配置信任关系,执行命令的时候需加上 -k(--ask-pass ask for SSH password 提示用户输入密码)选项,因为此处两台主机的口令一样,所以只提示一次,不一样的话会提示两次

2、ping

查看远程主机的运行状态。主机如果在线,则回复 pong。查看帮助:ansible-doc –s ping执行命令:ansible all -m ping --ask-pass -u root

也可以指定群组中的某台机器查看:

Page 24: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

3、setup

收集可用的 facts,收集每个节点的相关信息:架构信息, IP,时间,域名,网卡,MAC,主机 CPU 等信息。这些收集的信息,可以作为变量。查看帮助:ansible-doc –s setup

4、file

设置文件的属性查看帮助:ansible-doc –s file相关选项如下:

Page 25: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

force:需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no

group:定义文件/目录的属组mode:定义文件/目录的权限owner:定义文件/目录的属主path:必选项,定义文件/目录的路径recurse:递归设置文件的属性,只对目录有效src:被链接的源文件路径,只应用于 state=link 的情况dest:被链接到的路径,只应用于 state=link 的情况state:

       directory:如果目录不存在,就创建目录       file:即使文件不存在,也不会被创建       link:创建软链接       hard:创建硬链接       touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间       absent:删除目录、文件或者取消链接文件示例:## 远程文件符号链接创建# ansible test-m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link"

查看远程文件信息:# ansible test -m command -a "ls –al /tmp/resolv.conf"

## 远程文件符号链接删除# ansible test -m file -a "path=/tmp/resolv.conf state=absent"

Page 26: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

## 远程文件信息查看# ansible test -m command -a "ls –l /tmp/resolv.conf"

说明:如上显示,代表文件或链接已经删除。新建一个文件

查看文件信息:

创建一个目录并递归设置文件的属主或者属组:

Page 27: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

查看远程文件信息:

5、copy

远程复制备份模块查看帮助:ansible-doc –s copy模块参数详解:src:指定源文件路径,可以是相对路径,也可以是绝对路径,可以是目录(并非是必须的,可以使用 content,直接生成文件内容)dest=:指定目标文件路径,只能是绝对路径,如果 src 是目录,此项必须是目录owner:指定属主group:指定属组mode:指定权限,可以以数字指定比如 0644content:代替 src ,直接往 dest 文 件 中写内容, 可 以引用变量 ,也可 以直接 使 用inventory 中的主机变量backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|noforce:yes:默认项,如果目标主机包含该文件,但内容不同,则强制覆盖no:则只有当目标主机的目标位置不存在该文件时,才复制directory_mode:递归的设定目录的权限,默认为系统默认权限## 将本地文件“/etc/ansible/ansible.cfg”复制到远程服务器# ansible test -m copy -a "src=/etc/ansible/ansible.cfg dest=/root owner=root group=root mode=0644" –k

Page 28: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

远程主机查看:

向远程主机的文件中写内容,会把原内容覆盖掉

查看远程文件信息:

Page 29: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

6、user

管理用户查看帮助:ansible-doc –s user模块参数详解:name:指定用户名password:设定用户密码,password参数需要接受md5加密后的值state:用户状态,默认为 presentpresent:表示添加用户absent:表示删除用户update_password:修改用户密码always:新密码和旧密码不同时进行修改on_create:为新创建的用户指定密码createhome:创建家目录yes:默认项,即创建用户默认是有家目录的no:创建用户时不创建家目录remove:yes:删除用户家目录,需要指定此参数no:默认项,删除用户时默认不删除用户的家目录system:yes:默认创建为普通用户,而非系统用户如果不指定默认生成的选项有:home:创建家目录shell:创建默认的 shell为/bin/bashsystem:默认创建为普通用户,而非系统用户,指定是用 yes[root@localhost ~]# echo 123456 | openssl passwd -1 -stdin$1$cu2rSfkw$hUtP/Ri0j8QZ7pxb1ii3M0增加一个用户

到远程主机测试 test/123456 是否能正常登陆删除一个用户

Page 30: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

查看远程主机 test 是否被删除

更新用户的密码[root@localhost ~]# echo 654321 | openssl passwd -1 -stdin$1$Fn3fyDqz$ml3TBYcV7z.eEW4y2pIdS/

7、cron

任务计划模块查看帮助:ansible-doc –s cron模块参数详解:state:present:创建任务absent:删除任务backup:对远程主机上的原任务计划内容修改之前做备份job:要执行的任务name:该任务的描述(必须项)user:以哪个用户的身份运行minute:分钟(0-59,*,*/2,……),不写默认为*hour:小时(0-23,*,*/2,……),不写默认为*

Page 31: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

day:日(1-31,*,*/2,……),不写默认为*month:月(1-12,*,*/2,……),不写默认为*weekday:周(0-7,*,……),不写默认为*每隔 1 分钟同步一下时间

查看远程 crontab 任务:

8、yum

安装模块查看帮助:ansible-doc –s yum模块参数详解:name:表示要安装软件包的名字,默认最新的程序包,指明要安装的程序包,可以带上版本号state:表示是安装还卸载present:默认的,表示为安装lastest:安装为最新的版本absent:表示删除如:- name: 安装最新版本的 apache yum: name=httpd state=latest

- name: 移除 apache yum: name=httpd state=absent

- name: 安装一个特殊版本的 apache yum: name=httpd-2.2.29-1.4.amzn1 state=present

- name: 升级所有的软件包 yum: name=* state=latest

Page 32: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

- name: 从一个远程 yum仓库安装 nginx yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

- name: 从本地仓库安装 nginx yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present安装 nginx:

9、service

服务模块查看帮助:ansible-doc –s serviceenabled:表示设置服务开机是否启动,取值为 true或者 false;enabled=yesname=:表示要控制哪一个服务state:started:表示现在就启动此服务stopped:表示现在关闭此服务restarted:表示重启此服务sleep:如果执行了 restarted,在 stop 和 start之间沉睡几秒runlevel:定义在哪些级别可以自启动arguments:表示向命令行传递的参数设置 http启动并设为开机启动:

Page 33: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

四、YAML

1、YAML 概要[YAML](http://yaml.org/)是"YAML Ain't a Markup Language"(YAML 不是一种

置 标 语 言 ) 的递归缩写,早先 YAML 的意思其 实 是 : "Yet Another Markup Language"(另外一种置标语言),但为了强调这种语言以数据做为中心,而不是以置标语言为重点,而用返璞词重新命名,YAML 的官方定义很简单,即”一种人性化的数据格式定义语言”,其主要功能用途类似于 XML或 JSON,YAML 使用空白字符和分行来分隔数据,且巧妙避开各种封闭符号,如:引号、括号等,以避免这些符号在复杂层次结构中变得难以辨认。YAML 的语法与高阶语言类似,可以很简单地表述*序列( java 中的list)、杂凑表(java 中的 map)、标量(java 中的基本类型等)*数据结构,它重点强调可阅读性。

2、YAML 优点 > - YAML 的可读性好

> - YAML 和脚本语言的交互性好> - YAML 使用实现语言的数据类型> - YAML 有一个一致的信息模型> - YAML易于实现

Page 34: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

3、语法规范与范例> -大小写敏感> -使用缩进表示层级关系> -缩进时不允许使用 Tab 键,只允许使用空格。> -缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

(http://www.ruanyifeng.com/blog/2016/07/yaml.html?f=tt)# 表示注释,从这个字符一直到行尾,都会被解析器忽略可通过如下网站检查语法是否正确:http://nodeca.github.io/js-yaml/http://www.yamllint.com/

YAML 支持的数据结构有三种。对象: 键值对 的集合 ,又称为映射( mapping ) / 哈希( hashes ) / 字典

(dictionary);数组:一组按次序排列的值,又称为序列(sequence)/列表(list);纯量(scalars):单个的、不可再分的值

对象:对象的一组键值对,使用冒号结构表示。animal: pets转为 JavaScript 如下。{ animal: 'pets' }

Yaml 也允许另一种写法,将所有键值对写成一个行内对象。hash: { name: Steve, foo: bar } 转为 JavaScript 如下。{ hash: { name: 'Steve', foo: 'bar' } }

数组一组连词线开头的行,构成一个数组。- Cat- Dog- Goldfish转为 JavaScript 如下。[ 'Cat', 'Dog', 'Goldfish' ]

数据结构的子成员是一个数组,则可以在该项下面缩进一个空格。- - Cat - Dog - Goldfish转为 JavaScript 如下。

Page 35: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

[ [ 'Cat', 'Dog', 'Goldfish' ] ]

数组也可以采用行内表示法。animal: [Cat, Dog]转为 JavaScript 如下。{ animal: [ 'Cat', 'Dog' ] }

复合结构对象和数组可以结合使用,形成复合结构。languages: - Ruby - Perl - Python websites: YAML: yaml.org Ruby: ruby-lang.org Python: python.org Perl: use.perl.org 转为 JavaScript 如下。{ languages: [ 'Ruby', 'Perl', 'Python' ], websites: { YAML: 'yaml.org', Ruby: 'ruby-lang.org', Python: 'python.org', Perl: 'use.perl.org' } }

纯量纯量是最基本的、不可再分的值。以下数据类型都属于 JavaScript 的纯量。字符串布尔值整数浮点数Null时间日期数值直接以字面量的形式表示。number: 12.30转为 JavaScript 如下。{ number: 12.30 }

布尔值用 true 和 false 表示。isSet: true转为 JavaScript 如下。{ isSet: true }

Page 36: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

null 用~表示。parent: ~ 转为 JavaScript 如下。{ parent: null }

时间采用 ISO8601 格式。iso8601: 2001-12-14t21:59:43.10-05:00 转为 JavaScript 如下。{ iso8601: new Date('2001-12-14t21:59:43.10-05:00') }

日期采用复合 iso8601 格式的年、月、日表示。date: 1976-07-31转为 JavaScript 如下。{ date: new Date('1976-07-31') }

YAML 允许使用两个感叹号,强制转换数据类型。e: !!str 123f: !!str true转为 JavaScript 如下。{ e: '123', f: 'true' }

字符串字符串是最常见,也是最复杂的一种数据类型。字符串默认不使用引号表示。str: 这是一行字符串转为 JavaScript 如下。{ str: '这是一行字符串' }

如果字符串之中包含空格或特殊字符,需要放在引号之中。str: '内容: 字符串'转为 JavaScript 如下。{ str: '内容: 字符串' }

单引号和双引号都可以使用,双引号不会对特殊字符转义。s1: '内容\n字符串's2: "内容\n字符串"转为 JavaScript 如下。{ s1: '内容\\n字符串', s2: '内容\n字符串' }

单引号之中如果还有单引号,必须连续使用两个单引号转义。str: 'labor''s day' 转为 JavaScript 如下。{ str: 'labor\'s day' }

Page 37: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格。str: 这是一段 多行 字符串转为 JavaScript 如下。{ str: '这是一段 多行 字符串' }

多行字符串可以使用|保留换行符,也可以使用>折叠换行。this: | Foo Barthat: > Foo Bar转为 JavaScript 代码如下。{ this: 'Foo\nBar\n', that: 'Foo Bar\n' }

引用锚点&和别名*,可以用来引用。defaults: &defaults adapter: postgres host: localhostdevelopment: database: myapp_development <<: *defaultstest: database: myapp_test <<: *defaults等同于下面的代码。defaults: adapter: postgres host: localhostdevelopment: database: myapp_development adapter: postgres host: localhosttest: database: myapp_test adapter: postgres host: localhost&用来建立锚点(defaults),<<表示合并到当前数据,*用来引用锚点。下面是另一个例子。- &showell Steve

Page 38: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

- Clark - Brian - Oren - *showell 转为 JavaScript 代码如下。[ 'Steve', 'Clark', 'Brian', 'Oren', 'Steve' ]

五、Playbooks

1、简介简单来说,playbooks 是一种简单的配置管理系统与多机器部署系统的基础.与现有的

其他系统有不同之处,且非常适合于复杂应用的部署.Playbooks 可用于声明配置,更强大的地方在于,在 playbooks 中可以编排有序的执行过程,甚至于做到在多组机器间,来回有序的执行特别指定的步骤.并且可以同步或异步的发起任务.

2、Playbook 语言示例Playbooks 的格式是 YAML,语法做到最小化,意在避免 playbooks 成为一种编程语言

或是脚本。playbook 由一个或多个‘plays’ 组成.它的内容是一个以‘plays’为元素的列表.在 play 之中,一组机器被映射为定义好的角色.在 ansible 中,play 的内容,被称为

tasks, 即 任 务 . 在 基 本层次 的 应 用 中 ,一 个 任 务 是 一 个 对 ansible 模 块 的调用 .通 过 playbook,可以编排步骤进行多机器的部署,比如在 webservers 组的所有机器上运行一定的步骤, 然后在 database server 组运行一些步骤,最后回到 webservers 组,再运行一些步骤,诸如此类.

示例---- hosts: webservers vars: http_port: 80 max_clients: 200 remote_user: root

Page 39: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

tasks: - name: ensure apache is at the latest version yum: pkg=httpd state=latest - name: write the apache config file template: src=/srv/httpd.j2 dest=/etc/httpd.conf notify: - restart apache - name: ensure apache is running service: name=httpd state=started handlers: - name: restart apache service: name=httpd state=restarted

playbook 基础主机与用户你可以为 playbook 中的每一个 play,个别地选择操作的目标机器是哪些,以哪个用户身份去完成要执行的步骤(called tasks).

hosts 行的内容是一个或多个组或主机,以逗号为分隔符.remote_user 就是远程用户名:---- hosts: webservers remote_user: root

再者,在每一个 task 中,可以定义自己的远程用户:---- hosts: webservers remote_user: root tasks: - name: test connection ping: remote_user: yourname

也支持从 sudo 执行命令:---- hosts: webservers remote_user: yourname sudo: yes

同样的,你可以仅在一个 task 中,使用 sudo 执行命令,而不是在整个 play 中使用 sudo:---- hosts: webservers

Page 40: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

remote_user: yourname tasks: - service: name=nginx state=started sudo: yes

你也可以登陆后,sudo 到不同的用户身份,而不是使用 root:---- hosts: webservers remote_user: yourname sudo: yes sudo_user: postgres

如果你需要在使用 sudo 时指定密码,可在运行 ansible-playbook 命令时加上选项 --ask-sudo-pass (-K). 如果使用 sudo 时,playbook 疑似被挂起,可能是在 sudo prompt 处被卡住,这时可执行 Control-C 杀死卡住的任务,再重新运行一次.

Tasks 列表每一个 play 包含了一个 task 列表(任务列表).一个 task 在其所对应的所有主机上(通过 host pattern 匹配的所有主机)执行完毕之后,下一个 task 才会执行.有一点需要明白的是(很重要),在一个 play 之中,所有 hosts 会获取相同的任务指令,这是 play 的一个目的所在,也就是将一组选出的 hosts 映射到 task.

在运行 playbook 时(从上到下执行),如果一个 host 执行 task 失败,这个 host 将会从整个 playbook 中移除. 如果发生执行失败的情况,请修正 playbook 中的错误,然后重新执行即可.

每个 task 的目标在于执行一个 moudle, 通常是带有特定的参数来执行.在参数中可以使用变量(variables).

每一个 task 必须有一个名称 name,这样在运行 playbook 时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个 task 的. 如果没有定义 name,‘action’ 的值将会用作输出信息中标记特定的 task.

下面是一种基本的 task 的定义: tasks: - name: make sure apache is running

service: name=httpd state=running

比较特别的两个 modudle 是 command 和 shell ,它们不使用 key=value 格式的参数,而是这样:tasks: - name: disable selinux

command: /sbin/setenforce 0

Page 41: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

如果 action 行看起来太长,你可以使用 space(空格) 或者 indent(缩进) 隔开连续的一行:tasks: - name: Copy ansible inventory file to client copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts owner=root group=root mode=0644

Handlers: 在发生改变时执行的操作如果某一次操作配置文件发生改变的话,远程和本地配置文件不一致,那么肯定是将其配置文件需要进行覆盖,这样需要在配置文件发送改变的话需要触动某些机制进行操作。说白了就是事先可以在某些条件下,比如配置发生改变被触发的操作Rolesroles 用于层次性、结构化地组织 playbook。roles 能够根据层次型结构自动装载变量文件、tasks 以及 handlers 等。简单来讲,roles就是通过分别将变量(vars)、文件(file)、任务(tasks)、模块(modules)及处理器(handlers)放置于单独的目录中,并可以便捷地 include它们的一种机制。创建 roles 的步骤(1) 创建以 roles 命名的目录;(2) 在 roles 目录中分别创建以各角色名称命名的目录,如 webservers 等。注意:在 roles 必须包括 site.yml 文件,可以为空;(3) 在每个角色命名的目录中分别创建 files、handlers、meta、tasks、templates 和vars 目录;用不到的目录可以创建为空目录,也可以不创建;(4) 在 playbook 文件中,调用各角色;roles 内各目录中可用的文件tasks 目录:至少应该包含一个名为main.yml 的文件,其定义了此角色的任务列表;此文件可以使用 include 包含其它的位于此目录中的 task 文件;files 目录:存放由 copy或 script 等模块调用的文件;templates 目录:template 模块会自动在此目录中寻找 Jinja2 模板文件;handlers 目录:此目录中应当包含一个 main.yml 文件,用于定义此角色用到的各handler;在 handler 中使用 include 包含的其它的 handler 文件也应该位于此目录中;vars 目录:应当包含一个 main.yml 文件,用于定义此角色用到的变量;meta 目录:应当包含一个 main.yml 文件,用于定义此角色的特殊设定及其依赖关系;ansible 1.3 及其以后的版本才支持;default 目录:为当前角色设定默认变量时使用此目录;应当包含一个 main.yml 文件

3、示例1)、安装 http服务并启动,并设置开机启动http.retry http.yaml

Page 42: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

[root@ansible1 ~]# more http.yaml - name: web servers remote_user: root hosts: test tasks: - name: install http yum: name=httpd state=present - name: httpd service service: name=httpd enabled=yes state=started

执行过程:

这里 ok=3,就是安装 ok、开机启动 ok、启动 ok。2)、使用变量修改用户密码:[root@ansible1 ~]# echo 4567890 | openssl passwd -1 -stdin$1$1cjYSN8w$.BaXtcWET/13GD9L.6.ID/[root@ansible1 ~]# more passwd.yaml - name: changepasswd hosts: test vars: change_user: test passwd: $1$1cjYSN8w$.BaXtcWET/13GD9L.6.ID/ tasks: - name: changepasswod user: name={{ change_user }} password={{ passwd }} update_password=always

Page 43: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

3)、迭代创建多个用户

4)、当一个组当中存在 redhat 和 ubuntu 主机上,安装软件时命令不一样,这时可以用when首先需要使用 setup获取对方变量,如果使用的匹配 yum,那么再进行操作ansible all -m setup涉及变量:"ansible_pkg_mgr": "yum",涉及参数:

Page 44: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

when: ansible_pkg_mgr == "yum"yaml 文件如下:- name: install zsh remote_user: root hosts: a tasks: - name: install zsh yum: name=zsh state=present

when: ansible_pkg_mgr == "yum"

5)、role 安装 tomcat目录结构如下:[root@ansible1 roles]# tree[root@ansible1 ansible]# tree[root@ansible1 ansible]# tree.├── ansible.cfg├── hosts└── roles ├── http │   ├── default │   ├── files │   ├── handlers │   ├── meta │   ├── tasks │   ├── templates │   └── vars ├── mysql │   ├── default │   ├── files │   ├── handlers │   │   └── main.yaml │   ├── meta │   ├── tasks │   │   └── main.yml │   ├── templates │   └── vars │   └── main.yaml ├── php │   ├── default │   ├── files │   ├── handlers │   ├── meta │   ├── tasks

Page 45: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

│   ├── templates │   └── vars ├── site.retry ├── site.yml └── tomcat ├── defaults ├── files │   ├── apache-tomcat-7.0.69.tar.gz │   └── jdk-7u79-linux-x64.tar.gz ├── handlers │   └── main.yaml ├── meta │   └── test │   └── test.html ├── tasks │   └── main.yaml ├── templates │   └── test.yml └── vars

[root@ansible1 ansible]# more roles/site.yml - hosts: test remote_user: root roles:

- tomcat

[root@ansible1 ansible]# more roles/tomcat/handlers/main.yaml - name: stop tomcat service shell: "ps -ef |grep tomcat |grep -v grep |awk '{print $2}' |xargs kill -9"- name: start tomcat service shell: chdir=/home/app/tomcat/bin nohup ./startup.sh &

[root@ansible1 ansible]# more roles/tomcat/meta/test/test.html this is test

[root@ansible1 ansible]# more roles/tomcat/tasks/main.yaml- name: group group: name=app- name: user user: name=app group=app home=/home/app- name: 将 jdk压缩包 copy 到远程主机 jdk-7u79-linux-x64.tar.gz copy: src=jdk-7u79-linux-x64.tar.gz dest=/home/app- name: 解压 jdk压缩包 jdk-7u79-linux-x64.tar.gz shell: chdir=/home/app/ tar zxvf jdk-7u79-linux-x64.tar.gz

Page 46: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

- name: soft link file: src=/home/app/jdk1.7.0_79 dest=/usr/local/java state=link- name: java_profile config shell: /bin/echo {{ item }} >> /etc/profile && source /etc/profile with_items: - export JAVA_HOME=/usr/local/java - export JRE_HOME=/usr/local/java/jre - export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:\$JRE_HOME/lib:\$CLASSPATH - export PATH=\$JAVA_HOME/bin:\$PATH- name: 将 tomcat压缩包 copy 到远程主机 apache-tomcat-7.0.69.tar.gz copy: src=apache-tomcat-7.0.69.tar.gz dest=/home/app- name: 解压 tomcat压缩包 shell: chdir=/home/app tar zxvf apache-tomcat-7.0.69.tar.gz- name: 将 tomcat压缩包 重新命名为 tomcat shell: chdir=/home/app mv apache-tomcat-7.0.69 tomcat- name: 首次启动 tomcat shell: chdir=/home/app/tomcat/bin nohup ./startup.sh &- name: 将 test 工程 copy 到远程主机 copy: src=/etc/ansible/roles/tomcat/meta/test dest=/home/app/tomcat/webapps/ tags: - updateconf notify: - stop tomcat service - start tomcat service- name: 将某些模板文件 copy 到远程主机 template: src=test.yml dest=/home/app/tomcat/webapps/test/test.html

[root@ansible1 ansible]# more roles/tomcat/templates/test.yml 为空执行过程如下:(单独指定了其中的一台机器执行)[root@ansible1 roles]# ansible-playbook site.yml -l 192.168.67.138 -k SSH password: [DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and make sure become_method is 'sudo' (default).This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

PLAY [test] ********************************************************************

TASK [setup]

Page 47: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

*******************************************************************ok: [192.168.67.138]

TASK [tomcat : group] **********************************************************ok: [192.168.67.138]

TASK [tomcat : user] ***********************************************************ok: [192.168.67.138]

TASK [tomcat : 将 jdk 压 缩 包 copy 到 远 程 主 机 jdk-7u79-linux-x64.tar.gz] *********************ok: [192.168.67.138]

TASK [tomcat : 解 压 jdk 压 缩 包 jdk-7u79-linux-x64.tar.gz] *****************************changed: [192.168.67.138] [WARNING]: Consider using unarchive module rather than running tar

TASK [tomcat : soft link] ******************************************************ok: [192.168.67.138]

TASK [tomcat : java_profile config] ********************************************changed: [192.168.67.138] => (item=export JAVA_HOME=/usr/local/java)changed: [192.168.67.138] => (item=export JRE_HOME=/usr/local/java/jre)changed: [192.168.67.138] => (item=export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:\$JRE_HOME/lib:\$CLASSPATH)changed: [192.168.67.138] => (item=export PATH=\$JAVA_HOME/bin:\$PATH)

TASK [tomcat : 将 tomcat压缩包 copy 到远程主机 apache-tomcat-7.0.69.tar.gz] ****************ok: [192.168.67.138]

TASK [tomcat : 解压 tomcat压缩包] ****************************************************changed: [192.168.67.138]

TASK [tomcat : 将 tomcat 压 缩 包 重 新 命 名 为 tomcat] ****************************************changed: [192.168.67.138]

Page 48: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

TASK [tomcat : 首 次 启 动 tomcat] *****************************************************changed: [192.168.67.138]

TASK [tomcat : 将 test 工程 copy 到远程主机] *******************************************changed: [192.168.67.138]

TASK [tomcat : 将某些模板文件 copy 到远程主机] *********************************************changed: [192.168.67.138]

RUNNING HANDLER [tomcat : stop tomcat service] *********************************changed: [192.168.67.138]

RUNNING HANDLER [tomcat : start tomcat service] ********************************changed: [192.168.67.138]

PLAY RECAP *********************************************************************192.168.67.138 : ok=15 changed=9 unreachable=0 failed=0

页面测试访问如下:(roles/tomcat/templates/test.yml内容为空,所以访问页面为空)

现在新增一个页面[root@ansible1 test]# more /etc/ansible/roles/tomcat/meta/test/test1.html new新增一个页面不可能再重新安装 java 和 tomcat,这时就用到 tags 和 notify(调用/etc/ansible/roles/tomcat/handlers/里面的东西)执行情况如下:[root@ansible1 roles]# ansible-playbook site.yml -l 192.168.67.138 --tags=updateconf -k SSH password: [DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and make sure become_method is 'sudo' (default).This feature will

Page 49: €¦  · Web viewansible是新出现的自动化运维工具,基于Python研发。结合了众多老牌运维工具的优点实现了批量操作系统配置、批量程序的部署

be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

PLAY [test] ********************************************************************

TASK [setup] *******************************************************************ok: [192.168.67.138]

TASK [tomcat : 将 test 工程 copy 到远程主机] *******************************************changed: [192.168.67.138]

RUNNING HANDLER [tomcat : stop tomcat service] *********************************changed: [192.168.67.138]

RUNNING HANDLER [tomcat : start tomcat service] ********************************changed: [192.168.67.138]

PLAY RECAP *********************************************************************192.168.67.138 : ok=4 changed=3 unreachable=0 failed=0

可 以看出 只 执 行 了 将 test 工 程 copy 到 远 程 主 机 并重启了 tomcat, 没 有 将整个playbook 执行一遍。访问测试页面如下: