Linux自動化運維工具之Ansible綜合使用案例


1、 管理機部署

1.1 創建項目、安裝相關命令

[root@m1 ~]# mkdir project  # 創建項目目錄
[root@m1 ~]# yum install wget -y  # 安裝wget命令
[root@m1 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo  # 配置epel源
[root@m1 ~]# yum install ansible -y  # 安裝ansible
[root@m1 ~]# ansible -m ping  # 監測ansible是否安裝成功

1.2 修改主機清單調試所有機器

[root@m1 ~]# vim /etc/ansible/hosts  # 修改主機文件
[web01]
192.168.15.7 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[web02]
192.168.15.8 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[web03]
192.168.15.9 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[web:children]
web01
web02
web03
[lb01]
192.168.15.5 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[lb02]
192.168.15.6 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[lb:children]
lb01
lb02
[nfs]
192.168.15.31 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1' 
[db]
192.168.15.61 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1'
[prometheus]
192.168.15.71 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='1'

[root@m1 project]# vim /etc/ansible/ansible.cfg  # 	修改ansible配置文件
	host_key_checking = False                 #跳過檢查主機指紋
	
[root@m1 ~]# ansible all -m ping  # 測試主機文件配置正常

1.3 安裝插件准備代碼包

[root@m1 ~]# yum install python3 python3-devel  # 安裝python
[root@m1 ~]# pip3 install django  # 安裝Django
[root@m1 ~]# cd /opt/  # 切換目錄
[root@m1 opt]# django-admin startproject linux20  # 創建目錄
[root@m1 ~]# cd linux20  # 切換目錄
[root@m1 linux20]# django-admin startapp application  # 創建目錄
[root@m1 linux20]# vim linux20/settings.py  # 修改配置文件的以下內容
	ALLOWED_HOSTS = ['*']  # 加入一個※號表示通用
	DATABASES = {}  # 把原來的內容清空
	
[root@m1 linux20]# python3 manage.py runserver 0.0.0.0:8000  # 指定端口啟動服務
[root@m1 linux20]# pip3 install uwsgi  # 安裝
[root@m1 linux20]# vim myweb.ini  # 編輯配置文件
    [uwsgi]
    # 端口號
    socket            = :8000
    # 指定項目的目錄
    chdir           = /opt/linux20
    # wsgi文件路徑
    wsgi-file       = linux20/wsgi.py
    # 模塊wsgi路徑
    module          = linux20.wsgi
    # 是否開啟master進程
    master          = true
    # 工作進程的最大數目
    processes       = 4
    # 結束后是否清理文件
    vacuum          = true
    
[root@m1 linux20]# uwsgi --ini myweb.ini  # 啟動uwsgi
[root@m1 linux20]# cd ..  # 切換到上層目錄/opt
[root@m1 opt]# tar -czvf linux20.tar.gz linux20  # 打包代碼

image-20220224175511998

2、 部署公共roles

2.1 初始化公共角色

[root@m01 project]# ansible-galaxy init common  # 創建公共角色目錄

2.2 編輯任務文件

[root@m01 project]# vim common/tasks/main.yml  # 編輯公共任務配置文件
- name: 關閉防火牆
  service:
    name: firewalld
    state: stopped
    enabled: no
- name: 關閉Selinux
  selinux:
    state: disabled
- name: 安裝NFS
  yum:
    name: nfs-utils
    state: present
  when: 
    - ansible_distribution == "CentOS"
- name: 創建全局用戶組
  group:
    name: www
    state: present
    gid: 666
- name: 創建全局用戶
  user:
    name: www
    comment: 全局應用程序用戶
    uid: 666
    group: www
    shell: /sbin/nologin
    state: present
    create_home: false

image-20220223174602091

3、安裝部署NFS

3.1 初始化角色

[root@m01 project]# ansible-galaxy init nfs  # 初始化角色

3.2 編輯任務文件

[root@m01 project]# vim nfs/tasks/main.yml  # 編輯nfs任務配置文件
- name: 安裝RpcBind
  yum:
    name: rpcbind
    state: present
  when:
  	- ansible_distribution == "CentOS"
- name: 創建掛載點
  file:
    path: /backup
    owner: www
    group: www
    mode: 777
    state: directory
- name: 創建NFS配置文件
  template:
    src: ./nfs.j2
    dest: /etc/exports
- name: 啟動NFS和rpcbind
  service:
    name: "{{ item }}"
    state: restarted
  with_items:
    - nfs-server
    - rpcbind

3.3 編輯配置文件

[root@m01 project]# vim nfs/templates/nfs.j2  # 編輯nfs的j2配置文件
/backup 192.168.15.0/24(rw,sync,all_squash,anonuid=666,anongid=666)

image-20220223181036091

4、 部署數據庫db

4.1 初始化角色

[root@m01 project]# ansible-galaxy init db  # 初始化角色

4.2 編輯任務文件

[root@m01 project]# vim db/tasks/main.yml  # 編輯數據庫任務配置文件
- name: 安裝MariaDB和mariadb-server
  yum:
    name: "{{ item }}"
    state: present
  with_items:
    - mariadb
    - mariadb-server
- name: 啟動Mariadb和rpcbind
  service:
    name: mariadb
    state: restarted
- name: 創建遠程連接用戶和數據庫
  shell: /usr/bin/mysql -uroot -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'test@666' WITH GRANT OPTION;FLUSH PRIVILEGES;CREATE DATABASE django;"

image-20220223181158224

5、部署WEB

5.1 初始化角色

[root@m01 project]# ansible-galaxy init web  # 初始化角色

5.2 編輯任務文件

[root@m01 project]# vim web/tasks/main.yml  # 編輯web任務配置文件
- name: 卸載nginx、httpd殘留
  yum:
    name: "{{ item }}"
    state: absent
  with_items:
    - nginx
    - httpd
- name: 安裝Nginx、python3、python3-devel
  yum:
    name: "{{ item }}"
    state: present
  with_items:
    - nginx
    - python3
    - python3-devel
- name: 安裝Django
  shell: pip3 install django -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com
  
- name: 安裝uwsgi
  shell: pip3 install uwsgi -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com
- name: 上傳代碼
  unarchive:
    src: ./linux20.tar.gz
    dest: /opt/
    remote_src: no
- name: 上傳Nginx配置文件
  template:
    src: ./nginx.conf.j2	
    dest: /etc/nginx/nginx.conf
- name: 上傳Nginx主機配置文件
  template:
    src: ./django.conf.j2
    dest: /etc/nginx/conf.d/default.conf
- name: 啟動UWSGI
  shell: cd /opt/linux20 && /usr/local/bin/uwsgi -d --ini myweb.ini
- name: 啟動Nginx
  service:
    name: nginx
    state: restarted

5.3 編輯配置文件

[root@m01 project]# vim web/templates/django.conf.j2  
server {
    listen 80;
    server_name www.django.com;
    location / {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:8000;
        uwsgi_read_timeout 2;
        uwsgi_param UWSGI_SCRIPT linux20.wsgi;
        uwsgi_param UWSGI_CHDIR /opt/linux20;
        index  index.html index.htm;
        client_max_body_size 35m;
    }
}

[root@m1 project]# vim web/templates/nginx.conf.j2
user  www;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}

