Ansible应用总结【第二篇】: Ansible部署及配置讲解
Ansible部署
安装要求:
控制端:Python 2.6 or 2.7 (控制端不支持Windows主机)
被管理端:Python 2.4及以上,如果Python版本低于2.5 还需要安装python-simplejson模块,如果被管理端启用了SELinux,还需要安装libselinux-python模块
1、yum/apt/pip安装
# pip 方式 easy_install pip pip install paramiko PyYAML Jinja2 httplib2 six git clone git://github.com/ansible/ansible.git --recursive cd ./ansible source ./hacking/env-setup
# yum 方式(需配置EPEL源) yum install python-devel python-paramiko python-yaml python-jinja2 git -y yum install ansible -y
2、源码安装
# 使用源码打包rpm包,安装使用 # 先安装依赖 yum install gcc gcc-c++ automake autoconf -y yum install asciidoc.noarch -y # 打包并安装 git clone git://github.com/ansible/ansible.git cd ./ansible$ make rpm rpm -Uvh ~/rpmbuild/ansible-*.noarch.rpm
Ansible配置讲解
1、常见配置目录结构讲解
[root@ansible ~]# rpm -ql ansible /etc/ansible # 所有配置文件存放目录配置文件位于/etc/ansible 官方建议将该目录使用git/svn进行版本控制便于跟踪和修改 /etc/ansible/ansible.cfg # 主配置文件 /etc/ansible/hosts # 主机定义文件 /etc/ansible/roles /usr/bin/ansible # 实现批量部署的命令 /usr/bin/ansible-doc # 模块文档查看器 /usr/bin/ansible-galaxy # 可以把他理解成ansible的pip,可以从galaxy.ansible.com下载官方收录的playbooks /usr/bin/ansible-playbook # playbook配置管理工具 /usr/bin/ansible-pull # 支持直接从git下载playbook执行,需要遵循其规定的目录格式,用处不是特别大,可以不关注 /usr/bin/ansible-vault # 如果你的配置文件中含有敏感信息,你可能并不希望他能被人看到,vault可以帮你加密/解密这个配置文件主机或者组变量 /etc/ansible/group_vars/all # group_vars目录用于存放group变量,all文件对所有组有效 /etc/ansible/group_vars/windows # 文件windows要和hosts里面定义的组名一样,表示对windows组下的所有主机有效 /etc/ansible/host_vars/foosball # 文件foosball要和hosts里面定义的主机名一样,表示只对foosball主机有效 /etc/ansible/host_vars/all # host_vars目录用于存放hosts变量,all文件对所有主机有效
2、主配置讲解
[root@ansible ~]# cat /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 # 定义主机清单文件所在位置 #library = /usr/share/my_modules/ #remote_tmp = $HOME/.ansible/tmp # 被管理端临时目录位置 #forks = 5 # 启动子进程数量 #poll_interval = 15 #sudo_user = root # 如果以普通用户登录进行sudo那么sudo的默认账户是root #ask_sudo_pass = True #ask_pass = True #transport = smart #remote_port = 22 # 远程主机SSH端口 #module_lang = C # 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 # 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 #stdout_callback = skippy # enable additional callbacks #callback_whitelist = timer, mail # change this for alternative sudo implementations #sudo_exe = sudo # What flags to pass to sudo # WARNING: leaving out the defaults might create unexpected behaviours #sudo_flags = -H -S -n # SSH timeout #timeout = 10 # SSH连接超时时间 # default user to use for playbooks if user is not specified # (/usr/bin/ansible will use current user as default) #remote_user = root # 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 # 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} # This short version is better used in templates as it won't flag the file as changed every run. #ansible_managed = Ansible managed: {file} on {host} # 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 (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 #callback_plugins = /usr/share/ansible/plugins/callback #connection_plugins = /usr/share/ansible/plugins/connection #lookup_plugins = /usr/share/ansible/plugins/lookup #vars_plugins = /usr/share/ansible/plugins/vars #filter_plugins = /usr/share/ansible/plugins/filter #test_plugins = /usr/share/ansible/plugins/test # 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 # 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 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 [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 #ssh_args = -o ControlMaster=auto -o ControlPersist=60s # The path to use for the ControlPath sockets. This defaults to # "%(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 # if True, make ansible use scp if the connection type is ssh # (default is sftp) #scp_if_ssh = True # 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 [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
[root@ansible ~]# cat /etc/ansible/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 ## [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
3、Ansible命令讲解
[root@ansible ~]# ansible --help Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments # 模块参数 --ask-become-pass ask for privilege escalation password -k, --ask-pass ask for SSH password # SSH连接的用户名,默认root,ansible.cfg可以配置 --ask-su-pass ask for su password (deprecated, use become) -K, --ask-sudo-pass ask for sudo password (deprecated, use become) --ask-vault-pass ask for vault password -B SECONDS, --background=SECONDS run asynchronously, failing after X seconds (default=N/A) -b, --become run operations with become (nopasswd implied) --become-method=BECOME_METHOD privilege escalation method to use (default=sudo),valid choices: [ sudo | su | pbrun | pfexec | runas ] --become-user=BECOME_USER run operations as this user (default=None) -C, --check don't make any changes; instead, try to predict some of the changes that may occur # 只是测试一下会改变什么内容,不会真正去执行 -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) # 连接类型 -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON -f FORKS, --forks=FORKS specify number of parallel processes to use(default=5) # 多少个进程并发进程处理,默认为5个 -h, --help show this help message and exit # 显示本帮助信息并退出 -i INVENTORY, --inventory-file=INVENTORY specify inventory host file(default=/etc/ansible/hosts) # 指定主机列表清单的文件路径 -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern # 指定一个pattern,对已经匹配的主机再过滤一次 --list-hosts outputs a list of matching hosts; does not execute anything else -m MODULE_NAME, --module-name=MODULE_NAME module name to execute (default=command) # 要执行的模块,默认为command -M MODULE_PATH, --module-path=MODULE_PATH specify path(s) to module library (default=None) -o, --one-line condense output -P POLL_INTERVAL, --poll=POLL_INTERVAL set the poll interval if using -B (default=15) --private-key=PRIVATE_KEY_FILE use this file to authenticate the connection # 私钥路径 -S, --su run operations with su (deprecated, use become) # su到某个用户执行命令 -R SU_USER, --su-user=SU_USER run operations with su as this user (default=root) (deprecated, use become) -s, --sudo run operations with sudo (nopasswd) (deprecated, use become) # 使用sudo -U SUDO_USER, --sudo-user=SUDO_USER desired sudo user (default=root) (deprecated, use become) -T TIMEOUT, --timeout=TIMEOUT override the SSH timeout in seconds (default=10) # SSH连接超时时间,默认10秒 -t TREE, --tree=TREE log output to this directory # 日志输出到该目录,日志文件名会以主机命名 -u REMOTE_USER, --user=REMOTE_USER connect as this user (default=root) --vault-password-file=VAULT_PASSWORD_FILE vault password file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) # 显示模式,方便调试问题 --version show program's version number and exit # 输出程序版本号并退出
出处:http://www.cnblogs.com/madsnotes/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

浙公网安备 33010602011771号