Ansible-1 基本認識及清單與模組

  • 2020 年 3 月 16 日
  • 筆記

ansible

一、常用的自動化運維工具

1、puppet

基於ruby開發,採用c/s架構,擴展性強,基於ssl,遠程命令執行相對較弱,

2、saltstack

基於python開發,採用C/S架構,相對puppet更輕量級,配置語法使用YMAL,使得配置腳本更簡單

3、ansible

基於python paramiko開發,無需客戶端,輕量級,配置語法使用YMAL及jinjia2模板語言,更強的遠程命令執行操作
https://docs.ansible.com/ansible/latest/index.html

二、ansible能做什麼

1、ansible能做什麼

完成一些批量任務,或者是重複性工作。

例子1
在100台伺服器上部署nginx服務並且安裝後啟動。
例子2
在100台伺服器上創建賬戶,拷貝文件

2、腳本vs ansible

有些腳本也可以滿足例子1、2,但是ansible還支援一些優秀的特性,如冪等性(例子,拷貝文件到某主機目錄上,但是不確定存不存在)ansible會自定判斷是否存在此文件,所以ansible是以結果為導向判斷當前狀態是不是目標狀態一致,如果不一致就改為目標狀態,一致就不進行操作,這個就是ansible的冪等性。

3、ansible依賴ssh即可工作

用過puppet的一定知道,puppet客戶端需要裝agent才可以配合master工作,而ansible只需要依賴ssh即可

三、ansible工作機制

ansible在管理節點將ansible模組通過SSH協議(或者kerberos、LDAP)推送到被管理端執行,執行之後自動刪除,可以使用SVN等來管理自定義模組及編排

1、架構圖示

2、組成

ansible:核心
modules:包括ansible自帶的核心模組及自定義模組
plugins:完成模組功能的補充,包括連接插件、郵件插件等
playbooks:一般翻譯為劇本,可以理解為編排,是定義ansible多任務配置文件,由ansible自行執行
inventory:定義ansible管理主機的清單

四、ansible安裝

1、環境

主機名 IP 系統版本 備註
ansible 10.211.55.5 centos-7.6 ansible-2.9.3
test1 10.211.55.6 centos-7.6
Test2 10.211.55.7 centos-7.6

2、安裝軟體

yum install epel-release  yum install ansible

安裝了如下依賴:

Dependencies Resolved    ===============================================================================   Package                              Arch    Version            Repository                                                                            Size  ===============================================================================  Installing:   ansible                              noarch  2.9.3-1.el7        epel     17 M  Installing for dependencies:   PyYAML                               x86_64  3.10-11.el7        base    153 k   libyaml                              x86_64  0.1.4-11.el7_0     base     55 k   python-babel                         noarch  0.9.6-8.el7        base    1.4 M   python-backports                     x86_64  1.0-8.el7          base    5.8 k   python-backports-ssl_match_hostname  noarch  3.5.0.1-1.el7      base     13 k   python-cffi                          x86_64  1.6.0-5.el7        base    218 k   python-enum34                        noarch  1.0.4-1.el7        base     52 k   python-httplib2                      noarch  0.9.2-1.el7        extras  115 k   python-idna                          noarch  2.4-1.el7          base     94 k   python-ipaddress                     noarch  1.0.16-2.el7       base     34 k   python-jinja2                        noarch  2.7.2-4.el7        base    519 k   python-markupsafe                    x86_64  0.11-10.el7        base     25 k   python-paramiko                      noarch  2.1.1-9.el7        base    269 k   python-ply                           noarch  3.4-11.el7         base    123 k   python-pycparser                     noarch  2.14-1.el7         base    104 k   python-setuptools                    noarch  0.9.8-7.el7        base    397 k   python-six                           noarch  1.9.0-2.el7        base     29 k   python2-cryptography                 x86_64  1.7.2-2.el7        base    502 k   python2-jmespath                     noarch  0.9.0-3.el7        extras   39 k   python2-pyasn1                       noarch  0.1.9-7.el7        base    100 k   sshpass                              x86_64  1.06-2.el7         extras   21 k    Transaction Summary  ===============================================================================  Install  1 Package (+21 Dependent packages)  

3、配置主機清單-添加ssh資訊的方式

ansible 通過讀取默認的主機清單配置/etc/ansible/hosts,可以同時連接到多個遠程主機上執行任務默認路徑可以通過修改ansible.cfg的hostfile參數指定的路徑。

1)添加主機

配置文件/etc/ansible/hosts

cat /etc/ansible/hosts |grep 10.211*
vim /etc/ansible/hosts

