自动化运维 -- 02 Ansible
0参考资料
三度的ansible首页
http://www.cnblogs.com/sanduzxcvbnm/category/1036442.html
kkblog的ansible首页
http://www.cnblogs.com/Carr/tag/ansible/
ansible documentation <EN>
http://docs.ansible.com/ansible/latest/index.html
ansible中文权威指南
http://www.ansible.com.cn/docs/intro_configuration.html#environmental-configuration
python调用ansible api 2.0 运行playbook带callback返回(包含playbook)
http://www.cnblogs.com/qianchengprogram/p/6290913.html
1相关基础
1.1概念
Ansible是一个自动化管理IT资源的工具
1.2功能
系统环境配置
安装软件
持续集成、持续部署
热回滚
1.3优点
无客户端(基于SSH服务)
推送式
丰富的module
基于yaml的playbook
商业化支持(web功能、界面友好、稳定性)
1.4缺点
效率低、易挂起
由于SSH协议,单个机器的任务执行方式是串行的
并发效率低(网测500+效率低)
2安装
2.1环境准备
Python
Setuptools--相当于readhat的yum
2.2安装方法
2.2.1pip
安装pip
执行pip install ansible安装ansible
2.2.2源码安装
可使用自动安装脚本:https://github.com/yc913344706/Wheels
依赖包处理(yum部分)
sudo yum -y install xz wget gcc make gdbm-devel openssl-devel sqlite-devel zlib-devel bzip2-devel python-devel libyaml
依赖包处理(源码包部分)
按顺序安装:setuptools、pycrypto、PyYAML、MarkupSafe、Jinja2、pyasn1、pycparser、libffi-devel、cffi、six、PyNaCl、ecdsa、ipaddress、enum34、asn1crypto、idna、cryptography、bcrypt、paramiko、simplejson、ansible-devel、
解压源码
进入目录
运行source ./hacking/env-setup (需注意依赖包)
或者sudo python setup.py install(此种方法会自动将ansible加入到环境变量中)
注:如果ansible下载得是release版本的zip/tar.gz文件。则会报" The module ping was not found in configured module paths.
" 错误
需要再次下载下面这两个仓库,放在/lib/ansible/modules/目录下,再进行安装
https://github.com/ansible/ansible-modules-core
https://github.com/ansible/ansible-modules-extras
2.2.3系统源安装
centos
yum install ansible
ubuntu
apt-get install software-properties-common
apt-add-repository ppa:ansible/ansible
apt-get update
apt-get install ansible
3运行
由于ansible是无客户端+SSH服务运行的,所以运行非常简单,直接使用ansible命令就可以运行
4配置项
4.1配置文件优先级
export ANSIBLE_CONFIG
./ansible.cfg
~/.ansible.cfg
/etc/ansible/ansible.cfg
注:可以从github上获取到ansible.cfg
https://github.com/ansible/ansible/blob/devel/examples/ansible.cfg
# config file for ansible -- https://ansible.com/ # =============================================== # nearly all parameters can be overridden in ansible-playbook # or with command line flags. ansible will read ANSIBLE_CONFIG, # ansible.cfg in the current working directory, .ansible.cfg in # the home directory or /etc/ansible/ansible.cfg, whichever it # finds first # 默认配置项 [defaults] # some basic default values... #module_utils = /usr/share/my_module_utils/ #local_tmp = ~/.ansible/tmp #poll_interval = 15 #ask_sudo_pass = True #ansible客户端的执行用户有sudo权限,需要开启此功能 #ask_pass = True #控制遇到需要输入root密码的时候是否弹窗 # plays will gather facts by default, which contain information about # the remote system. # # smart - gather by default, but don't regather if already gathered # implicit - gather by default, turn off with gather_facts: False # explicit - do not gather by default, must say gather_facts: True #gathering = implicit # This only affects the gathering done by a play's gather_facts directive, # by default gathering retrieves all facts subsets # all - gather all subsets # network - gather min and network facts # hardware - gather hardware facts (longest facts to retrieve) # virtual - gather min and virtual facts # facter - import facts from facter # ohai - import facts from ohai # You can combine them using comma (ex: network,virtual) # You can negate them using ! (ex: !hardware,!facter,!ohai) # A minimal set of facts is always gathered. #gather_subset = all # 设置收集的内容,在ansible的收集数据影响到了系统性能时候设置 # some hardware related facts are collected # with a maximum timeout of 10 seconds. This # option lets you increase or decrease that # timeout to something more suitable for the # environment. # gather_timeout = 10 # default user to use for playbooks if user is not specified # (/usr/bin/ansible will use current user as default) # 客户机设置相关 #remote_user = root #remote_port = 22 #remote_tmp = ~/.ansible/tmp #sudo_user = root #使用sudo获取root权限的用户 # change this for alternative sudo implementations #sudo_exe = sudo #sudo命令的路径,默认/usr/bin # What flags to pass to sudo # WARNING: leaving out the defaults might create unexpected behaviours #sudo_flags = -H -S -n #sudo的参数 # 最大开辟的进程数,不宜过大,过大耗费性能高,过小并发性能低,一般为cpu核数*2 #forks = 5 # default module name for /usr/bin/ansible # 单独执行一条命令,前后没有什么关系,所以如果执行的shell有参数,变量等,需要将此改为shell #module_name = command # If set, configures the path to the Vault password file as an alternative to # specifying --vault-password-file on the command line. # 存放远程客户机密码的,可以是一个文件,也可以是一个脚本,如果是脚本,必须保证脚本可以执行并且密码可以在stdout上打印出来 #vault_password_file = /path/to/vault_password_file #pattern ?只在慕课网看到可以设置,后期待添加 #inventory = /etc/ansible/hosts # 存放可通信主机的目录 #library = /usr/share/my_modules/ # 存放Ansible搜索模块的默认路径 #transport = smart #module_lang = C #module_set_locale = False # additional paths to search for roles in, colon separated #roles_path = /etc/ansible/roles # uncomment this to disable SSH key host checking #host_key_checking = False # change the default callback, you can only have one 'stdout' type enabled at a time. #stdout_callback = skippy ## Ansible ships with some plugins that require whitelisting, ## this is done to avoid running all of a type by default. ## These setting lists those that you want enabled for your system. ## Custom plugins should not need this unless plugin author specifies it. # enable callback plugins, they can output to stdout but cannot be 'stdout' type. #callback_whitelist = timer, mail # Determine whether includes in tasks and handlers are "static" by # default. As of 2.0, includes are dynamic by default. Setting these # values to True will make includes behave more like they did in the # 1.x versions. #task_includes_static = False #handler_includes_static = False # Controls if a missing handler for a notification event is an error or a warning #error_on_missing_handler = True # SSH timeout #timeout = 10 # logging is off by default unless this path is defined # if so defined, consider logrotate #log_path = /var/log/ansible.log # use this shell for commands executed under sudo # you may need to change this to bin/bash in rare instances # if sudo is constrained #executable = /bin/sh # if inventory variables overlap, does the higher precedence one win # or are hash values merged together? The default is 'replace' but # this can also be set to 'merge'. #hash_behaviour = replace # by default, variables from roles will be visible in the global variable # scope. To prevent this, the following option can be enabled, and only # tasks and handlers within the role will see the variables there #private_role_vars = yes # list any Jinja2 extensions to enable here: #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n # if set, always use this private key file for authentication, same as # if passing --private-key to ansible or ansible-playbook #private_key_file = /path/to/file # format of string {{ ansible_managed }} available within Jinja2 # templates indicates to users editing templates files will be replaced. # replacing {file}, {host} and {uid} and strftime codes with proper values. #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} # {file}, {host}, {uid}, and the timestamp can all interfere with idempotence # in some situations so the default is a static string: #ansible_managed = Ansible managed # 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 # 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 packages or # other conditions that should be resolved if possible. # to disable these warnings, set the following value to False: #system_warnings = True # 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 # (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 # 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 #terminal_plugins = /usr/share/ansible/plugins/terminal #strategy_plugins = /usr/share/ansible/plugins/strategy # by default, ansible will use the 'linear' strategy but you may want to try # another one #strategy = free # 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 # 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 # 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 # 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 retry_files_save_path #retry_files_enabled = False #retry_files_save_path = ~/.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,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 # 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 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' # This controls the cutoff point (in bytes) on --diff for files # set to 0 for unlimited (RAM may suffer!). #max_diff_size = 1048576 # This controls how ansible handles multiple --tags and --skip-tags arguments # on the CLI. If this is True then multiple arguments are merged together. If # it is False, then the last specified argument is used and the others are ignored. # This option will be removed in 2.8. #merge_multiple_cli_flags = True # Controls showing custom stats at the end, off by default #show_custom_stats = True # Controls which files to ignore when using a directory as inventory with # possibly multiple sources (both static and dynamic) #inventory_ignore_extensions = ~, .orig, .bak, .ini, .cfg, .retry, .pyc, .pyo # This family of modules use an alternative execution path optimized for network appliances # only update this setting if you know how this works, otherwise it can break module execution #network_group_modules=eos, nxos, ios, iosxr, junos, vyos # When enabled, this option allows lookups (via variables like {{lookup('foo')}} or when used as # a loop with `with_foo`) to return data that is not marked "unsafe". This means the data may contain # jinja2 templating language which will be run through the templating engine. # ENABLING THIS COULD BE A SECURITY RISK #allow_unsafe_lookups = False # set default errors for all plays #any_errors_fatal = False [inventory] # enable inventory plugins, default: 'host_list', 'script', 'yaml', 'ini' #enable_plugins = host_list, virtualbox, yaml, constructed # ignore these extensions when parsing a directory as inventory source #ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~, .orig, .ini, .cfg, .retry # ignore files matching these patterns when parsing a directory as inventory source #ignore_patterns= # If 'true' unparsed inventory sources become fatal errors, they are warnings otherwise. #unparsed_is_failed=False # 执行命令的用户权限设置 [privilege_escalation] #become=True #become_method=sudo #become_user=root #become_ask_pass=False # 优化后的ssh服务 [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 # paramiko will default to looking for SSH keys initially when trying to # authenticate to remote devices. This is a problem for some network devices # that close the connection after a key failure. Uncomment this line to # disable the Paramiko look for keys function #look_for_keys = False # When using persistent connections with Paramiko, the connection runs in a # background process. If the host doesn't already have a valid SSH key, by # default Ansible will prompt to add the host key. This will cause connections # running in background processes to fail. Uncomment this line to have # Paramiko automatically add host keys. #host_key_auto_add = True # ssh连接设置 [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 # The base directory for the ControlPath sockets. # This is the "%(directory)s" in the control_path option # # Example: # control_path_dir = /tmp/.ansible/cp #control_path_dir = ~/.ansible/cp # The path to use for the ControlPath sockets. This defaults to a hashed string of the hostname, # port and username (empty string in the config). The hash mitigates a common problem users # found with long hostames and the conventional %(directory)s/ansible-ssh-%%h-%%p-%%r format. # In those cases, a "too long for Unix domain socket" ssh error would occur. # # Example: # control_path = %(directory)s/%%h-%%r #control_path = # 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 # Control the mechanism for transferring files (old) # * smart = try sftp and then try scp [default] # * True = use scp only # * False = use sftp only #scp_if_ssh = smart # Control the mechanism for transferring files (new) # If set, this will override the scp_if_ssh option # * sftp = use sftp to transfer files # * scp = use scp to transfer files # * piped = use 'dd' over SSH to transfer files # * smart = try sftp, scp, and piped, in that order [default] #transfer_method = 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 [persistent_connection] # Configures the persistent connection timeout value in seconds. This value is # how long the persistent connection will remain idle before it is destroyed. # If the connection doesn't receive a request before the timeout value # expires, the connection is shutdown. The default value is 30 seconds. #connect_timeout = 30 # Configures the persistent connection retry timeout. This value configures the # the retry timeout that ansible-connection will wait to connect # to the local domain socket. This value must be larger than the # ssh timeout (timeout) and less than persistent connection idle timeout (connect_timeout). # The default value is 15 seconds. #connect_retry_timeout = 15 # The command timeout value defines the amount of time to wait for a command # or RPC call before timing out. The value for the command timeout must # be less than the value of the persistent connection idle timeout (connect_timeout) # The default value is 10 second. #command_timeout = 10 [accelerate] #accelerate_port = 5099 #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,9p # Set this to yes to allow libvirt_lxc connections to work without SELinux. #libvirt_lxc_noseclabel = yes [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 [diff] # Always print diff when running ( same as always running with -D/--diff ) # always = no # Set how many context lines to show in diff # context = 3
4.2配置文件详解
参考
ansible中文权威指南
http://www.ansible.com.cn/docs/intro_configuration.html#environmental-configuration
Ansible学习记录三:配置文件
http://www.cnblogs.com/LuisYang/p/5960660.html
5添加第一台机器
5.0参考
记录一则Linux SSH的互信配置过程
http://www.cnblogs.com/jyzhao/p/3781072.html
linux生成公钥私钥,用户通过公钥访问服务器
http://www.cnblogs.com/tc520/p/7107362.html
5.1编辑/etc/ansible/hosts
没有新建即可,只要与ansible.cfg中定义的inventory所定义的值相对应即可
[yc@centos-7 .ssh]$ cat /etc/ansible/hosts
[localhost]
yc ansible_ssh_host=localhost
5.2添加本机的public ssh key添加到目标机器的authorized_keys
# 生成不对称加密公私钥
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
# 使本机可以访问目标机器
ssh-copy-id -i ~/.ssh/id_rsa.pub 目标用户@目标机器IP
5.3.添加本机的私钥到ansible
经实测,这一步其实可以省略
5.4.运行ansible all -m ping测试是否添加成功
成功后,会有"ping":"pong"字样
# 所有 [yc@centos-7 .ssh]$ ansible all -m ping yc | SUCCESS => { "changed": false, "failed": false, "ping": "pong" } # 组名 [yc@centos-7 .ssh]$ ansible localhost -m ping yc | SUCCESS => { "changed": false, "failed": false, "ping": "pong" } # 别名 [yc@centos-7 .ssh]$ ansible yc -m ping yc | SUCCESS => { "changed": false, "failed": false, "ping": "pong" }
6.ansible命令格式
6.0参考
ansible命令详解
http://www.cnblogs.com/sanduzxcvbnm/p/7200265.html
Ansible Inventory篇--类正则表达式
http://www.cnblogs.com/yanjingnan/p/7242102.html
6.1格式
<ansible命令主体> <host-pattern> [options]
6.2参数
6.2.1ansible命令主体
ansible 主要用于ad-hoc命令
ansible-config
ansible-connection
ansible-console
ansible-doc 显示ansible模块文档
ansible-galaxy 用于下载第三方扩展模块
ansible-inventory
ansible-playbook
ansible-pull
ansible-vault
6.2.2host-pattern -- 被操作目标机器的类正则表达式
作用
用来对ansible要操作的机器进行筛选
使用方式
直接使用IP或者域名
all或者* 所有的机器。如192.168.0.*
: 左右并集。可以是某个固定IP或者组
:! 在左边的组,不在右边的组。如webservers:!nginx
:& 在左边的组,并且在右边的组。如webservers:&nginx
重要
从左到右依次匹配。如:webservers:nginx:&vim:!python:!mysql
6.2.3options -- 参数
常用参数如下
-a MODULE_ARGS 模块的参数,如果执行默认COMMAND的模块,即是命令参数,如: “date”,"pwd"等等
-C -D两个一起使用,检查host规则文件的修改
-l 进一步限制所选主机/组模式 -l 192.168.91.135 只对这个ip执行
--list-hosts 显示所有匹配规则的主机数
-m 指定要执行的模块的名字,默认command
-M 指定要执行的模块的路径,可以通过查找ping.py的位置,来找到本机上ansible的module库的所在路径
--syntax-check 语法检查
-v 显示详细的日志
-B xx [-P xx] B--运行超时时间,P--每隔多少秒获取一次状态
-u username 以指定用户在远程机器上执行命令
7模块
7.0参考
模块总体认知
http://www.cnblogs.com/iois/p/6216936.html
模块详解
http://www.cnblogs.com/Carr/p/7447091.html
7.1相关命令
ansible-doc -l 列出所有可用模块
ansible-doc -s shell 列出shell模块的playbook代码
7.2常用模块
command--使用ansible自带模块执行命令,如果要用> < | & ``,需使用shell模块
shell--使用linux的shell模块执行命令,但是复杂的命令建议写成脚本,copy到远程执行
copy--复制本地文件至远程服务器
file--创建文件夹、文件、连接文件、更改属性、组、删除文件、文件夹等
fetch--从远程服务器拉取文件至本机,只能fetch文件,如果是文件夹,先tar/zip,后拉取
cron--管理cron计划任务
yum--使用yum安装软件
script--发送脚本到远程服务器,并执行
git--git相关操作
service--系统服务相关,启动,关闭,重启等
setup--系统环境相关
async_status--获取ansible执行状态(适用于ansible可视化管理)
8inventory-分组
8.0参考
Ansible Inventory篇--host中的参数列表
http://www.cnblogs.com/yanjingnan/p/7242102.html
ansible使用2-inventory & dynamic inventory
http://www.cnblogs.com/liujitao79/p/4195143.html
8.1概念
可以同时操作属于一个组的多台主机,组和主机的关系通过inventory的配置文件/etc/ansible/hosts来进行配置
8.2常规配置方法
直接写IP/域名;
非默认ssh端口;
主机别名&多参数配置;
配置大量主机;
自定义主机变量;
自定义主机组变量;
...
8.3组的分文件管理&分文件夹管理
/etc/ansible/group_vars
此文件夹下可以放文件夹,可以放文件。
放文件时,文件名就是组名
放文件夹时,文件夹名就是组名
此处有疑问:文件夹下的文件中的机器应该如何寻找?
/etc/ansible/host_vars
此文件夹下放置文件中存放的是不进行分组的机器
9命令执行方式
9.1基础执行方式之Ad-Hoc
适用场景
适用于执行一些来去比较快的,不需要将命令特别保存下来的命令
举例
将atlanta组内的所有机器重启,每次并行重启10个
ansible atlanta -a "/sbin/reboot" -f 10
使用指定用户执行shell命令
ansible atlanta -a "/usr/bin/foo" -u username
使用sudo
ansible atlanta -a "/usr/bin/foo" -u username --sudo [--ask-sudo-pass]
创建文件夹
ansible webservers -m file -a "path=/path/des_dir mode=755 owner=yc group=yc state=directory "
9.2基础执行方式之playbook
概念
是ansible官方提供的一个简单的配置管理系统与多机部署系统的基础。
用途
playbook可用于声明配置,更强大的地方在于,playbook中可以编排有序的执行过程,甚至于做到多组机器间,来回有序地执行指定的步骤,并且可以同步或异步地发起任务
9.3高级执行方式之ansible api
参考
ansible documentation <en>
http://docs.ansible.com/ansible/latest/index.html
ansible中文权威指南
http://www.ansible.com.cn/docs/intro_configuration.html#environmental-configuration
python调用ansible api 2.0 运行playbook带callback返回(带playbook)
http://www.cnblogs.com/qianchengprogram/p/6290913.html
ansible api提供了哪些功能
开发动态的inventory数据源
更好地控制playbook等功能的运行
脚本调用ansible模块
举例
# ansible 2.0之前的调用方法 # 1.引入ansible runner库 # 2.初始化runner对象,传入相关参数 # 3.运行runner对象的run函数 # 注:如果主机不通或者失败,结果将会输出到 dark部分,否则结果输出到 contacted部分 #!/usr/bin/env python import ansible.runner import json runner = ansible.runner.Runner( module_name='ping', # 模块名称 module_args='', # 模块参数 pattern='35_db', # 主机组 forks=10 # 并发量 ) datastruncture = runner.run() data = json.dumps(datastructure,indent=4) ####################分割线##################### # ansible 2.0之后的调用方法==>通过回调的方法去实现API接口 # 注:print ansible.__version__,即可得到ansible的版本 # 1.定义一个结果对象 # 2.初始化ansible节点对象 # 3.初始化结果对象 # 4.创建一个任务 # 5.运行ansible节点 #!/usr/bin/env python import json from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory import Inventory from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.plugins.callback import CallbackBase class ResultCallback(CallbackBase): """A sample callback plugin used for performing an action as results come in If you want to collect all results into a single object for processing at the end of the execution, look into utilizing the ``json`` callback plugin or writing your own custom callback plugin """ def v2_runner_on_ok(self, result, **kwargs): """Print a json representation of the result This method could store the result in an instance attribute for retrieval later """ host = result._host print(json.dumps({host.name: result._result}, indent=4)) # 参数选项 Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff']) # initialize needed objects # 变量管理器 variable_manager = VariableManager(loader=loader, inventory=inventory) loader = DataLoader() # 定义ansible连接参数 options = Options(connection='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False,diff=False) passwords = dict(vault_pass='secret') # Instantiate our ResultCallback for handling results as they come in results_callback = ResultCallback() # create inventory and pass to var manager inventory = Inventory(loader=loader, variable_manager=variable_manager,host_list='/etc/ansible/hosts') variable_manager.set_inventory(inventory) # create play with tasks play_source = dict( hosts = 'localhost', name = "Ansible Play", gather_facts = 'no', tasks = [ dict(action=dict(module='shell', args='ls'), register='shell_out'), dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}'))) ] ) play = Play().load(play_source, variable_manager=variable_manager, loader=loader) # actually run it tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords, ##登录ansible控制机器的密码,如果通过公钥方式连接,此passwords可以传入个错误的,但不能不传 stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup()
9.4高级执行方式之自定义module
用途
自定义module脚本,并将其添加到ansible的module库中,通过ansible调用该模块,来实现自己想要的结果
注意
module脚本为.py文件
module脚本结尾必须打印json格式的输出
举例
简单格式
import datatime import json date = str(datetime.datetime.now()) print json.dumps({ "time":date })
可接受参数的module文件
#!/usr/bin/python import datetime import sys import json import os import shlex args_file = sys.argv[1] args_data = file(args_file).read() arguments = shlex.split(args_data) for arg in arguments: if "=" in arg: (key,value) = arg.split("=") if key == "time": # date -s STRING ==> set time described by STRING rc = os.system("date -s \"%s\"" % value) if rc != 0: print json.dumps({ "failed" : True, "msg" : "failed setting the time" }) sys.exit(1) date = str(datatime.datetime.now()) print json.dumps({ "time" : date, "changed": True }) sys.exit(0) date = str(datatime.datetime.now()) print json.dumps({ "time" : date })
使用方法
将自己编写的module文件加入到ansible中
将.py文件放到ansible的module库所在路径下
可以通过查找ping.py的位置,来找到本机上ansible的module库的所在路径
更改ansible.cfg的默认模块搜索路径
library = xxx
运行自己的module
ansible all -m timer
ansible all -m timer -a "time=\'March 14 12:23\""
9.5高级执行方式之自定义plugin
用途
主要用于监控方面,目前暂未有自定义plugin功能,现有的方法都是继承于ansible自带的插件,然后重写方法来进行实现。如上面的ansible_api。
常见插件
Callback Plugins
Connection Plugins
Lookup Plugins
Vars Plugins
Filter Plugins
Test Plugins
Distributing Plugins