三度的ansible首頁html
http://www.cnblogs.com/sanduzxcvbnm/category/1036442.htmlpython
kkblog的ansible首頁mysql
http://www.cnblogs.com/Carr/tag/ansible/linux
ansible documentation <EN>ios
http://docs.ansible.com/ansible/latest/index.htmlnginx
ansible中文權威指南git
http://www.ansible.com.cn/docs/intro_configuration.html#environmental-configurationgithub
python調用ansible api 2.0 運行playbook帶callback返回(包含playbook)web
http://www.cnblogs.com/qianchengprogram/p/6290913.html正則表達式
Ansible是一個自動化管理IT資源的工具
系統環境配置
安裝軟件
持續集成、持續部署
熱回滾
無客戶端(基於SSH服務)
推送式
豐富的module
基於yaml的playbook
商業化支持(web功能、界面友好、穩定性)
效率低、易掛起
因爲SSH協議,單個機器的任務執行方式是串行的
併發效率低(網測500+效率低)
Python
Setuptools--至關於readhat的yum
安裝pip
執行pip install ansible安裝ansible
可以使用自動安裝腳本: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
centos
yum install ansible
ubuntu
apt-get install software-properties-common
apt-add-repository ppa:ansible/ansible
apt-get update
apt-get install ansible
因爲ansible是無客戶端+SSH服務運行的,因此運行很是簡單,直接使用ansible命令就能夠運行
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
參考
ansible中文權威指南
http://www.ansible.com.cn/docs/intro_configuration.html#environmental-configuration
Ansible學習記錄三:配置文件
http://www.cnblogs.com/LuisYang/p/5960660.html
記錄一則Linux SSH的互信配置過程
http://www.cnblogs.com/jyzhao/p/3781072.html
linux生成公鑰私鑰,用戶經過公鑰訪問服務器
http://www.cnblogs.com/tc520/p/7107362.html
沒有新建便可,只要與ansible.cfg中定義的inventory所定義的值相對應便可
[yc@centos-7 .ssh]$ cat /etc/ansible/hosts
[localhost]
yc ansible_ssh_host=localhost
# 生成不對稱加密公私鑰
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
# 使本機能夠訪問目標機器
ssh-copy-id -i ~/.ssh/id_rsa.pub 目標用戶@目標機器IP
經實測,這一步其實能夠省略
成功後,會有"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" }
ansible命令詳解
http://www.cnblogs.com/sanduzxcvbnm/p/7200265.html
Ansible Inventory篇--類正則表達式
http://www.cnblogs.com/yanjingnan/p/7242102.html
<ansible命令主體> <host-pattern> [options]
ansible 主要用於ad-hoc命令
ansible-config
ansible-connection
ansible-console
ansible-doc 顯示ansible模塊文檔
ansible-galaxy 用於下載第三方擴展模塊
ansible-inventory
ansible-playbook
ansible-pull
ansible-vault
做用
用來對ansible要操做的機器進行篩選
使用方式
直接使用IP或者域名
all或者* 全部的機器。如192.168.0.*
: 左右並集。能夠是某個固定IP或者組
:! 在左邊的組,不在右邊的組。如webservers:!nginx
:& 在左邊的組,而且在右邊的組。如webservers:&nginx
重要
從左到右依次匹配。如:webservers:nginx:&vim:!python:!mysql
經常使用參數以下
-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 以指定用戶在遠程機器上執行命令
模塊整體認知
http://www.cnblogs.com/iois/p/6216936.html
模塊詳解
http://www.cnblogs.com/Carr/p/7447091.html
ansible-doc -l 列出全部可用模塊
ansible-doc -s shell 列出shell模塊的playbook代碼
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可視化管理)
Ansible Inventory篇--host中的參數列表
http://www.cnblogs.com/yanjingnan/p/7242102.html
ansible使用2-inventory & dynamic inventory
http://www.cnblogs.com/liujitao79/p/4195143.html
能夠同時操做屬於一個組的多臺主機,組和主機的關係經過inventory的配置文件/etc/ansible/hosts來進行配置
直接寫IP/域名;
非默認ssh端口;
主機別名&多參數配置;
配置大量主機;
自定義主機變量;
自定義主機組變量;
...
/etc/ansible/group_vars
此文件夾下能夠放文件夾,能夠放文件。
放文件時,文件名就是組名
放文件夾時,文件夾名就是組名
此處有疑問:文件夾下的文件中的機器應該如何尋找?
/etc/ansible/host_vars
此文件夾下放置文件中存放的是不進行分組的機器
適用場景
適用於執行一些來去比較快的,不須要將命令特別保存下來的命令
舉例
將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 "
概念
是ansible官方提供的一個簡單的配置管理系統與多機部署系統的基礎。
用途
playbook可用於聲明配置,更強大的地方在於,playbook中能夠編排有序的執行過程,甚至於作到多組機器間,來回有序地執行指定的步驟,而且能夠同步或異步地發起任務
參考
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()
用途
自定義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\""
用途
主要用於監控方面,目前暫未有自定義plugin功能,現有的方法都是繼承於ansible自帶的插件,而後重寫方法來進行實現。如上面的ansible_api。
常見插件
Callback Plugins
Connection Plugins
Lookup Plugins
Vars Plugins
Filter Plugins
Test Plugins
Distributing Plugins