Ansible 入門學習筆記

ansible 學習筆記

本文 的主要內容來自ansible官網書籍python

本文采用vagrant軟件基於VirtualBox的虛擬機進行自動化管理,先要安裝VirtualBox和vagrant兩個軟件。
相似Docker有Dockerfile, Jenkins有Jenkinsfile, Vagrant也有本身的Vagrantfile, Vagrantfile是用Ruby語言寫成的。mysql

注意:這幾種配置文件的使用方式相似,命名都是首字母大寫的無擴展名文件。

vagrant: 流浪 stray, wandering, wanderings, vagrant, vagabonds, strayedgit

配置環境

建立工做目錄sql

$ mkdir -p ~/ansible/vms
$ cd ~/ansible/vms
$ ls

下面放兩個文件:
hosts Vagrantfile
文件內容:shell

$ cat hosts

輸出:django

# Lines beginning with a # are comments, and are only included for
# illustration. These comments are overkill for most inventory files.
# Application servers
[app]
192.168.60.4
192.168.60.5
# Database server
[db]
192.168.60.6
# Group 'multi' with all servers
[multi:children]
app
db
# Variables that will be applied to all servers
[multi:vars]
ansible_ssh_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
$ cat Vagrantfile

輸出:centos

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
    # General Vagrant VM configuration.
    config.vm.box = "geerlingguy/centos7"
    config.ssh.insert_key = false
    config.vm.synced_folder ".", "/vagrant", disabled: true
    config.vm.provider :virtualbox do |v|
        v.memory = 256
        v.linked_clone = true
    end

    # Application server 1.
    config.vm.define "app1" do |app|
        app.vm.hostname = "orc-app1.dev"
        app.vm.network :private_network, ip: "192.168.60.4"
    end

    # Application server 2.
    config.vm.define "app2" do |app|
        app.vm.hostname = "orc-app2.dev"
        app.vm.network :private_network, ip: "192.168.60.5"
    end

    # Database server.
    config.vm.define "db" do |db|
        db.vm.hostname = "orc-db.dev"
        db.vm.network :private_network, ip: "192.168.60.6"
    end
end

下載虛擬機鏡像

$ vagrant box add "geerlingguy/centos7"

按Vagrantfile來初始化虛擬機:ruby

$ vagrant up
$ vagrant provision

若是都安裝好了,能夠ping一下試試服務器

$ ansible app -a 'ping -c 1 baidu.com'

192.168.60.5 | SUCCESS | rc=0 >>
PING baidu.com (220.181.38.148) 56(84) bytes of data.
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=1 ttl=63 time=2.54 ms

--- baidu.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 2.541/2.541/2.541/0.000 ms

192.168.60.4 | SUCCESS | rc=0 >>
PING baidu.com (220.181.38.148) 56(84) bytes of data.
64 bytes from 220.181.38.148 (220.181.38.148): icmp_seq=1 ttl=63 time=3.11 ms

--- baidu.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 3.116/3.116/3.116/0.000 ms

由於以測試都是以hosts文件中的inventory定義爲基礎,因此能夠建一個alias ansible='ansible -i hosts', 避免每次都輸入 -i hosts參數。爲便於讀者複製粘貼,如下ansible命令前再也不重複命令行提示符$網絡

還能夠作一此測試,如安裝時間服務:

ansible multi -a "hostname" -f 1
ansible multi -f 1 -a "hostname" 
ansible multi -a "df -h"
ansible multi -a "free -m -h "
ansible multi -a "date"
ansible multi -m setup
ansible multi -s -m yum -a "name=ntp state=present"
ansible multi -a "date"
ansible multi -s -m service  -a "name=ntpd state=started enabled=yes"
ansible multi -s  -a "service ntpd stop"
ansible multi -s -a "ntpdate -q 0.rhel.pool.ntp.org"
ansible multi -s -a "service ntpd start"

ansible 默認是在多臺服務器上並行執行操做的, 能夠經過 --forks <N>參數指定並行度。N=1,採用串行方式執行。

  • -m參數是指定 ansible 的模塊名稱,模塊採用狀態聲明的方式,強調操做的冪等性,即次操做與一次操做的最終結果是同樣的。
  • -s參數是--sudo的縮寫。即以 root 用戶身份執行操做。

安裝軟件

ansible app -s -m yum -a "name=MySQL-python state=present"
ansible app -s -m yum -a "name=python-setuptools state=present"
ansible app -s -m easy_install -a "name=django state=present"

#在我機器上由於用 easy_install 安裝 django 因 python 版本沒有成功,後改成 pip3安裝。

ansible app -s -m yum -a "name=python3-pip state=present"
ansible app -s -m pip -a "name=django state=present"

