使用 Ansible Playbook自动化部署 Web 应用程序或数据库服务器,展示详细示例代码
时间: 2024-02-21 09:56:53 浏览: 217
自动化运维工具 Ansible 详细部署
当然可以,以下是一个使用 Ansible Playbook 自动化部署 Web 应用程序和数据库服务器的示例代码:
```
---
- name: Deploy web application and database server
hosts: all
become: true
vars:
app_name: myapp
app_port: 8080
db_name: mydb
db_user: myuser
db_password: mypassword
db_port: 3306
tasks:
# Install required packages
- name: Install required packages
apt:
name: "{{ item }}"
state: present
with_items:
- apache2
- libapache2-mod-wsgi
- python-dev
- python-pip
- mysql-server
- libmysqlclient-dev
# Configure Apache
- name: Configure Apache
template:
src: apache.conf.j2
dest: /etc/apache2/sites-available/{{ app_name }}.conf
notify: Restart Apache
# Configure WSGI
- name: Configure WSGI
template:
src: wsgi.conf.j2
dest: /var/www/{{ app_name }}/wsgi.py
# Copy application files
- name: Copy application files
copy:
src: "{{ playbook_dir }}/files/{{ app_name }}"
dest: /var/www/{{ app_name }}/
notify: Restart Apache
# Create database
- name: Create database
mysql_db:
name: "{{ db_name }}"
state: present
login_user: root
login_password: ""
# Create database user
- name: Create database user
mysql_user:
name: "{{ db_user }}"
password: "{{ db_password }}"
priv: "{{ db_name }}.*:ALL"
state: present
login_user: root
login_password: ""
# Configure Django settings
- name: Configure Django settings
lineinfile:
path: /var/www/{{ app_name }}/settings.py
regexp: '^DATABASES'
line: "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': '{{ db_name }}',\n 'USER': '{{ db_user }}',\n 'PASSWORD': '{{ db_password }}',\n 'HOST': 'localhost',\n 'PORT': '{{ db_port }}',\n }\n}"
handlers:
# Restart Apache
- name: Restart Apache
service:
name: apache2
state: restarted
```
这个 Ansible Playbook 部署了一个名为 `myapp` 的 Web 应用程序,使用 Apache 和 WSGI 来运行 Python Web 应用程序。它还配置了一个名为 `mydb` 的 MySQL 数据库,使用 Django ORM 访问数据库。在实际应用中,需要根据具体情况进行调整和优化。
阅读全文