利用Django和Ansible实现自动化部署
以下是一个简化的例子,展示了如何使用Ansible playbook来自动化部署一个使用Django框架的Web应用:
---
- hosts: servers
become: yes
gather_facts: no
tasks:
- name: Install dependencies
apt:
update_cache: yes
pkg:
- name: python3
state: present
- name: python3-pip
state: present
- name: git
state: present
- name: Install Django and other required packages
pip:
name: django
extra_args: --upgrade
- name: Clone the Django project repository
git:
repo: https://github.com/username/project.git
dest: /opt/project
version: master
- name: Collect static files
shell: "source /opt/venv/bin/activate && cd /opt/project && python3 manage.py collectstatic --no-input"
args:
executable: /bin/bash
- name: Apply database migrations
shell: "source /opt/venv/bin/activate && cd /opt/project && python3 manage.py migrate"
args:
executable: /bin/bash
- name: Create a superuser
shell: "source /opt/venv/bin/activate && cd /opt/project && python3 manage.py createsuperuser"
args:
executable: /bin/bash
- name: Start the Gunicorn server
shell: "source /opt/venv/bin/activate && cd /opt/project && gunicorn project.wsgi:application -b 0.0.0.0:8000"
args:
executable: /bin/bash
这个Ansible playbook包含了安装依赖、克隆代码仓库、收集静态文件、迁移数据库、创建管理员用户、启动Gunicorn服务器的步骤。这样的自动化流程可以显著减少部署时间和人为错误,并提高系统的一致性。
评论已关闭