昨天介紹完 Ansible 的重要元件,今天來簡單的實作。
pip install ansible
確認安裝成功
ansible --version
ansible [core 2.16.2]
我們簡單從 MacOS 部署到一台 Linux 的主機上
首先我們建立一個資料夾,叫啥都行
裡面我們建立一個 yaml 檔
playbook.yaml
裡面的 tasks 分別會去執行
---
- hosts: database
become: true # 確保有 root 權限執行
tasks:
- name: apt update
apt:
update_cache: yes
- name: Install MySQL
apt:
name: mysql-server
state: present
tags: install_mysql
- name: Check MySQL service
service:
name: mysql
state: started
enabled: true
tags: install_mysql
- name: Restart MySQL
service:
name: mysql
state: restarted
tags: install_mysql
接著建立一個 inventory 叫做 hosts
[all:vars]
ansible_user=對方主機的 user (user 的權限會影響你執行時的操作)
[database]
database-1 ansible_host=你要部署的主機
執行 ansible-playbook -i hosts playbook.yaml
ansible-playbook -i hosts playbook.yaml
PLAY [database] **********************************************************************
TASK [Gathering Facts] ***************************************************************
ok: [database-1]
TASK [apt update] ********************************************************************
changed: [database-1]
TASK [Install MySQL] *****************************************************************
ok: [database-1]
TASK [Check MySQL service] ***********************************************************
ok: [database-1]
TASK [Restart MySQL] *****************************************************************
changed: [database-1]
PLAY RECAP ***************************************************************************
database-1 : ok=5 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
結束後會顯示 tasks 的幾個狀態
接著我們到部署的主機去查看服務
就會發現成功部署囉!
sudo systemctl status mysql.service
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2024-10-08 22:38:14 CST; 11min ago
Process: 2503640 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
Main PID: 2503648 (mysqld)
Status: "Server is operational"
Tasks: 38 (limit: 9402)
Memory: 365.6M
CPU: 6.657s
CGroup: /system.slice/mysql.service
└─2503648 /usr/sbin/mysqld
Oct 08 22:38:12 staging-vm-247 systemd[1]: Starting MySQL Community Server...
Oct 08 22:38:14 staging-vm-247 systemd[1]: Started MySQL Community Server.
今天只是一個簡單的範例,ansible 還有提供很多可以客製化的選項,和細節的操作設定,如果有興趣的朋友們再去官方文件多多了解囉!