
連結:https://www.cnblogs.com/wenha/p/18690986

一、基礎入門
未來主體是傳統行業利用網際網路技術,以雲端用人工智慧的方式處理大資料。從早期的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, 16:14:06) [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 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'
# 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_connectionAnsible預設使用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 <host-pattern> [option]
表示inventory中定義的主機或主機組,該引數不可省略
[option]表示該選項的引數任選其一,具體選項可以使用
man 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 <host-pattern> [options]
可用[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
官方站點:www.linuxprobe.com
Linux命令大全:www.linuxcool.com

劉遄老師QQ:5604215
Linux技術交流群:2636170
(新群,火熱加群中……)
想要學習Linux系統的讀者可以點選"閱讀原文"按鈕來了解書籍《Linux就該這麼學》,同時也非常適合專業的運維人員閱讀,成為輔助您工作的高價值工具書!