一、基礎入門
未來主體是傳統行業利用互聯網技術,以云端用人工智能的方式處理大數據。從早期的All In One(所有應用部署在一臺機器上)的簡單應用,到后期集群、高可用、緩存、消息隊列、配置中心、主從分離、負載均衡、大數據存儲等尖端技術的復雜應用,對運維的技術專業度和綜合度技能要求越來越高,運維交付的標準不再是以天為單位,而是以分鐘為單位。我們需要一套自動化管理工具來幫助運維更高質量、更有效的完成手頭工作,以證明運維能創造的價值不止于此,生活不止眼前的茍且,還有詩和遠方。
1.1 定義
運維自動化目標:將日常重復性的工作通過規則設定使其遵循預先既定規則,在指定的范圍時間內自動化運行。但整個過程無需人工參與。
Ansible是幫助運維人員實現自動化的最重要的工具之一。
Ansible名字來源于其作者喜歡的一本書《安德的游戲》,該書中Ansible是一種能跨越時空的即時通信工具,使用Ansible可以在相距數光年的距離遠程實時控制前線的艦隊戰斗。
Ansible是越來越火的一款運維自動化工具,其主要功能是幫助運維實現IT工作的自動化、降低人為操作失誤、提高業務自動化率、提升運維工作效率,常用于軟件部署自動化、配置自動化、管理自動化、系統化開發任務、持續集成、零宕機平滑升級等。
Ansible是一款極其簡單的IT自動化工具。Ansible操作極其簡單,功能卻非常豐富,其自身內置的模塊數量達五百多個,主要包括:
系統層:支持Linux、Windows等
虛擬化:VMWare、Docker、Openstack等
商業化硬件:F5、ASA等
系統應用層:Apache、Zabbix、Rabbitmq、SVN、GIT
1.2 為什么選擇Ansible
Ansible基于python開發,運維人員開發門檻低
Ansible內置模塊豐富,還有專門為商業平臺開發的功能模塊
去中心化,一個簡單的操作即可完成管理配置中心的遷移
AgentLess,客戶端無需任何配置,由管理端配置好后即可使用
1.3 工作原理
Ansible沒有客戶端,底層通信依賴于系統軟件,Linux系統基于OpenSSH通信,Windows系統基于Powershell,管理端必須是Linux系統,使用者認證通過后在管理節點通過Ansible工具調用各應用模塊將指令推送至管理端執行,并在執行完畢后自動刪除產生的臨時文件。
Ansible整個工作流程中大致有三類角色:
使用者:Ansible的使用者來源于多個維度,第一種方式,CMDB(Configuration Management Database,配置管理數據庫)運維人員可以結合CMDB和Ansible,通過CMDB直接下發指令調用Ansible工具集完成操作者所希望達到的目標;第二種方式是API接口,運維人員可以使用通用開發語言以API接口調用形式完成相應的操作;第三種方式是開發人員以Ad-Hoc臨時命令方式完成相應操作;第四種是運維人員使用提前寫好的playbook完成相應的操作。
Ansible工具集:ansible命令是Ansible的核心,ansible命令通過協調Inventory(命令執行的目標對象配置文件)、API(供第三方應用程序調用的API接口)、M
作用對象:Ansible的作用對象,不僅僅是Linux和非Linux操作系統的主機,同樣也可以作用于公有云和私有云的各個網絡設施
再從Ansible工具集來講,Ansible主要有以下幾部分組成:
Ansible Playbook:任務集,編排定義Ansible任務集的配置文件,順序依次執行,一般為yaml或json文件
Inventory:主機清單
Modules:Ansible執行命令的功能模塊,多數為內置的核心模塊
Plugins:模塊功能的補充,如連接類型插件、循環插件、變量插件
API:供第三方應用程序調用的應用程序接口
Ansible執行時,這些組件的調用關系如下:
1.4 通信方式
從Ansible 1.3版本開始,默認使用OpenSSH通信方式(底層基于SSH協議,window基于Powershell協議),支持密碼和SSH認證
1.5 安裝
pip安裝方式:
// 安裝python | |
yum install python-pip python-devel -y | |
// 安裝gcc glibc開發環境 | |
yum install gcc glibc-devel zlib-devel rpm-build openssl-devel -y | |
// 升級pip | |
pip install --upgrade pip | |
// 安裝ansible | |
pip install ansible -upgrade |
yum安裝方式
rpm | |
yum install ansible -y |
安裝完后,查看ansible版本號,如果有正確返回,則表示安裝成功
[root@192-168-158-100-RedHat-7 ansible]# ansible --version | |
ansible 2.9.27 | |
config file = /etc/ansible/ansible.cfg | |
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] | |
ansible python module location = /usr/lib/python2.7/site-packages/ansible | |
executable location = /usr/bin/ansible | |
python version = 2.7.5 (default, Nov 14 2023, 1606) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] |
1.6 目錄結構
使用命令rpm -ql ansible可以查看Ansible的安裝目錄,該輸出較多,但大致可以分為以下幾個目錄:
配置文件目錄:/etc/ansible/ 用于存放Ansible主機清單,工具功能配置等。
執行文件目錄:/usr/bin/ansible-xxx 用于存放Ansible所有可執行文件
庫依賴文件目錄:/usr/lib/PythonX.X/sitepackage/ansible/
help文檔目錄:/usr/share/doc/ansible-xxxx/
1.7 配置文件詳解
Ansible自身配置文件只有一個,默認存放于/etc/ansible/ansible.cfg路徑,Ansible命令執行時,會依次從當前命令執行路徑、當前用戶家目錄、默認安裝路徑尋找ansible.cfg配置文件,找到哪個就用哪個
default 基礎設置項,保持默認即可
[defaults] | |
# some basic default values... | |
#inventory = /etc/ansible/hosts # 主機清單 | |
#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 | |
#ask_sudo_pass = True | |
#ask_pass = True | |
#transport = smart | |
#remote_port = 22 | |
#module_lang = 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 | |
# 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 | |
# 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 | |
# 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 | |
# 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 | |
# 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 | |
# 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 | |
# 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 | |
# 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 | |
#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 | |
# 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 | |
#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 hostdatabase triplet: fact_caching_connection = localhost0 | |
#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' | |
# 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 |
privilege_escalation 部分公司不希望直接以Root最高管理員權限直接部署應用,往往會開通普通用戶并授權sudo權限來進行相關操作,該部分是sudo提升權限的配置
[privilege_escalation] | |
#become=True | |
#become_method=sudo | |
#become_user=root | |
#become_ask_pass=False |
ssh_connection Ansible默認使用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 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 = | |
# 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 | |
# The -tt argument is passed to ssh when pipelining is not enabled because sudo | |
# requires a tty by default. | |
#usetty = True | |
# Number of times to retry an SSH connection to a host, in case of UNREACHABLE. | |
# For each retry attempt, there is an exponential backoff, | |
# so after the first attempt there is 1s wait, then 2s, 4s etc. up to 30s (max). | |
#retries = 3 |
accelerate 加速配置相關
[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 |
color 輸出顏色相關配置
[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 |
1.8 系列命令和使用場景
前面提到了,ansible相關命令的可執行文件均放在/usr/bin/目錄下,如下:
[root@192-168-158-100-RedHat-7 ansible-2.9.27]# ll /usr/bin/ | grep 'ansible' | |
lrwxrwxrwx 1 root root 20 Jul 26 2023 ansible -> /usr/bin/ansible-2.7 | |
lrwxrwxrwx 1 root root 20 Jul 26 2023 ansible-2 -> /usr/bin/ansible-2.7 | |
-rwxr-xr-x 1 root root 5933 Jan 16 2022 ansible-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-config -> ansible | |
-rwxr-xr-x 1 root root 13432 Jan 16 2022 ansible-connection | |
lrwxrwxrwx 1 root root 28 Jul 26 2023 ansible-console -> /usr/bin/ansible-console-2.7 | |
lrwxrwxrwx 1 root root 28 Jul 26 2023 ansible-console-2 -> /usr/bin/ansible-console-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-console-2.7 -> ansible | |
lrwxrwxrwx 1 root root 24 Jul 26 2023 ansible-doc -> /usr/bin/ansible-doc-2.7 | |
lrwxrwxrwx 1 root root 24 Jul 26 2023 ansible-doc-2 -> /usr/bin/ansible-doc-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-doc-2.7 -> ansible | |
lrwxrwxrwx 1 root root 27 Jul 26 2023 ansible-galaxy -> /usr/bin/ansible-galaxy-2.7 | |
lrwxrwxrwx 1 root root 27 Jul 26 2023 ansible-galaxy-2 -> /usr/bin/ansible-galaxy-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-galaxy-2.7 -> ansible | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-inventory -> ansible | |
lrwxrwxrwx 1 root root 29 Jul 26 2023 ansible-playbook -> /usr/bin/ansible-playbook-2.7 | |
lrwxrwxrwx 1 root root 29 Jul 26 2023 ansible-playbook-2 -> /usr/bin/ansible-playbook-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-playbook-2.7 -> ansible | |
lrwxrwxrwx 1 root root 25 Jul 26 2023 ansible-pull -> /usr/bin/ansible-pull-2.7 | |
lrwxrwxrwx 1 root root 25 Jul 26 2023 ansible-pull-2 -> /usr/bin/ansible-pull-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-pull-2.7 -> ansible | |
lrwxrwxrwx 1 root root 26 Jul 26 2023 ansible-vault -> /usr/bin/ansible-vault-2.7 | |
lrwxrwxrwx 1 root root 26 Jul 26 2023 ansible-vault-2 -> /usr/bin/ansible-vault-2.7 | |
lrwxrwxrwx 1 root root 7 Jul 26 2023 ansible-vault-2.7 -> ansible |
大致分為以下幾類: 1) ansible命令 日常工作中使用率非常高的命令之一,主要在非固化需求、臨時一次性操作、二次開發接口調用場景下使用。命令格式如下: ansible
[root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible all -m win_ping | |
192.168.158.104 | SUCCESS => { | |
"changed": false, | |
"ping": "pong" | |
} |
ansible命令輸出用紅綠黃來區分執行結果成功與失敗
2) ansible-doc命令 ansible-doc可以查看ansible各個模塊的文檔說明,功能類似于man命令 ansible支持的window模塊大多以“win_”開頭
//查看ansible各個模塊,可以看到ansible支持的windows模塊大多以"win_"開頭,例如,linux中使用的ping模塊,windows中為win_ping | |
ansible-doc -l | |
//查看某個具體的模塊 | |
ansible-doc win_ping |
3) ansible-galaxy命令 模塊管理器,類似python中的pip,可以根據安裝量和下載量等信息,查找和安裝相應的roles
ansible-galaxy [init|info|list|install|remove] [options].... |
4) ansible-playbook命令 通過預先編寫好的playbook文件實現批量管理,要實現的功能與命令ansible一樣,可以理解為按一定條件組成的ansible任務集 5) ansible-pull命令 ansible的另外一種工作模式,默認為push模式 6) ansible-vault命令 用于配置文件加密,如果編寫的playbook文件中有敏感信息,可以使用ansible-valut進行加密解密,防止他人隨意查看
[root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible-vault encrypt test.yaml | |
New Vault password: | |
Confirm New Vault password: | |
Encryption successful | |
[root@192-168-158-100-RedHat-7 ansible-2.9.27]# cat test.yaml | |
$ANSIBLE_VAULT;1.1;AES256 | |
36353131383762396361623833653734356261666435633335636338333834393535353839383962 | |
6237316263616662336161353433643435663737323431350a626338393561623639653961656238 | |
66663031626464343661393732633264366265653734363139343330396430386364343232366138 | |
3430326166326336630a343062623461633862366266363963376231343732623861666336326533 | |
65346363386338636161613833646137306562636566633434373037313630636161 | |
[root@192-168-158-100-RedHat-7 ansible-2.9.27]# ansible-vault decrypt test.yaml | |
Vault password: | |
Decryption successful |
1.9 Inventory配置文件詳解
Inventory是ansible管理主機信息的配置文件,默認存放于/etc/ansible/hosts。Ansible在使用時通過-i或者--inventory-file來制定文件讀取,如ansible -i /etc/ansible/hosts webs -m ping,如果只有一個Inventory時可以不用指定路徑,默認讀取/etc/ansible/hosts。inventory可以同時存在多個,而且支持動態生成。
1)主機和組
Inventory配置文件遵循ini文件風格,中括號里的字符為組名,并且支持將同一個主機同時歸并到多個不同的組中。若主機使用了非默認的ssh端口,還可以在主機名稱之后使用冒號加端口號來標明
#“#”開頭的行表示該行為注釋行,即當時行的配置不生效 | |
# Inventory 可以直接為 IP 地址 | |
192.168.37.149# Inventory 同樣支持 Hostname 的方式,后跟冒號加數字表示端口號,默認 22 號端口ntp.magedu.com:2222 | |
nfs .magedu.com | |
# 中括號內的內容表示一個分組的開始,緊隨其后的主機均屬于該組成員,空行后的主機亦屬于該組,即web2.magedu.com這臺主機也屬于[websevers]組 | |
[websevers] | |
web1 .magedu.com | |
web[10:20].magedu.com #[10:20]表示10~20 之間的所有數字(包括10和20),即表示 web10.magedu.com、web11.magedu.com……web20.magedu.com 的所有主機 | |
web2 .magedu.com[dbservers] | |
db-a.magedu.com | |
db-[b:f].magedu.com #[b:f]表示b到f之間的所有數字(包括b和f),即表示 db-b.magedu.com、db-e.magedu.com…db-f.magedu.com的所有主機 |
2) 定義主機變量
[webservers] | |
web1.magedu.com http_port=808 maxRequestsPerchild=801 #自定義http_port 的端口號為808,配置maxRequestsPerchild為801 | |
3) 定義組變量
[groupservers] | |
webl .magedu.com | |
web2 .magedu.com | |
[groupservers:vars] | |
ntp_server=ntp.magedu.com #定義groupservers 組中所有主機ntp_server 值為 ntp.magedu.com | |
nfs_server=nfs.magedu.com #定義groupservers 組中所有主機nfs_server 值為 nfs.magedu.com | |
4) 定義組嵌套及變量
[apache] | |
httpdl.magedu.com | |
httpd2.magedu.com | |
[nginx] | |
ngx1.magedu.com | |
ngx2.magedu.com | |
[webservers:children] | |
apache | |
nginx | |
[webservers:vars] | |
ntp_server=ntp.magedu.com |
二、兩大常用命令
介紹了Ansible的各項元素、系列命令、Inventory基礎,這些是掌握Ansible的基礎,本篇接著介紹Ansible兩大神器Ad-Hoc命令集和playbook,通過模擬真實的案例和應用場景更深入地了解Ansible。
2.1 Ad-Hoc命令集
1)使用場景
Ad-Hoc源自拉丁語“ad hoc”,意思是“為了這個目的”或“特定目的”。我們可以理解為解決一些簡單或者平時工作中臨時遇到的任務所做的“臨時操作”。比如:臨時向某一集群中各個服務器推送一個文件等
2)命令集介紹
Ad-Hoc命令集由/usr/bin/ansible實現,其命令語法如下:
ansible |
可用[options]有:
-i PATH,指定inventory信息,默認/etc/ansible/hosts
-f NUM, 并發線程數,默認5個線程
--private-key=PRIVATE_KEY_FILE:指定密鑰文件
-m NAME,指定使用的模塊
-M DIRECTORY,指定模塊存放路徑
-a 'ARGUMENTS',模塊參數
-k,認證密碼
-o,標準輸出至一行
-s,相當于Linux系統下的sudo命令
-t DIRECTORY,輸出信息至DIRECTORY目錄下,結果文件為遠程主機名
-T SECONDS,指定連接遠程主機的最大超時時間,單位是秒
-B NUM,后臺執行命令,超Num秒后中止正在執行的任務
-P NUM,定期返回后臺任務進度
-u USERNAME,指定遠程主機以USERNAME運行命令
--list-hosts,列出符合條件的主機列表,不執行任何命令 命令執行流程:
場景1:檢查主機是否存活 執行命令: ansible linux -m ping 返回結果:
[root@192-168-158-100-RedHat-7 .ssh]# ansible linux -m ping | |
192.168.158.16 | SUCCESS => { | |
"ansible_facts": { | |
"discovered_interpreter_python": "/usr/bin/python" | |
}, | |
"changed": false, | |
"ping": "pong" | |
} | |
192.168.158.23 | SUCCESS => { | |
"ansible_facts": { | |
"discovered_interpreter_python": "/usr/bin/python" | |
}, | |
"changed": false, | |
"ping": "pong" | |
} | |
192.168.158.176 | SUCCESS => { | |
"ansible_facts": { | |
"discovered_interpreter_python": "/usr/bin/python" | |
}, | |
"changed": false, | |
"ping": "pong" | |
} | |
“linux”組下有三臺linux機器,看下第一臺機器的輸出 “172.168.158.16”是命令執行的主機; “Success”表示命令執行成功; “=>{}”表示詳細返回結果如下; ““changed”:false”表示沒有對主機做變更;““ping”:"pong"”表示執行ping命令返回了pong
場景2:返回Linux組所有主機的hostname 執行命令: ansible linux -m command -a 'hostname' 返回結果:
[root@192-168-158-100-RedHat-7 .ssh]# ansible linux -m command -a 'hostname' | |
192.168.158.16 | CHANGED | rc=0 >> | |
k8sworker | |
192.168.158.23 | CHANGED | rc=0 >> | |
k8smaster | |
192.168.158.176 | CHANGED | rc=0 >> | |
192-168-158-176-RedHat-7 | |
場景3:返回Linux組所有機器 執行命令 ansible linux --list-hosts 返回結果
[root@192-168-158-100-RedHat-7 .ssh]# ansible linux --list-hosts | |
hosts (3): | |
192.168.158.23 | |
192.168.158.16 | |
192.168.158.176 |
鏈接:https://www.cnblogs.com/wenha/p/18690986
-
互聯網
+關注
關注
54文章
11189瀏覽量
103876 -
IT
+關注
關注
2文章
870瀏覽量
63633 -
自動化
+關注
關注
29文章
5629瀏覽量
79677
原文標題:二、兩大常用命令
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
誠聘高級運維自動化工程師
CasePlayer2--單元測試自動化工具
紅帽推出Ansible 2.2 :為開源自動化框架奠定牢靠的基礎
模擬EDA自動化工具如今已經登場
利用Ansible實現OpenStack自動化
![利用<b class='flag-5'>Ansible</b>實現OpenStack<b class='flag-5'>自動化</b>](https://file.elecfans.com/web1/M00/AF/79/pIYBAF3g-taAd5raAAEO6rq0A8s089.png)
利用Ansible實現OpenStack自動化
一文詳解Ansible的自動化運維
![一文詳解<b class='flag-5'>Ansible</b>的<b class='flag-5'>自動化</b>運維](https://file.elecfans.com/web1/M00/BC/8E/o4YBAF7DoNqAWrNMAAAgVKI8Uv0899.png)
使用Ansible的OpenStack自動化
![使用<b class='flag-5'>Ansible</b>的OpenStack<b class='flag-5'>自動化</b>](https://file.elecfans.com//web2/M00/85/0C/poYBAGOio7KAZK9FAABkxYRfs3Y548.jpg)
網絡設備自動化運維工具—ansible入門筆記介紹
![網絡設備<b class='flag-5'>自動化</b>運維<b class='flag-5'>工具</b>—<b class='flag-5'>ansible</b><b class='flag-5'>入門</b>筆記介紹](https://file1.elecfans.com/web2/M00/BD/84/wKgaomWkx0GASzkwAABPQEe9jQo543.png)
評論