本章主要講的是 Ansible 安裝與基本配置,主要包含如下內容:html
從 GitHub 獲取 Ansible,準備控制主機,查看被管節點。python
使用的操做系統爲 Centos 7.0,自帶 Python 2.7.5。linux
角色 | 主機名 | IP 地址 | 組名 | CPU | Web 根目錄 |
---|---|---|---|---|---|
被管節點 | web1 | 192.168.46.128 | webservers | 2 | /website |
被管節點 | web2 | 192.168.46.129 | webservers | 2 | /website |
控制節點 | ansiblecontrol | 192.168.46.130 | --- | --- | --- |
永久性的修改主機名稱
hostnamectl set-hostname web1
ios
Ansible 的安裝方式分爲直接用源碼安裝以及用包管理工具安裝。git
從 GitHub 源碼庫安裝方式github
提取 Ansible 源代碼web
git clone https://github.com/ansible/ansible.git -- recursive cd ./ansible # 減小告警/錯誤信息輸出,可在安裝時加上 -q 參數 source ./hacking/env-setup -q
若沒有安裝 pip,安裝對應 Python 版本的 pipredis
sudo easy_install pip
安裝 Ansible 控制主機須要的 Python 模塊shell
sudo pip install paramiko PyYAML Jinja2 httplib2 six
當更新 Ansible 版本時,要更新 git 源碼樹以及 git 中指向 Ansible 自身的模塊(稱爲 submodules)json
git pull --rebase git submodule update --init --recursive
運行 env-setup 腳本(默認資源清單 inventory 文件是 /etc/ansible/hosts)
.. code-block:: bash echo "127.0.0.1" > ~/ansible_hosts export ANSIBLE_HOSTS=~/ansible_hosts
經過 GitHub 倉庫安裝的,須要把倉庫中 examples 目錄下的 ansible.cfg 複製到 /etc/ansible 目錄下
pip安裝方式
#安裝 pip sudo easy_install pip #經過 pip 命令安裝 Ansible sudo pip install ansible
經過 pip 安裝的,沒有自動生成的配置文件,須要本身新建 /etc/ansible/ansible.cfg
配置文件優先級:
[defaults] #inventory = /etc/ansible/hosts #inventory文件路徑 #library = /usr/share/my_modules/ #模塊文件路徑 #module_utils = /usr/share/my_module_utils/ #自定義模塊工具存放目錄 #remote_tmp = ~/.ansible/tmp #臨時文件遠程主機存放目錄 #local_tmp = ~/.ansible/tmp #臨時文件本地存放目錄 #plugin_filters_cfg = /etc/ansible/plugin_filters.yml #forks = 5 #默認開啓的進程數 #poll_interval = 15 #默認輪詢時間間隔 #sudo_user = root #默認sudo用戶 #ask_sudo_pass = True #是否須要sudo密碼 #ask_pass = True #是否須要密碼 #transport = smart 通訊機制,若是本地系統支持 ControlPersist技術的話,將會使用(基於OpenSSH)‘ssh’,若是不支持將使用‘paramiko’,其餘傳輸選項‘local’,‘chroot’,’jail’等等 #remote_port = 22 #鏈接被管節點的管理端口 #module_lang = C #模塊運行的語言環境 #module_set_locale = False #gathering = implicit #facts信息收集開關,implicit(默認不收集) #gather_subset = all #facts 的收集範圍 # gather_timeout = 10 #收集超時間隔 # Ansible facts are available inside the ansible_facts.* dictionary # namespace. This setting maintains the behaviour which was the default prior # to 2.5, duplicating these variables into the main namespace, each with a # prefix of 'ansible_'. # This variable is set to True by default for backwards compatibility. It # will be changed to a default of 'False' in a future release. # ansible_facts. # inject_facts_as_vars = True #roles_path = /etc/ansible/roles #role存放路徑 #host_key_checking = False #是否檢查SSH主機的密鑰 # change the default callback, you can only have one 'stdout' type enabled at a time. #stdout_callback = skippy # 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 #sudo_exe = sudo #ansible sudo執行命令 #sudo_flags = -H -S -n #ansible sudo執行參數 #timeout = 10 #ansible SSH鏈接的超時間隔/秒 #remote_user = root #ansible 遠程認證用戶 #log_path = /var/log/ansible.log #指定存儲日誌的文件 #module_name = command #ansible 默認執行模塊 #executable = /bin/sh #ansible 命令執行 shell # 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 #ansible 主機變量重複處理方式 # 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 #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n #Jinja2 擴展列表 #private_key_file = /path/to/file #ansible ssh 私鑰文件 # 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 #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} #在 jinja2 中格式化 ansible_managed 變量 #ansible_managed = Ansible managed #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 #error_on_undefined_vars = False #開啓錯誤,或者沒有定義的變量 #system_warnings = True #開啓第三方包系統警告 #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 #ansible action 插件路徑 #become_plugins = /usr/share/ansible/plugins/become #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 #bin_ansible_callbacks = False #開啓 ansible 命令加載 callback 插件 #nocows = 1 #是否開啓 ansiblenocows 圖形 # 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 #nocolor = 1 #是否開啓 ansible 顏色輸出 # 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 #This option tells Ansible where to cache facts. The value is plugin dependent. #For the jsonfile plugin, it should be a path to a local directory. #For the redis plugin, the value is a host:port:database triplet: fact_caching_connection = localhost:6379:0 #fact_caching_connection=/tmp # retry files # When a playbook fails a .retry file can be created that will be placed in ~/ # You can enable this feature by setting retry_files_enabled to True # 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' #max_diff_size = 1048576 #diff文件的大小限制/字節 # 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', 'auto', 'yaml', 'ini', 'toml' #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 模式 #become_method=sudo #定義 become 方式 #become_user=root #定義 become 用戶 #become_ask_pass=False #是否認義 become 提示密碼 [paramiko_connection] #record_host_keys=False #是否記錄主機 key #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_connection] #SSH 鏈接配置 #ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s #ansib ssh參數,ControlMaster用於設置是否啓用 SSH的Multiplexing,關閉則寫no,ControlPersist爲SSH session保持的時間 # control_path_dir = /tmp/.ansible/cp #ansible ssh 長鏈接控制文件 #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 hostnames 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 = #pipelining = False #是否開啓 pipelining 模式 #scp_if_ssh = smart #是否開啓scp模式推送腳本,smart(先嚐試sftp推送,再嘗試scp推送) # 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 # The -tt argument is passed to ssh when pipelining is not enabled because sudo # requires a tty by default. #usetty = True #retries = 3 #重試與主機SSH鏈接的次數 [persistent_connection] #持久鏈接配置 #connect_timeout = 30 #持久鏈接超時間隔 # 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 30 second. #command_timeout = 30 [accelerate] #accelerate_port = 5099 #accelerate 遠程監聽端口 #accelerate_timeout = 30 #accelerate 模式,命令執行超時時間/秒 #accelerate_connect_timeout = 5.0 #accelerate 模式,鏈接超時時間/秒 # 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] #上下文配置 #special_context_filesystems=nfs,vboxsf,fuse,ramfs,9p,vfat #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 = no #是否一直打印diff # context = 3 #diff中顯示的上下文行數
爲避免 Ansible 下發指令時須要輸入目標主機密碼,經過證書籤名達到 SSH 無密碼訪問。使用 ssh-keygen 和 ssh-copy-id 來實現快速證書的生成及公鑰的下發。
在控制主機上建立密鑰,執行ssh-keygen -t rsa
,將在 /root/.ssh/ 下生成密鑰,其中 id_rsa 爲私鑰, id_rsa.pub 爲公鑰。
#生成密鑰 ssh-keygen -t rsa
下發密鑰就是控制主機將公鑰 is_rsa.pub 下發到被管節點上用戶下的 .ssh 目錄,並重命名爲 authorized_keys,且權限值爲400。
#下發公鑰到 web1(192.168.46.128) ssh-copy-id -i id_rsa root@192.168.46.128 #ssh鏈接驗證 ssh root@192.168.46.128 #退出 exit
修改主機與組配置 /etc/ansible/hosts ,添加兩臺主機的ip地址,同時定義一個 webservers 組包含這兩個地址
192.168.46.128 192.168.46.129 [webservers] 192.168.46.128 192.168.46.129
用 ping 模塊對單臺主機進行 ping 操做
ansible 192.168.46.128 -m ping
結果以下
192.168.46.128 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" }
對 webservers 組進行 ping 操做
ansible webservers -m ping
在命令後加 -v 或 -vvv 可獲得詳細的輸出結果
結果以下
192.168.46.128 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } 192.168.46.129 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" }
在 home 目錄下建立資源清單文件 inventory.cfg
vim inventory.cfg
內容以下:
[webservers] 192.168.46.128 192.168.46.129
用 Ansible 的 shell 模塊 在 webservers 組的服務器上顯示 hello ansible(用 common 模塊也能夠實現)
ansible webservers -m shell -a '/bin/echo hello ansible' -i inventory.cfg
結果以下:
192.168.46.128 | CHANGED | rc=0 >> hello ansible 192.168.46.129 | CHANGED | rc=0 >> hello ansible
ansible-doc -h
得到幫助
ansible-doc -l
得到工具下可以使用的模塊
ansible-doc -s
得到工具下模塊支持的動做
經過在 CentOS 上以不一樣的方式安裝 Ansible 以及對 Ansible 進行參數配置,並經過 Ansible 在被管節點上執行命令。