image-20220223193553895

5.4 上傳代碼包

[root@m1 ~]# cp /opt/linux20.tar.gz /root/project/web/files/

6、部署負載均衡lb

6.1 初始化角色

[root@m01 project]# ansible-galaxy init lb  # 初始化角色

6.2 編輯任務文件

[root@m01 project]# vim lb/tasks/main.yml  # 編輯lb任務配置文件
---
- name: 安裝高可用軟件和nginx
  yum:
    name: "{{ item }}"
    state: present
  with_items:
    - nginx
    - keepalived
- name: 配置Nginx
  template:
    src: ./nginx.conf.j2
    dest: /etc/nginx/nginx.conf
- name: 配置Upstream
  template:
    src: ./upstream.conf.j2
    dest: /etc/nginx/upstream.conf
- name: 配置lb
  template:
    src: ./lb.conf.j2
    dest: /etc/nginx/conf.d/default.conf
- name: 配置keepalived
  template:
    src: ./keepalived.conf.j2
    dest: /etc/keepalived/keepalived.conf
- name: 啟動Nginx和Keepalived
  service:
    name: "{{ item }}"
    state: restarted
  with_items:
    - nginx
    - keepalived

6.3 編輯配置文件

[root@m01 project]# vim lb/templates/nginx.conf.j2
user  www;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}

