自動化運維工具-Ansible(一)
一、Ansible概述
Ansible簡介
Ansible是一款類Unix系統開發的自由開源的配置和自動化工具。
它用Python寫成,類似於saltstack和Puppeet,但是有一個不同的優點是我們不需要在節點中安裝任何客戶端
它使用ssh來和節點進行通訊。Ansible基於Python paramiko開發,分散式、無需客戶端、輕量級,配置語法使用yaml及Jinja2模板語言,更強的遠端命令來執行操作。
Ansible官方網站
Ansible特點
1、部署簡單、沒有客戶端,只需在主控端部署Ansible環境,被控端無需做任何操作
2、模組化:呼叫特定的模組,完成特定任務
3、預設是用SSH協議對裝置進行管理
4、主從集中化管理
5、配置簡單、功能強大、擴充套件性強
6、支援API及自定義模組,可通過Python輕鬆擴充套件
7、通過Playbooks來定製強大的配置、狀態管理
8、對雲端計算、大資料都有很好的支援
9、具有冪等性:一個操作在一個主機執行一遍和執行N遍的結果是一樣的
Ansible是基於模組工作的,本身沒有批量部署的能力。真正具有批量部署的是Ansible所執行的模組,Ansible只是提供一種框架。
Ansible框架主要包括:
- 連線外掛connection plugins:負責和被監控端實現通訊;
- host inventory:指定操作的主機,是一個配置檔案裡面定義監控的主機
- 各種模組核心模組、command模組、自定義模組
- 將誒主語外掛完成記錄日誌郵件等功能
- playbook:劇本執行多個任務時,非必需可以讓節點一次性執行多個任務
Ansible架構
Ansible在管理節點將Ansible模組通過SSH協議推送到被管理端執行,執行完之後自動刪除,可以使用SVN等來管理自定義模組及編排。
Ansible主要由以下模組組成:
- Ansible:ansible的核心程式
- Host Inventory:記錄由Ansible管理的主機資訊,包括埠、密碼、ip等
- Playbooks:ansible的劇本,yaml格式檔案,多個任務定義在一個檔案中,定義主機需要呼叫哪些模組來完成的功能
- Core Modules:核心模組,主要操作是通過呼叫核心模組來完成管理任務
- Custom Modules:自定義模組,完成核心模組無法完成的功能,支援多種語言
- Connection Plugins:連線外掛,用於與被管控主機之間基於SSH建立連線關係
- Plugins:其他外掛,包括記錄日誌等
Ansible任務執行
Ansible任務執行模式
Ansible系統由控制主機對被管控節點的操作方式可分為兩類:adhoc和playbook:
-
ad-hoc模式(點對點模式)
使用單個模組,支援批量執行單條命令。ad-hoc命令是一種可以快速輸入的命令,而且是不需要儲存起來的命令。相當於bash中的一條shell指令
-
playbook模式(劇本模式)
是Ansible主要管理方式,也是Ansible功能強大的關鍵所在。playbook通過多個task集合完成一類功能,如Web服務的安裝部署、資料庫伺服器的批量備份等。可以簡單地把playbook理解為通過組合多條ad-hoc操作的配置檔案
Ansible執行流程
Ansible在執行時,首先讀取ansible.cfg中的配置,根據規則獲取Inventory中的管理主機列表,並行在這些主機中執行配置的任務,最後等待執行返回的結果。
Ansible命令執行過程
- 載入自己的配置檔案,預設
/etc/ansible/ansible.cfg
- 查詢對應的主機配置檔案,找到要執行的主機或組
- 載入自己對應的模組檔案,如command
- 通過Ansible將模組或命令生成對應的臨時py檔案,並將該檔案傳輸至遠端伺服器
- 對應執行使用者的家目錄的
.ansible/tmp/xxx/xxx.py
檔案 - 給檔案賦予執行許可權
- 執行並返回結果
- 刪除臨時py檔案,sleep 0退出
Ansible是導演,受控機器列表(inventory)為演員列表,開發者則是編劇。開發者只要把劇本(palybook.yml)寫好,Ansible拿著劇本與inventory對上號,演員就會按照劇本如實表演,不會有任何個人發揮。
二、Ansible配置詳解
Ansible安裝
centos系統
#由於Ansible不在yum倉庫中,需要先安裝epel倉庫
[root@aliyun ~]# yum install -y epel-release
#安裝Ansible
[root@aliyun ~]# yum install -y ansible
#檢視Ansible版本
[root@aliyun ~]# 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 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
Ansible程式結構
安裝目錄如下(yum安裝):
- 配置檔案目錄:
/etc/ansible
- 執行檔案目錄:
/usr/bin
- Lib庫依賴目錄:
/usr/lib/pythonX.X/site-package/ansible
- Help文件目錄:
/usr/share/doc/ansible-X.X.X
- Man文件目錄:
/usr/share/man/man1
Ansible配置檔案查詢順序
Ansible與我們其他的服務在這一點上有很大不同,這裡的配置檔案查詢是從多個地方找的,順序如下:
- 檢查環境變數
ANSIBLE_CONFIG
指向的路徑檔案(export ANSIBLE_CONFIG=/etc/ansible.cfg) -
~/.ansible.cfg
,檢查當前目錄下的ansible.cfg配置檔案 -
/etc/ansible.cfg
,檢查etc目錄的配置檔案
Ansible配置檔案
Ansible的配置檔案為/etc/ansible/ansible.cfg
,ansible有許多引數,下面列出一些常見的引數:
- inventory = /etc/ansible/hosts #這個引數表示資源清單inventory檔案的位置
- library = /usr/share/ansible #指向存放ansible模組的目錄,支援多個目錄,只要用冒號(:)隔開即可
- forks = 5 #併發連線數,預設為5
- sudo_user = root #設定預設執行命令的使用者
- remote_port = 22 #指定連線被管節點的管理埠,預設為22埠,建議修改,能夠更加安全
- host_key_checking = False #設定是否檢查ssh主機的金鑰,值為True/False。關閉後第一次連線不會提示配置示例
- timeout = 60 #設定SSH連線的超時時間,單位為秒
- log_path = /var/log/ansible.log #指定一個儲存ansible日誌的檔案(預設不記錄日誌)
Ansible主機清單
在配置檔案中,我們提到了資源清單,這個清單就是我們的主機清單,裡面儲存的是一些Ansible需要連線管理的主機列表。
[root@aliyun ansible]# cat 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
三、Ansible常用命令
Ansible命令集
#Ansible AD-Hoc臨時命令執行工具,常用於臨時命令的執行
/usr/bin/ansible
#Ansible模組功能檢視工具
/usr/bin/ansible-doc
#下載/上傳優秀程式碼或Roles模組的官方平臺
/usr/bin/ansible-galaxy
#Ansible定製自動化的任務集編排工具
/usr/bin/ansible-playbook
#Ansible遠端執行命令的工具,拉取配置而非推送配置(使用較少,海量機器時使用,對運維的架構能力要求較高)
/usr/bin/ansible-pull
#Ansible檔案加密工具
/usr/bin/ansible-vault
#Ansible基於Linux Consoble介面可與使用者互動的命令執行工具
/usr/bin/ansible-console
其中比較常用的是:/usr/bin/ansible
和/usr/bin/ansible-playbook
ansible-doc命令
ansible-doc
命令常用於獲取模組資訊及其使用幫助,一般用法如下:
#獲取全部模組資訊
[root@aliyun ~]# ansible-doc -l
#獲取指定模組的使用幫助
[root@aliyun ~]# ansible-doc -s MOD_NAME
#檢視ansible-doc的用法
[root@aliyun ~]# ansible-doc
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
[--playbook-dir BASEDIR]
[-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
[-j] [-F | -l | -s | --metadata-dump]
[plugin [plugin ...]]
plugin documentation tool
positional arguments:
plugin Plugin
optional arguments:
--metadata-dump **For internal testing only** Dump json metadata for
all plugins.
--playbook-dir BASEDIR
Since this tool does not use playbooks, use this as a
substitute playbook directory.This sets the relative
path for many features including roles/ group_vars/
etc.
--version show program's version number, config file location,
configured module search path, module location,
executable location and exit
-F, --list_files Show plugin names and their source files without
summaries (implies --list)
-M MODULE_PATH, --module-path MODULE_PATH
prepend colon-separated path(s) to module library (def
ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
gins/modules)
-h, --help show this help message and exit
-j, --json Change output into json format.
-l, --list List available plugins
-s, --snippet Show playbook snippet for specified plugin(s)
-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}
Choose which plugin type (defaults to "module").
Available plugin types are : ('become', 'cache',
'callback', 'cliconf', 'connection', 'httpapi',
'inventory', 'lookup', 'netconf', 'shell', 'module',
'strategy', 'vars')
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com
#實驗,以mysql為例
[root@aliyun ~]# ansible-doc -l |grep mysql
azure_rm_mysqlfirewallrule_info Get Azure MySQL Firewall Rule facts
azure_rm_mysqlconfiguration_info Get Azure MySQL Configuration facts
mysql_info Gather information about MySQL servers
mysql_db Add or remove MySQL databases from a remote host
azure_rm_mysqlserver_info Get Azure MySQL Server facts
azure_rm_mysqldatabase_info Get Azure MySQL Database facts
mysql_variables Manage MySQL global variables
mysql_user Adds or removes a user from a MySQL database
proxysql_backend_servers Adds or removes mysql hosts from proxysql admin interface
azure_rm_mysqlconfiguration Manage Configuration instance
azure_rm_mysqlfirewallrule Manage MySQL firewall rule instance
azure_rm_mysqlserver Manage MySQL Server instance
mysql_replication Manage MySQL replication
proxysql_mysql_users Adds or removes mysql users from proxysql admin interface
azure_rm_mysqldatabase Manage MySQL Database instance
#檢視具體的模組mysql_user
[root@aliyun ~]# ansible-doc -s mysql_user
- name: Adds or removes a user from a MySQL database
mysql_user:
append_privs: # Append the privileges defined by priv to the existing ones for this user instead of overwriting
existing ones.
ca_cert: # The path to a Certificate Authority (CA) certificate. This option, if used, must specify the same
certificate as used by the server.
check_implicit_admin: # Check if mysql allows login as root/nopassword before trying supplied credentials.
client_cert: # The path to a client public key certificate.
client_key: # The path to the client private key.
config_file: # Specify a config file from which user and password are to be read.
connect_timeout: # The connection timeout when connecting to the MySQL server.
encrypted: # Indicate that the 'password' field is a `mysql_native_password` hash.
host: # The 'host' part of the MySQL username.
host_all: # Override the host option, making ansible apply changes to all hostnames for a given user. This option
cannot be used when creating users.
login_host: # Host running the database.
login_password: # The password used to authenticate with.
login_port: # Port of the MySQL server. Requires `login_host' be defined as other than localhost if login_port is
used.
login_unix_socket: # The path to a Unix domain socket for local connections.
login_user: # The username used to authenticate with.
name: # (required) Name of the user (role) to add or remove.
password: # Set the user's password..
priv: # MySQL privileges string in the format: `db.table:priv1,priv2'. Multiple privileges can be specified by
separating each one using a forward slash:
`db.table:priv/db.table:priv'. The format is based on MySQL `GRANT'
statement. Database and table names can be quoted, MySQL-style. If
column privileges are used, the `priv1,priv2' part must be exactly as
returned by a `SHOW GRANT' statement. If not followed, the module will
always report changes. It includes grouping columns by permission
(`SELECT(col1,col2') instead of `SELECT(col1',SELECT(col2))).
sql_log_bin: # Whether binary logging should be enabled or disabled for the connection.
state: # Whether the user should exist. When `absent', removes the user.
update_password: # `always' will update passwords if they differ. `on_create' will only set the password for newly created
users.
(END)
Ansible命令詳解
使用ansible -h
可檢視ansible如何使用
[root@aliyun ~]# ansible -h
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
[--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
[-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
[--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
[-c CONNECTION] [-T TIMEOUT]
[--ssh-common-args SSH_COMMON_ARGS]
[--sftp-extra-args SFTP_EXTRA_ARGS]
[--scp-extra-args SCP_EXTRA_ARGS]
[--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
[-e EXTRA_VARS] [--vault-id VAULT_IDS]
[--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
[-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
[-a MODULE_ARGS] [-m MODULE_NAME]
pattern
Define and run a single task 'playbook' against a set of hosts
positional arguments:
pattern host pattern
optional arguments:
--ask-vault-pass ask for vault password
--list-hosts outputs a list of matching hosts; does not execute
anything else
--playbook-dir BASEDIR
Since this tool does not use playbooks, use this as a
substitute playbook directory.This sets the relative
path for many features including roles/ group_vars/
etc.
--syntax-check perform a syntax check on the playbook, but do not
execute it
--vault-id VAULT_IDS the vault identity to use
--vault-password-file VAULT_PASSWORD_FILES
vault password file
--version show program's version number, config file location,
configured module search path, module location,
executable location and exit
-B SECONDS, --background SECONDS
run asynchronously, failing after X seconds
(default=N/A)
-C, --check don't make any changes; instead, try to predict some
of the changes that may occur
-D, --diff when changing (small) files and templates, show the
differences in those files; works great with --check
-M MODULE_PATH, --module-path MODULE_PATH
prepend colon-separated path(s) to module library (def
ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
gins/modules)
-P POLL_INTERVAL, --poll POLL_INTERVAL
set the poll interval if using -B (default=15)
-a MODULE_ARGS, --args MODULE_ARGS
module arguments
-e EXTRA_VARS, --extra-vars EXTRA_VARS
set additional variables as key=value or YAML/JSON, if
filename prepend with @
-f FORKS, --forks FORKS
specify number of parallel processes to use
(default=5)
-h, --help show this help message and exit
-i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY
specify inventory host path or comma separated host
list. --inventory-file is deprecated
-l SUBSET, --limit SUBSET
further limit selected hosts to an additional pattern
-m MODULE_NAME, --module-name MODULE_NAME
module name to execute (default=command)
-o, --one-line condense output
-t TREE, --tree TREE log output to this directory
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
Privilege Escalation Options:
control how and which user you become as on target hosts
--become-method BECOME_METHOD
privilege escalation method to use (default=sudo), use
`ansible-doc -t become -l` to list valid choices.
--become-user BECOME_USER
run operations as this user (default=root)
-K, --ask-become-pass
ask for privilege escalation password
-b, --become run operations with become (does not imply password
prompting)
Connection Options:
control as whom and how to connect to hosts
--private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE
use this file to authenticate the connection
--scp-extra-args SCP_EXTRA_ARGS
specify extra arguments to pass to scp only (e.g. -l)
--sftp-extra-args SFTP_EXTRA_ARGS
specify extra arguments to pass to sftp only (e.g. -f,
-l)
--ssh-common-args SSH_COMMON_ARGS
specify common arguments to pass to sftp/scp/ssh (e.g.
ProxyCommand)
--ssh-extra-args SSH_EXTRA_ARGS
specify extra arguments to pass to ssh only (e.g. -R)
-T TIMEOUT, --timeout TIMEOUT
override the connection timeout in seconds
(default=10)
-c CONNECTION, --connection CONNECTION
connection type to use (default=smart)
-k, --ask-pass ask for connection password
-u REMOTE_USER, --user REMOTE_USER
connect as this user (default=None)
Some modules do not make sense in Ad-Hoc (include, meta, etc)
以下列出一些比較常用的選項,並解釋其含義
選項 | 描述 |
---|---|
-a MODULE_ARGS | 模組的引數,如果執行預設command的模組,即是命令引數,如:date,pwd等等 |
-k, --ask-pass | 登陸密碼,提示輸入SSH密碼而不是假設基於金鑰的驗證 |
-i INVENTORY | 指定主機清單的路徑 |
-B SECONDS | 後臺執行超時時間 |
-C, --check | 模擬執行環境並進行預執行,可進行查錯測試 |
-c CONNECTION | 連線型別使用 |
-f FORKS | 併發任務數,預設為5 |
--list-hosts | 檢視有哪些主機組 |
-m MODULE_NAME | 執行模組的名字,預設使用command模組。所以如果只執行單一命令,可以不使用-m引數 |
-o, --one-line | 壓縮輸出,嘗試將所有結果在一行輸出,一般針對收集工具使用 |
-T TIMEOUT | 指定ssh預設超時時間,預設為10s,也可在配置檔案中修改 |
-u REMOTE_USER | 遠端使用者,預設為root使用者 |
-v, --verbose | 檢視詳細資訊 |
Ansible配置公私鑰
#主控機器生成私鑰
[root@server ~]# ssh-keygen
#向受控機發送私鑰
[root@server ~]# ssh-copy-id [email protected]
[root@server ~]# ssh-copy-id [email protected]
四、Ansible常用模組
主機連通性測試
#在/etc/ansible/hosts檔案中新增受控主機列表
[root@k8s-master ansible]# vim hosts
···
# Here's another example of host ranges, this time there are no
# leading 0s:
## db-[99:101]-node.example.com
[k8s]
192.168.133.11
192.168.133.12
#測試連通性
[root@k8s-master ansible]# ansible k8s -m ping
192.168.133.11 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong" #pong表示連通成功
}
192.168.133.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
command模組
此模組可以直接在遠端主機上執行命令,並將結果返回本主機
[root@k8s-master ~]# ansible k8s -m command -a "ss -ntl"
192.168.133.12 | CHANGED | rc=0 >>
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 127.0.0.1:10248 *:*
LISTEN 0 128 127.0.0.1:10249 *:*
LISTEN 0 128 127.0.0.1:9099 *:*
LISTEN 0 128 127.0.0.1:41999 *:*
LISTEN 0 128 *:111 *:*
LISTEN 0 8 *:179 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 [::1]:25 [::]:*
LISTEN 0 128 [::]:10250 [::]:*
LISTEN 0 128 [::]:111 [::]:*
LISTEN 0 128 [::]:10256 [::]:*
LISTEN 0 128 [::]:22 [::]:*
192.168.133.11 | CHANGED | rc=0 >>
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 8 *:179 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 127.0.0.1:10248 *:*
LISTEN 0 128 127.0.0.1:46632 *:*
LISTEN 0 128 127.0.0.1:10249 *:*
LISTEN 0 128 127.0.0.1:9099 *:*
LISTEN 0 128 *:111 *:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
LISTEN 0 128 [::]:10250 [::]:*
LISTEN 0 128 [::]:111 [::]:*
LISTEN 0 128 [::]:10256 [::]:*
命令模組接受命令名稱,後面是空格分隔的列表引數。給定的命令將在所有選定的節點上執行。它不會通過shell進行處理,比如$HOME和操作符如:<、>、|、&等(需使用shell模組才能實現)。注意:該命令不支援管道命令:|
以下是該模組下常用的幾個命令
- chdir:在執行命令之前,先切換到該目錄
- executable:切換shell來執行命令,需要使用命令的絕對路徑
- free_form:要執行的Linux指令,一般使用Ansible的-a引數代替
- creates:一個檔名,當這個檔案存在,則該命令不執行,可以用來做判斷
- removes:一個檔名,當檔案不存在,則該命令不執行
#測試
#切換目錄並檢視該目錄下的內容
[root@k8s-master ~]# ansible k8s -m command -a "chdir=/root ls"
192.168.133.12 | CHANGED | rc=0 >>
anaconda-ks.cfg
k8s-images-v1.20.4.tar.gz
192.168.133.11 | CHANGED | rc=0 >>
anaconda-ks.cfg
k8s-images-v1.20.4.tar.gz
#事先在192.168.133.11中建立/root/111.txt檔案
[root@k8s-node1 ~]# touch 111.txt
#如果/root/111.txt存在,則不執行ls命令
[root@k8s-master ~]# ansible k8s -m command -a "creates=/root/111.txt ls"
192.168.133.12 | CHANGED | rc=0 >>
anaconda-ks.cfg
k8s-images-v1.20.4.tar.gz
192.168.133.11 | SUCCESS | rc=0 >>
skipped, since /root/111.txt exists
#如果/root/111.txt存在,則執行ls命令
[root@k8s-master ~]# ansible k8s -m command -a "removes=/root/111.txt ls"
192.168.133.11 | CHANGED | rc=0 >>
111.txt
anaconda-ks.cfg
k8s-images-v1.20.4.tar.gz
192.168.133.12 | SUCCESS | rc=0 >>
skipped, since /root/111.txt does not exist
shell模組
shell模組可以在遠端主機上呼叫shell直譯器來執行命令,支援shell的各種功能
[root@k8s-master ~]# ansible k8s -m shell -a "ps -aux | grep kube | grep -v grep"
192.168.133.12 | CHANGED | rc=0 >>
root 923 1.1 5.5 1385644 55136 ? Ssl 15:19 0:31 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --network-plugin=cni --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.2
root 3023 0.0 2.3 743584 23368 ? Ssl 15:21 0:00 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=k8s-node2
polkitd 3985 0.0 2.6 740488 26104 ? Ssl 15:21 0:00 /usr/bin/kube-controllers
192.168.133.11 | CHANGED | rc=0 >>
root 921 1.2 5.7 1467572 57068 ? Ssl 15:19 0:34 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --network-plugin=cni --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.2
root 3261 0.0 2.1 743584 21084 ? Ssl 15:21 0:00 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=k8s-node1
copy模組
此模組的作用是:將檔案複製到遠端主機,同時支援給定內容生成檔案和修改許可權等,其相關選項如下:
- src:將主機中的檔案複製到遠端主機,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,則會遞迴複製,用法類似於rsync
- content:用於替換src,可以直接指定檔案的值
- dest:必選項,將原始檔複製到遠端主機的哪個路徑,此路徑為絕對路徑
- backup:當檔案內容發生改變後,在覆蓋之前將原始檔備份,備份檔案包含時間資訊
- directory_mode:遞迴設定目錄的許可權,預設為系統預設許可權
- force:當目標主機包含該檔案,但內容不同時,設為“yes”,表示強制覆蓋;設為“no”,表示目標主機的目標位置不存在該檔案時才複製。預設為yes
- others:所有的file模組中的選項可以在這裡使用
#複製檔案
[root@k8s-master ~]# ansible k8s -m copy -a "src=./hello.txt dest=/home/hello.txt"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511",
"dest": "/home/hello.txt",
"gid": 0,
"group": "root",
"md5sum": "6f5902ac237024bdd0c176cb93063dc4",
"mode": "0644",
"owner": "root",
"size": 12,
"src": "/root/.ansible/tmp/ansible-tmp-1653553381.48-115490-67144649980806/source",
"state": "file",
"uid": 0
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511",
"dest": "/home/hello.txt",
"gid": 0,
"group": "root",
"md5sum": "6f5902ac237024bdd0c176cb93063dc4",
"mode": "0644",
"owner": "root",
"size": 12,
"src": "/root/.ansible/tmp/ansible-tmp-1653553381.56-115492-162691615569451/source",
"state": "file",
"uid": 0
}
#檔案已複製成功
[root@k8s-node1 home]# ll
總用量 4
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
#給定內容生成檔案,並指定許可權
[root@k8s-master ~]# ansible k8s -m copy -a "content='雷子鍋' dest=/home/111.txt mode=700"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "d3ddd0c4bc75549fc810543f9fe1450011c1b739",
"dest": "/home/111.txt",
"gid": 0,
"group": "root",
"md5sum": "67b24789ccd15daa7dc6d9bcd4596886",
"mode": "0700",
"owner": "root",
"size": 9,
"src": "/root/.ansible/tmp/ansible-tmp-1653553527.88-120148-183008755365152/source",
"state": "file",
"uid": 0
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "d3ddd0c4bc75549fc810543f9fe1450011c1b739",
"dest": "/home/111.txt",
"gid": 0,
"group": "root",
"md5sum": "67b24789ccd15daa7dc6d9bcd4596886",
"mode": "0700",
"owner": "root",
"size": 9,
"src": "/root/.ansible/tmp/ansible-tmp-1653553527.89-120150-177029078281199/source",
"state": "file",
"uid": 0
}
#驗證
[root@k8s-node1 home]# ll
總用量 8
-rwx------ 1 root root 9 5月 26 16:25 111.txt
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
[root@k8s-node1 home]# cat 111.txt
雷子鍋
#覆蓋備份
[root@k8s-master ~]# ansible k8s -m copy -a "content='雷子鍋666' backup=yes dest=/home/111.txt mode=700"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/home/111.txt.117882.2022-05-26@16:28:02~",
"changed": true,
"checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"dest": "/home/111.txt",
"gid": 0,
"group": "root",
"md5sum": "5be6f09789e8a48c5b3f3522ee3672e2",
"mode": "0700",
"owner": "root",
"size": 12,
"src": "/root/.ansible/tmp/ansible-tmp-1653553681.57-124779-212378984215513/source",
"state": "file",
"uid": 0
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/home/111.txt.124358.2022-05-26@16:28:02~",
"changed": true,
"checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"dest": "/home/111.txt",
"gid": 0,
"group": "root",
"md5sum": "5be6f09789e8a48c5b3f3522ee3672e2",
"mode": "0700",
"owner": "root",
"size": 12,
"src": "/root/.ansible/tmp/ansible-tmp-1653553681.57-124781-36212787773143/source",
"state": "file",
"uid": 0
}
#驗證,看到之前111.txt檔案已進行備份
[root@k8s-master ~]# ansible k8s -m shell -a "ls -al /home"
192.168.133.11 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 2 root root 81 5月 26 16:28 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.117882.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
192.168.133.12 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 2 root root 81 5月 26 16:28 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.124358.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
#檢視111.txt的檔案內容
[root@k8s-master ~]# ansible k8s -m shell -a "cat /home/111.txt"
192.168.133.11 | CHANGED | rc=0 >>
雷子鍋666
192.168.133.12 | CHANGED | rc=0 >>
雷子鍋666
file模組
該模組主要用於設定檔案的屬性,如建立檔案、建立連結檔案、刪除檔案等,常用命令如下:
- force:需要在兩種情況下強制建立軟連線,一種是原始檔不存在,但之後會建立的情況下;另一種是目標軟連結已存在,需要先取消之前的軟連結,然後建立新的軟連結,有兩個選項:yes|no
- group:定義檔案/目錄的屬組。後面可加上mode用於定義檔案/目錄的許可權
- owner:定義檔案/目錄的屬主。後面必須跟上path來指定檔案/目錄的路徑
- recurse:遞迴設定檔案的屬性,只對目錄有效,後面可以跟上src:被連結的原始檔路徑,只應用於state=link的情況
- state:狀態,有以下選項:
- directory:如果目錄不存在,就建立目錄
- file:即使檔案不存在,也不會被建立
- link:建立軟連結
- hard:建立硬連結
- touch:如果檔案不存在,則會建立一個新的檔案,如果檔案或目錄已存在,則只更新其最後修改時間
- absent:刪除目錄、檔案或者取消連結檔案
#建立目錄
[root@k8s-master ~]# ansible k8s -m file -a "path=/home/test state=directory"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/home/test",
"size": 6,
"state": "directory",
"uid": 0
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/home/test",
"size": 6,
"state": "directory",
"uid": 0
}
#驗證
[root@k8s-master ~]# ansible k8s -m shell -a "ls -al /home"
192.168.133.12 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 93 5月 26 17:05 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.124358.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test #目錄已建立
192.168.133.11 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 93 5月 26 17:05 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.117882.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test
#建立軟連結檔案
[root@k8s-master ~]# ansible k8s -m file -a "path=/home/222.txt src=111.txt state=link"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/home/222.txt",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 7,
"src": "111.txt",
"state": "link",
"uid": 0
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/home/222.txt",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 7,
"src": "111.txt",
"state": "link",
"uid": 0
}
#驗證
[root@k8s-master ~]# ansible k8s -m shell -a "ls -al /home"
192.168.133.12 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 108 5月 26 17:15 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.124358.2022-05-26@16:28:02~
lrwxrwxrwx 1 root root 7 5月 26 17:15 222.txt -> 111.txt
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test
192.168.133.11 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 108 5月 26 17:15 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.117882.2022-05-26@16:28:02~
lrwxrwxrwx 1 root root 7 5月 26 17:15 222.txt -> 111.txt
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test
#可以看到,222.txt檔案已建立
#刪除檔案
[root@k8s-master ~]# ansible k8s -m file -a "path=/home/222.txt state=absent"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/home/222.txt",
"state": "absent"
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/home/222.txt",
"state": "absent"
}
#驗證
[root@k8s-master ~]# ansible k8s -m shell -a "ls -al /home"
192.168.133.11 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 93 5月 26 17:17 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.117882.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test
192.168.133.12 | CHANGED | rc=0 >>
總用量 12
drwxr-xr-x. 3 root root 93 5月 26 17:17 .
dr-xr-xr-x. 17 root root 244 2月 19 17:18 ..
-rwx------ 1 root root 12 5月 26 16:28 111.txt
-rwx------ 1 root root 9 5月 26 16:25 111.txt.124358.2022-05-26@16:28:02~
-rw-r--r-- 1 root root 12 5月 26 16:23 hello.txt
drwxr-xr-x 2 root root 6 5月 26 17:05 test
#可以看到,檔案已經刪除了
fetch模組
該模組用於從遠端某主機獲取(複製)檔案到本地,有兩個選項:
- dest:用於存放檔案的目錄
- src:在遠端拉取的檔案,並且只能是檔案,不能是目錄
[root@k8s-master ~]# ansible k8s -m fetch -a "src=/home/111.txt dest=/home"
192.168.133.11 | CHANGED => {
"changed": true,
"checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"dest": "/home/192.168.133.11/home/111.txt",
"md5sum": "5be6f09789e8a48c5b3f3522ee3672e2",
"remote_checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"remote_md5sum": null
}
192.168.133.12 | CHANGED => {
"changed": true,
"checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"dest": "/home/192.168.133.12/home/111.txt",
"md5sum": "5be6f09789e8a48c5b3f3522ee3672e2",
"remote_checksum": "f02a1a9239ee5ca965dd62094efd84744356dc6e",
"remote_md5sum": null
}
#驗證
[root@k8s-master ~]# cd /home/192.168.133.11/home/
[root@k8s-master home]# ls
111.txt
[root@k8s-master home]# pwd
/home/192.168.133.11/home
注意:檔案儲存的路徑在我們設定的接收目錄下的被管控主機IP目錄下
corn模組
該模組適用於管理cron
計劃任務的
其使用的語法和我們crontab
檔案中的語法一種,同時,可以指定以下選項:
- day=:日期
- hour=:小時
- minute=:分鐘
- month=:月份
- weekday=:周
- job=:指明執行的命令
- name=:定時任務描述
- reboot:任務在重啟時執行,不建議使用,建議使用special_time
- special_time:特殊的時間範圍,引數:reboot(重啟時)、annually(每年)、monthly(每月)、weekly(每週)、daily(每天)、hourly(每小時)
- state:指明狀態,present:新增定時任務(預設設定)、absent:刪除定時任務
- user:以哪個使用者的身份執行、
ps:
1、crontab檔案格式:
* * * * * command
minute hour day month week
- minute:表示分鐘,可以是0~59之間的任何整數
- hour:表示小時,可以是0~23之間的任何整數
- day:表示日期,可以是從1~31之間的任何整數
- month:表示月份,可以是從1到12之間的任何整數
- week:表示星期幾,可以是從0~7之間的任何整數,這裡的0或7代表週日
- command:要執行的命令,可以是系統命令,也可以是自己編寫的指令碼檔案
2、特殊字元:
星號(*):代表所有可能的值,例如month欄位如果是星號,則表示在滿足其他欄位的制約條件後每月都執行該命令操作
逗號(,):可以用逗號隔開的值指定一個列表範圍,如“1,2,5,7,8,9”
中劃線(-):可以用整數之間的中劃線表示一個整數範圍,如“2-6”表示“2,3,4,5,6”
正斜線(/):可以用正斜線指定時間的間隔頻率,例如“0-23/2”表示每兩個小時執行一次;同時正斜線可以和星號一起使用,如:*/10
#新增定時任務
[root@k8s-master home]# ansible k8s -m cron -a "name='ntp update every 5 min' minute=*/5 job='/sbin/ntpdate 172.17.0.1 &> /dev/null'"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"ntp update every 5 min"
]
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"ntp update every 5 min"
]
}
#驗證
[root@k8s-master home]# ansible k8s -m shell -a "crontab -l"
192.168.133.12 | CHANGED | rc=0 >>
* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null
192.168.133.11 | CHANGED | rc=0 >>
* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null
###可以看到計劃任務已經提交成功了
#刪除定時任務
[root@k8s-master home]# ansible k8s -m cron -a "name='ntp update every 5 min' minute=*/5 job='/sbin/ntpdate 172.17.0.1 &> /dev/null' state=absent"
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
#驗證
[root@k8s-master home]# ansible k8s -m shell -a "crontab -l"
192.168.133.12 | CHANGED | rc=0 >>
* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org
192.168.133.11 | CHANGED | rc=0 >>
* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org
###可以看到剛剛新增的定時任務已經刪除了
yum模組
該模組主要用於軟體的安裝,其選項如下:
- name:所安裝的包的名稱
- state:
- present:安裝
- latest:安裝最新的
- absent:解除安裝軟體
- update_cache:強制更新yum快取
- conf_file:指定遠端yum安裝時所依賴的配置檔案(安裝本地已有的包)
- disable_pgp_check:是否禁止GPG checking,只用於
present
或者latest
- disablerepo:臨時禁止使用yum庫。只用於安裝或更新時
- enablerepo:臨時使用yum庫。只用於安裝或更新時
#安裝
[root@k8s-master ~]# ansible k8s -m yum -a "name=htop state=latest"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"htop"
],
"updated": []
},
"msg": "warning: /var/cache/yum/x86_64/7/epel/packages/htop-2.2.0-3.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY\nImporting GPG key 0x352C64E5:\n Userid : \"Fedora EPEL (7) <[email protected]>\"\n Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5\n Package : epel-release-7-11.noarch (@extras)\n From : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7\n",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.njupt.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n htop x86_64 2.2.0-3.el7 epel 103 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 103 k\nInstalled size: 218 k\nDownloading packages:\nPublic key for htop-2.2.0-3.el7.x86_64.rpm is not installed\nRetrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : htop-2.2.0-3.el7.x86_64 1/1 \n Verifying : htop-2.2.0-3.el7.x86_64 1/1 \n\nInstalled:\n htop.x86_64 0:2.2.0-3.el7 \n\nComplete!\n"
]
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"htop"
],
"updated": []
},
"msg": "http://hk.mirrors.thegigabit.com/epel/7/x86_64/Packages/h/htop-2.2.0-3.el7.x86_64.rpm: [Errno 12] Timeout on http://hk.mirrors.thegigabit.com/epel/7/x86_64/Packages/h/htop-2.2.0-3.el7.x86_64.rpm: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds')\nTrying other mirror.\nhttp://my.mirrors.thegigabit.com/epel/7/x86_64/Packages/h/htop-2.2.0-3.el7.x86_64.rpm: [Errno -1] Package does not match intended download. Suggestion: run yum --enablerepo=epel clean metadata\nTrying other mirror.\nhttps://download.nus.edu.sg/mirror/epel/7/x86_64/Packages/h/htop-2.2.0-3.el7.x86_64.rpm: [Errno -1] Package does not match intended download. Suggestion: run yum --enablerepo=epel clean metadata\nTrying other mirror.\nwarning: /var/cache/yum/x86_64/7/epel/packages/htop-2.2.0-3.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY\nImporting GPG key 0x352C64E5:\n Userid : \"Fedora EPEL (7) <[email protected]>\"\n Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5\n Package : epel-release-7-11.noarch (@extras)\n From : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7\n",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.tuna.tsinghua.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n htop x86_64 2.2.0-3.el7 epel 103 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 103 k\nInstalled size: 218 k\nDownloading packages:\nPublic key for htop-2.2.0-3.el7.x86_64.rpm is not installed\nRetrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : htop-2.2.0-3.el7.x86_64 1/1 \n Verifying : htop-2.2.0-3.el7.x86_64 1/1 \n\nInstalled:\n htop.x86_64 0:2.2.0-3.el7 \n\nComplete!\n"
]
}
service模組
該模組用於服務程式的管理。其主要選項如下:
- arguments:命令列提供額外的引數
- enabled:設定開機啟動
- name:服務名稱
- runlevel:開機啟動的級別,一般不用指定
- sleep:在重啟服務的過程中,是否等待。如在服務關閉以後等待2秒再啟動。(定義在劇本中)
- state:有四種狀態,分別為:
- started:啟動服務
- stopped:停止服務
- restarted:重啟服務
- reloaded:過載配置
#開啟服務並設定自啟動
[root@server ~]# ansible web -m service -a 'name=nginx state=started enabled=true'
192.168.37.122 | SUCCESS => {
"changed": true,
"enabled": true,
"name": "nginx",
"state": "started",
……
}
192.168.37.133 | SUCCESS => {
"changed": true,
"enabled": true,
"name": "nginx",
"state": "started",
……
}
#驗證,檢視埠是否開啟
[root@server ~]# ansible web -m shell -a 'ss -ntl'
192.168.37.122 | SUCCESS | rc=0 >>
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
192.168.37.133 | SUCCESS | rc=0 >>
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
###可以看出我們的80埠已經開啟。
#關閉服務
[root@server ~]# ansible web -m service -a 'name=nginx state=stopped'
192.168.37.122 | SUCCESS => {
"changed": true,
"name": "nginx",
"state": "stopped",
……
}
192.168.37.133 | SUCCESS => {
"changed": true,
"name": "nginx",
"state": "stopped",
……
}
#驗證
[root@server ~]# ansible web -m shell -a 'ss -ntl | grep 80'
192.168.37.122 | FAILED | rc=1 >>
192.168.37.133 | FAILED | rc=1 >>
###可以看出,我們已經沒有80埠了,說明我們的nginx服務已經關閉了。
user模組
該模組主要用於管理使用者賬號,其主要選項如下:
- comment:使用者的描述資訊
- createhome:是否建立家目錄
- force:在使用state=absent時,執行與userdel-force一致
- group:指定基本組
- groups:指定附加組,如果指定為(groups=)表示刪除所有組
- home:指定使用者家目錄
- move_home:如果設定為home=時,試圖將使用者主目錄移動到指定的目錄
- name:指定使用者名稱
- non_unique:該選項允許改變非唯一的使用者ID值
- password:指定使用者密碼
- remove:在使用state=absent時,行為是與userdel-remove一致
- shell:指定預設shell
- state:設定賬號狀態,不指定則表示建立,指定值為absent表示刪除
- system:當建立一個使用者,設定這個使用者是系統使用者。這個設定不能更改現有使用者
- uid:指定使用者的uid
#新增一個使用者並指定其uid
[root@k8s-master ~]# ansible k8s -m user -a "name=test uid=11111"
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 11111,
"home": "/home/test",
"name": "test",
"shell": "/bin/bash",
"state": "present",
"stderr": "useradd:警告:此主目錄已經存在。\n不從 skel 目錄裡向其中複製任何檔案。\n",
"stderr_lines": [
"useradd:警告:此主目錄已經存在。",
"不從 skel 目錄裡向其中複製任何檔案。"
],
"system": false,
"uid": 11111
}
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 11111,
"home": "/home/test",
"name": "test",
"shell": "/bin/bash",
"state": "present",
"stderr": "useradd:警告:此主目錄已經存在。\n不從 skel 目錄裡向其中複製任何檔案。\n",
"stderr_lines": [
"useradd:警告:此主目錄已經存在。",
"不從 skel 目錄裡向其中複製任何檔案。"
],
"system": false,
"uid": 11111
}
#驗證:檢視使用者是否已新增
[root@k8s-master ~]# ansible k8s -m shell -a "cat /etc/group | grep test"
192.168.133.12 | CHANGED | rc=0 >>
test:x:11111:
192.168.133.11 | CHANGED | rc=0 >>
test:x:11111:
[root@k8s-master ~]# ansible k8s -m shell -a "cat /etc/passwd | grep test"
192.168.133.11 | CHANGED | rc=0 >>
test:x:11111:11111::/home/test:/bin/bash
192.168.133.12 | CHANGED | rc=0 >>
test:x:11111:11111::/home/test:/bin/bash
#刪除使用者
[root@k8s-master ~]# ansible k8s -m user -a "name=test uid=11111 state=absent"
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "test",
"remove": false,
"state": "absent"
}
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "test",
"remove": false,
"state": "absent"
}
#驗證,檢視使用者是否已刪除
[root@k8s-master ~]# ansible k8s -m shell -a "cat /etc/passwd | grep test"
192.168.133.12 | FAILED | rc=1 >>
non-zero return code
192.168.133.11 | FAILED | rc=1 >>
non-zero return code
group模組
該模組主要用於新增或刪除組,常用的選項如下:
- gid=:設定組的GID號
- name=:指定組的名稱
- state=:指定組的狀態,預設為建立,設定值為absent表示刪除
- system=:設定值為yes,表示建立系統組
#建立組
[root@k8s-master ~]# ansible k8s -m group -a "name=sanguo gid=22222"
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 22222,
"name": "sanguo",
"state": "present",
"system": false
}
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 22222,
"name": "sanguo",
"state": "present",
"system": false
}
#驗證:檢視組是否存在
[root@k8s-master ~]# ansible k8s -m shell -a "cat /etc/group | grep sanguo"
192.168.133.11 | CHANGED | rc=0 >>
sanguo:x:22222:
192.168.133.12 | CHANGED | rc=0 >>
sanguo:x:22222:
#刪除組
[root@k8s-master ~]# ansible k8s -m group -a "name=sanguo gid=22222 state=absent"
192.168.133.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "sanguo",
"state": "absent"
}
192.168.133.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "sanguo",
"state": "absent"
}
#驗證,檢視組是否以刪除
[root@k8s-master ~]# ansible k8s -m shell -a "cat /etc/group | grep sanguo"
192.168.133.12 | FAILED | rc=1 >>
non-zero return code
192.168.133.11 | FAILED | rc=1 >>
non-zero return code
script模組
該模組用於將本機的指令碼在被管控主機上執行。該模組直接指定指令碼的執行路徑即可
#在主機上新增一個test.sh指令碼
[root@k8s-master ~]# vim test.sh
[root@k8s-master ~]# cat test.sh
#!/bin/bash
echo "Hello Torres"
#給test.sh指令碼新增許可權
#ansible執行
[root@k8s-master ~]# ansible k8s -m script -a "/root/test.sh"
192.168.133.11 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.133.11 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.133.11 closed."
],
"stdout": "Hello Torres\r\n",
"stdout_lines": [
"Hello Torres"
]
}
192.168.133.12 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.133.12 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.133.12 closed."
],
"stdout": "Hello Torres\r\n",
"stdout_lines": [
"Hello Torres"
]
}
setup模組
該模組主要用於收集資訊,是通過呼叫facts元件來實現的。facts元件是Ansible用於採集被管控主機資訊的一個功能,可以使用setup模組檢視機器的所有facts資訊,可以使用filter來檢視指定資訊。整個facts資訊被包裝在一個json格式的資料結構中,ansible_facts是最上層的值。
facts就是變數,內建變數。每個主機的各種資訊,cpu顆數、記憶體大小等。會存在facts中的某個變數中。呼叫後返回很多對應主機的資訊。
#檢視資訊
#檢視記憶體
[root@k8s-master ~]# ansible k8s -m setup -a "filter='*mem*'"
192.168.133.12 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 67,
"ansible_memory_mb": {
"nocache": {
"free": 518,
"used": 454
},
"real": {
"free": 67,
"total": 972,
"used": 905
},
"swap": {
"cached": 0,
"free": 0,
"total": 0,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.133.11 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 61,
"ansible_memory_mb": {
"nocache": {
"free": 529,
"used": 443
},
"real": {
"free": 61,
"total": 972,
"used": 911
},
"swap": {
"cached": 0,
"free": 0,
"total": 0,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
#驗證,檢視記憶體大小是否一致
[root@k8s-master ~]# ansible k8s -m shell -a "free -m"
192.168.133.11 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 411 69 14 491 406
Swap: 0 0 0
192.168.133.12 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 422 64 14 485 395
Swap: 0 0 0
#儲存資訊
###setup模組還有一個很好用的功能就是可以儲存我們所篩選的資訊至我們的主機上,同時,檔名為我們被管制的主機的IP,這樣方便我們知道是哪臺機器出的問題
[root@k8s-master ~]# ansible k8s -m setup -a "filter='*mem*'" --tree /tmp/facts
192.168.133.11 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 67,
"ansible_memory_mb": {
"nocache": {
"free": 528,
"used": 444
},
"real": {
"free": 67,
"total": 972,
"used": 905
},
"swap": {
"cached": 0,
"free": 0,
"total": 0,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.133.12 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 70,
"ansible_memory_mb": {
"nocache": {
"free": 517,
"used": 455
},
"real": {
"free": 70,
"total": 972,
"used": 902
},
"swap": {
"cached": 0,
"free": 0,
"total": 0,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
#驗證:檢視主機上對應目錄下的內容
[root@k8s-master ~]# cd /tmp/facts/
[root@k8s-master facts]# ls
192.168.133.11 192.168.133.12
[root@k8s-master facts]# ll
總用量 8
-rw-r--r-- 1 root root 311 5月 27 11:08 192.168.133.11
-rw-r--r-- 1 root root 311 5月 27 11:08 192.168.133.12
[root@k8s-master facts]# cat 192.168.133.11
{"ansible_facts": {"ansible_memfree_mb": 67, "ansible_memory_mb": {"nocache": {"free": 528, "used": 444}, "real": {"free": 67, "total": 972, "used": 905}, "swap": {"cached": 0, "free": 0, "total": 0, "used": 0}}, "ansible_memtotal_mb": 972, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}