接下來是看要如何利用 Ansible 部屬我們的程式
我們一樣會寫 Ansible Playbook,流程大概是
先看我們的 Playbook 和 roles
# deploy.yml
---
- hosts: all
roles:
- apt_upgrade
- install_nodejs
- install_app
# roles/apt_upgrade/tasks/main.yml
---
- name: Perform 'apt update'
apt:
update_cache: yes
tags:
- apt
- name: Perform 'apt upgrade'
apt:
package: '*'
state: latest
tags:
- apt
# roles/install_nodejs/tasks/main.yml
---
- name: Use apt to install nodejs & npm
apt:
pkg:
- nodejs
- npm
tags:
- nodejs
---
- name: Create dir /app
file:
path: /app
owner: root
group: root
mode: '0755'
state: directory
tags:
- app
- name: Copy our app into folder
copy:
src: ../../../../app/index.js
dest: /app/index.js
owner: root
group: root
mode: '0644'
tags:
- app
- name: Run npm install in the folder
shell: npm i express
args:
chdir: /app
- name: Install systemd service file
copy:
src: nodeapp.service
dest: /etc/systemd/system/nodeapp.service
owner: root
group: root
mode: '0644'
tags:
- app
- name: Reload systemd daemon
systemd:
daemon_reload: yes
tags:
- app
- name: Enable nodeapp service
systemd:
name: nodeapp
state: started
enabled: yes
tags:
- app
# roles/install_app/files/nodeapp.service
[Unit]
Description=Node App
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/node /app/index.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
我們接下來要在 lxc.tf
裡加入部署選項
我們要把我們的 SSH Key 放進去,同時也要放部署的指令
大概會像這樣
ssh_public_keys = "<YOUR_SSH_KEY>"
provisioner "local-exec" {
command = "sleep 30; ansible-playbook -u root -i '${var.lxc_ip},' deploy.yml;"
}
最後,當我們執行 terraform apply
的時候,就能看到 Ansible 把我們的 app 部署進去了
執行結果大概像這樣
這樣我們就有辦法利用工具來幫助我們部署、管理機器了
明天講監控的部分