[root@m01 project]# vim lb/templates/lb.conf.j2
upstream web {
    server 192.168.15.7;
    server 192.168.15.8;
    server 192.168.15.9;
}

server {
    listen 80;
    server_name www.django.com;
    location / {
        proxy_pass http://web;
        include upstream.conf;
    }
}

[root@m01 project]# vim lb/templates/keepalived.conf.j2
! Configuration File for keepalived
# 全局配置
global_defs {
   # 當前keepalived唯一標識
   router_id {{ ansible_fqdn }}
}

# 配置VRRP協議
vrrp_instance VI_1 {

{% if ansible_fqdn == "lb01" %}
    # 狀態,MASTER和BACKUP
    state MASTER
    # 優先級
    priority 100
{% else %}
    # 狀態,MASTER和BACKUP
    state BACKUP
    # 優先級
    priority 90
{% endif %}
    # 綁定網卡
    interface eth0
    # 虛擬路由標示,可以理解為分組
    virtual_router_id 50
    # 監測心跳間隔時間
    advert_int 1
    # 配置認證
    authentication {
        # 認證類型
        auth_type PASS
        # 認證的密碼
        auth_pass 1111
    }
    # 設置VIP
    virtual_ipaddress {
        # 虛擬的VIP地址
        192.168.15.3
    }
}

[root@m01 project]# vim lb/files/upstream.conf.j2

proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;

#后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;

#允許客戶端請求的最大單文件字節數
client_max_body_size 10m;

#緩沖區代理緩沖用戶端請求的最大字節數,
#如果把它設置為比較大的數值,例如256k,那么,無論使用firefox還是IE瀏覽器,來提交任意小於256k的圖片,都很正常。如果注釋該指令,使用默認的client_body_buffer_size設置,也就是操作系統頁面大小的兩倍,8k或者16k,問題就出現了。
#無論使用firefox4.0還是IE8.0,提交一個比較大,200k左右的圖片,都返回500 Internal Server Error錯誤
client_body_buffer_size 128k;

#表示使nginx阻止HTTP應答代碼為400或者更高的應答。
proxy_intercept_errors on;

#后端服務器連接的超時時間_發起握手等候響應超時時間
#nginx跟后端服務器連接超時時間(代理連接超時)
proxy_connect_timeout 90;

#后端服務器數據回傳時間(代理發送超時)
#后端服務器數據回傳時間_就是在規定時間之內后端服務器必須傳完所有的數據
proxy_send_timeout 90;

#連接成功后,后端服務器響應時間(代理接收超時)
#連接成功后_等候后端服務器響應時間_其實已經進入后端的排隊之中等候處理(也可以說是后端服務器處理請求的時間)
proxy_read_timeout 90;

#設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
#設置從被代理服務器讀取的第一部分應答的緩沖區大小,通常情況下這部分應答中包含一個小的應答頭,默認情況下這個值的大小為指令proxy_buffers中指定的一個緩沖區的大小,不過可以將其設置為更小
proxy_buffer_size 4k;

#proxy_buffers緩沖區,網頁平均在32k以下的設置
#設置用於讀取應答(來自被代理服務器)的緩沖區數目和大小,默認情況也為分頁大小,根據操作系統的不同可能是4k或者8k
proxy_buffers 4 32k;

#高負荷下緩沖大小(proxy_buffers*2)
proxy_busy_buffers_size 64k;

#設置在寫入proxy_temp_path時數據的大小,預防一個工作進程在傳遞文件時阻塞太長
#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
proxy_temp_file_write_size 64k;

image-20220223195857842

7、 部署監控prometheus