測試 django

ansible app -a "python3 -c 'import django; print(django.get_version())'"
192.168.60.4 | SUCCESS | rc=0 >>
2.2.5

192.168.60.5 | SUCCESS | rc=0 >>
2.2.5

安裝MySQL

ansible  db -s -m yum -a "name=mariadb-server state=present"
ansible  db -s -m service -a "name=mariadb state=started enabled=yes"
ansible  db -s -a "iptables -F"
ansible  db -s -a "iptables -A INPUT -s 192.168.60.0/24 -p tcp -m tcp --dport 3306 -j ACCEPT"

設置MySQL

ansible  db -s -m yum -a "name=MySQL-python state=present"
ansible  db -s -m mysql_user -a "name=django host=% password=12345 priv=*.*:ALL state=present"

經常使用操做一覽

檢查服務狀態

ansible app -s -a "service ntpd status"

只檢查一臺機器

ansible app -s -a "service ntpd restart" --limit "192.168.60.4"

正則匹配~

ansible app -s -a "service ntpd restart" --limit ~".*\.4"

建組

ansible app -s -m group -a "name=admin state=present"

刪除組

ansible app -s -m group -a "name=admin state=absent"

建用戶

ansible app -s -m user -a "name=johndoe group=admin createhome=yes"

若是要爲新用戶自動建立 SSH 密鑰(若是不存在的話),您可使用參數generate_ssh_key=yes。您還能夠經過傳入 uid=[uid],來設置用戶的 UID,shell=[shell]設置用戶外殼 ,password=[encryptedpassword] 設置密碼 等。

刪除用戶

ansible app -s -m user -a "name=johndoe state=absent remove=yes"

系統無關的包安裝

ansible app -s -m package -a "name=git state=present"

狀態檢查

ansible multi -m stat -a "path=/etc/environment"

拷貝文件

ansible multi -m copy -a "src=/etc/hosts dest=/tmp/hosts"

下載(會產生以host/ip目錄開頭的多個文件)

ansible multi -s -m fetch -a "src=/etc/hosts dest=/tmp"

後臺執行

  • -B <seconds>: 指定最多用時。
  • -P <seconds>:指定任務執行狀態的更新時間。默認10秒。
ansible multi -s -B 3600 -a "yum -y update"

啓動就不理的長時任務

ansible multi -B 3600 -P 0 -a "/path/to/fire-and-forget-script.sh"

檢查日誌文件

ansible執行完後回顯輸出,因此不適合跟蹤大量的文本輸出。

ansible multi -s -a "tail /var/log/messages"
#或
ansible multi -s -m shell -a "tail /var/log/messages | \
grep ansible-command | wc -l"

克隆任務執行

增長每日定時任務

ansible multi -s -m cron -a "name='daily-cron-all-servers' \
hour=4 job='/path/to/daily-script.sh'"

去掉任務

ansible multi -s -m cron -a "name='daily-cron-all-servers' \
state=absent"

git

ansible package -s -m yum -a "name=git state=present".
ansible app -s -m git -a "repo=git://example.com/path/to/repo.git dest=/opt/myapp update=yes version=1.2.4"

ansible 執行加速

SSH pipelining

SSH pipelining 是一個加速 Ansible 執行速度的簡單方法。ssh pipelining 默認是關閉,之因此默認關閉是爲了兼容不一樣的 sudo 配置,主要是 requiretty 選項。此選項能夠減小 ansible 執行沒有傳輸時 ssh 在被控機器上執行任務的鏈接數。若是使用 sudo,必須關閉 requiretty 選項。修改 /etc/ansible/ansible.cfg 文件能夠開啓 pipelining

pipelining=False

修改成

pipelining=True

修改完後,能夠批量對機器執行命令試下,能夠明顯感覺到速度的提高。

ControlPersist

ControlPersist 特性須要高版本的 SSH 才支持,CentOS 6 默認是不支持的,若是須要使用,須要自行升級 openssh。ControlPersist 即持久化 socket,一次驗證,屢次通訊。而且只須要修改 ssh 客戶端就行。

ControlPersist 設置的辦法:

cat ~/.ssh/config 
 Host * 
  Compression yes 
  ServerAliveInterval 60 
  ServerAliveCountMax 5 
  ControlMaster auto 
  ControlPath ~/.ssh/sockets/%r@%h-%p
  ControlPersist 4h

在開啓了 ControlPersist 特性後,SSH 在創建了 sockets 以後,節省了每次驗證和建立的時間。在網絡情況不是特別理想時,帶來的性能提高是很是可觀的。

小結

以上是 ansible 的一些初步使用展現。更高級的 playbook 用法沒有涉及到。

相關文章
相關標籤/搜索