......  10.211.55.6 ansible_port=22 ansible_user=root ansible_ssh_pass=111111  ......

注意:這裡還可以添加別名的方法:test1 ansible_host=10.211.55.6 ansible_port=22 ansible_user=root ansible_ssh_pass=111111

2)執行查看返回結果

ansible 10.211.55.6 -m ping

10.211.55.6 | SUCCESS => {      "ansible_facts": {          "discovered_interpreter_python": "/usr/bin/python"      },      "changed": false,      "ping": "pong"  }

3)如ssh不同則是

ansible 10.211.55.6 -m ping

The authenticity of host '10.211.55.6 (10.211.55.6)' can't be established.  ECDSA key fingerprint is SHA256:m1VnZbagJ8pJphMISxwjZSwJ7YhdEwA1nC7awJXJ6t0.  ECDSA key fingerprint is MD5:27:b6:32:8b:fd:d7:e7:af:a6:75:c3:bc:4c:0b:68:b2.  Are you sure you want to continue connecting (yes/no)? yes  10.211.55.6 | UNREACHABLE! => {      "changed": false,      "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.211.55.6' (ECDSA) to the list of known hosts.rnPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",      "unreachable": true  }  

4、配置主機清單-ssh免密登錄方式

ssh認證方式可以是密碼認證和秘鑰認證,為了提高安全性,通常使用秘鑰認證,可以在管理機中生成秘鑰,然後通過公鑰認證的方式連接到對應的受管主機。

1)、執行ssh-keygen命令

ssh-keygen -t rsa //生成秘鑰對,也就是私鑰與公鑰

例子:

ssh-keygen -t rsa  Generating public/private rsa key pair.  Enter file in which to save the key (/root/.ssh/id_rsa):  Enter passphrase (empty for no passphrase):  Enter same passphrase again:  Your identification has been saved in /root/.ssh/id_rsa.  Your public key has been saved in /root/.ssh/id_rsa.pub.  The key fingerprint is:  SHA256:hwxorgSBRIj3a0zOdXUJWnhjY8f7ZzQT4hMVHjfUIRE root@ansible  The key's randomart image is:  +---[RSA 2048]----+  |Bo       .oo E=B=|  |+..  .  .oB =oo.=|  |.. .o . .= =..o..|  | . oo .o..  .o o.|  |  .=.o .S .  ...o|  | . .*    .    . o|  |  ..           o |  |                 |  |                 |  +----[SHA256]-----+

2)、拷貝文件

scp /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys

5、還可以將生成公鑰加入55.6的認證列表裡

ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

6、修改配置文件並進行測試

配置文件
vim /etc/ansible/hosts
10.211.55.6 ansible_port=22 //因為已經進行免密登錄,這裡指定主機ip及埠即可
cat /etc/ansible/hosts |grep 10.211
測試
ansible 10.211.55.6 -m ping

10.211.55.6 | SUCCESS => {      "ansible_facts": {          "discovered_interpreter_python": "/usr/bin/python"      },      "changed": false,      "ping": "pong"  }

7、清單分組功能

還可以為一個組指定變數,組內每個主機都可以使用,相同主機可以分配到不同的組,可以按照功能、系統、等進行分類,便於對某些主機貨者某一組功能相同的主機進行操作

vim /etc/ansible/hosts

[test-a]  10.211.55.6 ansible_port=22  [test-b]  10.211.55.7 ansible_port=22  [test]  10.211.55.6  10.211.55.7

測試

ansible test -m ping

[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters in group names by default, this will change, but still be user  configurable on deprecation. This feature will be removed in version 2.10. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.  [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details    10.211.55.6 | SUCCESS => {      "ansible_facts": {          "discovered_interpreter_python": "/usr/bin/python"      },      "changed": false,      "ping": "pong"  }  10.211.55.7 | SUCCESS => {      "ansible_facts": {          "discovered_interpreter_python": "/usr/bin/python"      },      "changed": false,      "ping": "pong"  }

8、使用YAML語言的配置語法書寫hosts

什麼是YAML語言那,就是"YAML Ain’t a Markup Language",他不是一種標記語言但是如果掌握XML這用標記語言也是可以很快學會YAML

1)使用YAML語言書寫hosts

vim hosts  all:   children:    test:     children:      testA:       hosts:        10.211.55.6:      testB:       hosts:        10.211.55.7:

2)拆分主機和組專用數據

當host和group定義一些比較複雜的變數時,可以用單獨文件保存host和group變數,以YAML格式書寫變數,避免都寫在hosts文件比較混亂

二、ansible模組使用

1、查看使用方法

比如剛才的ping就需要使用ping模組,ansible還提供很多模組,可以通過命令查看有哪些?
ansible-doc -l //查看ansible都有哪些模組
ansible-doc -s ping //獲取ping模組的詳細使用方法
ansible-doc -s fetch //獲取fetch拉取模組的詳細使用方法

- name: Fetch files from remote nodes    fetch:        dest:                  # (required) A directory to save the file into.                                 For example, if                                 the `dest'                                 directory is                                 `/backup' a `src'                                 file named                                 `/etc/profile' on                                 host `host.exampl                                 e.com', would be                                 saved into `/back                                 up/host.example.c                                 om/etc/profile'.                                 The host name is                                 based on the                                 inventory name.        fail_on_missing:       # When set to `yes', the task will fail if the                                 remote file                                 cannot be read                                 for any reason.                                 Prior to Ansible                                 2.5, setting this                                 would only fail                                 if the source                                 file was missing.                                 The default was                                 changed to `yes'                                 in Ansible 2.5.        flat:                  # Allows you to override the default behavior of                                 appending hostnam                                 e/path/to/file to                                 the destination.                                 If `dest' ends                                 with '/', it will                                 use the basename                                 of the source                                 file, similar to                                 the copy module.                                 This can be

2、Files modules-fetch

ansible testA -m fetch -a "src=/etc/fstab dest=/testdir/ansible/"
注意:運行兩次就可以看到ansible冪等性,第一遍為黃色-修改後第二遍為綠色-成功changed欄位有變化,如果是紅色-代表失敗

10.211.55.6 | CHANGED => {      "changed": true,      "checksum": "1e4b62ac91bdadeb0d07b8b2f7d8dc184f807fd6",      "dest": "/testdir/ansible/10.211.55.6/etc/fstab",      "md5sum": "19a888135cfae98fa7fc0d21ea8ef848",      "remote_checksum": "1e4b62ac91bdadeb0d07b8b2f7d8dc184f807fd6",      "remote_md5sum": null  }
10.211.55.6 | SUCCESS => {      "changed": false,      "checksum": "1e4b62ac91bdadeb0d07b8b2f7d8dc184f807fd6",      "dest": "/testdir/ansible/10.211.55.6/etc/fstab",      "file": "/etc/fstab",      "md5sum": "19a888135cfae98fa7fc0d21ea8ef848"
檢查文件的目錄

tree /testdir/ansible

/testdir/ansible  └── 10.211.55.6      └── etc          └── fstab    2 directories, 1 file

3、Files modules-copy

使用方法:

- name: Copy files to remote locations    copy:        attributes:        backup:創建一個包含時間戳的備份文件,這樣,如果某種方式錯誤地處理了原始文件,就可以重新獲得原始文件        checksum:傳輸的文件校驗和,用於驗證文件的副本是否成功        content:當不適用src時,將文件內容直接設置為指定的值,只有當』dest『是一個文件時才能工作,如果文件不存在,就創建改文件        decrypt:使用vault控制源文件的自動解密        dest:文件複製到遠程絕對路徑        directory_mode:進行遞歸複製時,設置目錄的模式,如果沒有則使用默認        follow:如果目標文件系統鏈接存在就遵循他們        force:影響遠程文件是否必須總是被替換。如果是,當內容與源文件不同時,遠程文件將被替換。如果是「否」,則只有在目的地不存在的情況下才會傳輸文件。        group:指定文件屬組,遠程主機上必須有對應的組        local_follow:遵循源文件系統鏈接        mode:指定文件拷貝到遠程主機後的許可權,如果想講許可權設置為「rw-rw--r--」,就可以使用mode=0664,也可以使用mode=u+x表示        owner:指定文件拷貝到遠程主機的屬主,遠程主機上必須有對應的用戶        remote_src:        selevel:        serole:        setype:        seuser:        src:用於指定需要copy的文件或目錄        unsafe_writes:        validate:           

ansible testA -m copy -a 'content="aaanbbbn" dest=/opt/test'

10.211.55.6 | CHANGED => {      "ansible_facts": {          "discovered_interpreter_python": "/usr/bin/python"      },      "changed": true,      "checksum": "90c206af0bfefa95541d3e724efe1dbc1ed3877f",      "dest": "/opt/test",      "gid": 0,      "group": "root",      "md5sum": "8b652b8c79f357694a04bd793f533c96",      "mode": "0644",      "owner": "root",      "size": 8,      "src": "/root/.ansible/tmp/ansible-tmp-1581719905.88-143348935084249/source",      "state": "file",      "uid": 0  }

轉載請註明出處: https://www.cnblogs.com/zhangxingeng/p/12503376.html