prometheus監控的架構:
grafana(顯示圖表:只在監控上安裝) --> server(存儲和處理監控數據:只在監控上安裝)--> agent(獲取監控數據:所有機器安裝)      

7.1 初始化角色

[root@m01 project]# ansible-galaxy init prometheus  # 初始化角色

7.2 下載監控相關的插件包

[root@m1 files]# wget https://mirrors.tuna.tsinghua.edu.cn/grafana/yum/rpm/grafana-8.4.1-1.x86_64.rpm  # 下載grafana軟件包
[root@m1 files]# wgt https://github.com/prometheus/prometheus/releases/download/v2.33.4/prometheus-2.33.4.linux-amd64.tar.gz  # 下載prometheus軟件包
[root@m1 files]# wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz  # 下載node-Exporter軟件包
[root@m1 files]# wget https://github.com/prometheus/mysqld_exporter/releases/download/v0.13.0/mysqld_exporter-0.13.0.windows-amd64.zip  # 下載數據庫插件包

7.3 編輯任務文件

[root@m01 project]# vim prometheus/tasks/main.yml  # 編輯監控的任務配置文件
# 機器系統數據收集:需要注冊服務
- name: 安裝部署NodeExporter
  unarchive:
    src: ./node_exporter-1.3.1.linux-amd64.tar.gz
    dest: /usr/local/
- name: 注冊NodeExpoeter systemd服務
  copy:
    src: node-exporter.service
    dest: /usr/lib/systemd/system/
- name: 啟動NodeExporter服務
  systemd:
    name: node-exporter
    daemon_reload: yes
    state: restarted

# 數據庫監控:需要注冊服務並且需要連接數據庫的賬戶密碼
- name: 安裝部署MysqldExporter
  unarchive:
    src: ./mysqld_exporter-0.13.0.linux-amd64.tar.gz 
    dest: /usr/local/
  when: ansible_fqdn == "db01"
- name: 注冊MysqldExporter systemd服務
  copy:
    src: mysqld-exporter.service
    dest: /usr/lib/systemd/system/
  when: ansible_fqdn == "db01"
- name: 上傳密碼文件
  copy:
    src: ./.my.cnf
    dest: /usr/local/mysqld_exporter-0.13.0.linux-amd64/
  when: ansible_fqdn == "db01"
- name: 啟動MysqldExporter服務
  systemd:
    name: mysqld-exporter
    daemon_reload: yes
    state: restarted
  when: ansible_fqdn == "db01"

# 監控服務:需要注冊服務,需要修改配置文件
- name: 部署Prometheus
  unarchive:
    src: ./prometheus-2.33.4.linux-amd64.tar.gz
    dest: /usr/local/
  when: ansible_fqdn == "prometheus"
- name: 注冊Prometheus systemd服務
  copy:
    src: prometheus.service
    dest: /usr/lib/systemd/system/
  when: ansible_fqdn == "prometheus"
- name: 修改Prometheus的配置文件
  template:
    src: ./prometheus.yml
    dest: /usr/local/prometheus-2.33.4.linux-amd64/
  when: ansible_fqdn == "prometheus"
- name: 啟動Prometheus服務
  systemd:
    name: prometheus
    daemon_reload: yes
    state: restarted
  when: ansible_fqdn == "prometheus"
# grafana服務:可以做數據監控和數據統計展示為圖表,不需要注冊服務,直接yum安裝插件就可以用了
- name: 上傳Grafana安裝包
  copy:
    src: ./grafana-8.4.1-1.x86_64.rpm
    dest: /opt/
  when: ansible_fqdn == "prometheus"
- name: 安裝Grafana
  shell: "cd /opt/ && yum install grafana-8.4.1-1.x86_64.rpm -y"
  when: ansible_fqdn == "prometheus"
- name: 啟動Grafana服務
  systemd:
    name: grafana-server
    daemon_reload: yes
    state: restarted
  when: ansible_fqdn == "prometheus"

7.4 編輯注冊文件

[root@m1 files]# vim mysqld-exporter.service  # 編輯mysql注冊文件
[Unit]
Description=Prometheus

[Service]
ExecStart=/usr/local/mysqld_exporter-0.1.0.linux-amd64/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter-0.1.0.linux-amd64/.my.cnf --web.listen-address=:9104
Restart=on-failure

[Install]
WantedBy=multi-user.target

[root@m1 files]# vim node-exporter.service  # 編輯node服務注冊文件
[Unit]
Description=This is prometheus node exporter
After=node_exporter.service

[Service]
Type=simple
ExecStart=/usr/local/node_exporter-1.3.1.linux-amd64/node_exporter
ExecReload=/bin/kill -HUP 
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target

[root@m1 files]# vim prometheus.service  # 編輯prometheus服務注冊文件
[Unit]
Description=Prometheus

[Service]
ExecStart=/usr/local/prometheus-2.33.4.linux-amd64/prometheus --config.file=/usr/local/prometheus-2.33.4.linux-amd64/prometheus.yml --web.enable-lifecycle  
Restart=on-failure

[Install]
WantedBy=multi-user.target
[root@m1 files]# cat prometheus.service
[Unit]
Description=Prometheus

[Service]
ExecStart=/usr/local/prometheus-2.33.4.linux-amd64/prometheus --config.file=/usr/local/prometheus-2.33.4.linux-amd64/prometheus.yml --web.enable-lifecycle  
Restart=on-failure

[Install]
WantedBy=multi-user.target

7.5 編輯配置文件

  [root@m1 templates]# vim prometheus.yml   # 編輯prometheus的配置文件
# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090"]
  - job_name: "Linux主機監控"
    static_configs:
      - targets:
          - "192.168.15.7:9100"
          - "192.168.15.8:9100"
          - "192.168.15.9:9100"
          - "192.168.15.31:9100"
          - "192.168.15.61:9100"
          - "192.168.15.71:9100"
          - "192.168.15.81:9100"
          - "192.168.15.5:9100"
          - "192.168.15.6:9100"
  - job_name: "MySQL監控"
    static_configs:
      - targets:
          - "192.168.15.61:9104"

7.6 編輯密碼文件

[root@m1 files]# vim .my.cnf
[client]
host=192.168.15.61
user=root
password=test@666

8、編寫並執行劇本

8.1 編寫劇本

[root@m1 ~]# cd /root  # 切換到project的上一層目錄再編輯執行劇本
[root@m1 ~]# vim test.yaml  # 編寫劇本
- hosts: all
  name: 全局初始化
  roles:
    - common

- hosts: nfs
  name: NFS相關操作
  roles:
    - nfs

- hosts: db01
  name: 數據庫相關操作
  roles:
    - db

- hosts: web
  name: WEB相關操作
  roles:
    - web

- hosts: lb
  name: 負載均衡相關操作
  roles:
    - lb
- hosts: all
  name: 安裝部署監控
  roles:
    - prometheus

8.2 執行劇本

root@m1 ~]# ansible-playbook -C role.yaml  # -C參數用於測試劇本能不能正常執行
[root@m1 ~]# ansible-playbook role.yaml

9、實現監控

1.瀏覽器訪問ip:http://192.168.15.71:9090/進入prometheus監控頁面
2.statue選擇targets
3.瀏覽器訪問ip:http://192.168.15.71:3000/進入grafana圖表頁面,輸入賬號密碼
4.點設置圖標,點Data sources,選prometheus
5.修改url:192.168.15.71:9090,拉到頁面底部save & test
6.回到grafana官網:https://grafana.com/products/cloud/
7.頁面頂端菜單欄選擇Products,點Dashboards
8.左邊菜單欄Data sources 選擇prometheus
9.選擇Node Exporter Full,復制儀表板ID  1860
10.回到3000的grafana監控頁面,點+號下面的import,輸入1860點load,選prometheus然后點import即可查看圖表。

image-20220224214618660

image-20220224220240151

image-20220224220349223

image-20220224220542148

image-20220224220738050

image-20220224220749805

image-20220224221018750

image-20220224221328128

image-20220224221515904

image-20220224221702739

image-20220224221856216

image-20220224222030387

image-20220224222212987


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM