Ansible一鍵部署Flask(nginx+Uwsgi)

問題:在一臺安裝有Ansible的主機上如何一鍵部署Flask到另外一臺centos系統的主機?

    前提:兩臺主機網絡互通(參考“Ansible入門基礎"進行配置)

一,新建目錄app和其子目錄conf,目錄app用於存放Flaks項目文件(.py),uwsgi配置文件(.ini),playbook運行文件(.yml),子目錄conf用於存放nginx配置文件(.conf)

1.

準備目錄創建Flask文件
>mkdir app
>cd app
>vim hello.py           #創建Flask 項目hello.py
from flaskimportFlask
app = Flask(__name__)
 
 
@app.route(‘/’)
def index():
 return'<h1>Hello World!!'
 
 
if __name__ =="__main__":
 app.run(port=8088)


2.

創建uwsgi配置文件

>vim test_uwsgi.ini
[uwsgi]
socket =127.0.0.1:8088  
chdir = /root/app
processes =4
threads =2
master =true
pythonpath = /root/app         #Flask項目所在文件路徑
module = hello                      #因爲flask文件名爲hello.py
callable = app                       #因爲Flask項目文件中 app = Flask(__name__)
memory-report =true
daemonize =127.0.0.1:8088    #配置讓uwsgi在後臺運行
 

 

3.

創建nginx配置文件

>mkdir conf          #在app目錄下創建conf文件,用於存放nginx.conf配置文件
>cd conf
>vim nginx.conf      #nginx 配置文件
include  /etc/nginx/conf.d/*.conf;
server {
    listen        80default_server;
    listen          [::]:80default_server;
    server_name   _;
     include  /etc/nginx/default.d/*.conf;
     location /{
         include  uwsgi_params:
         uwsgi_pass    127.0.0.1:8088    #IP和端口要求與uwsgi配置文件裏面的socket值一致
        }
}

 

4.

回到app目錄下,創建playbook文件

>cd ..
>vim test_build.yml         #ansible執行的playbook文件
---
- name: nginx and uwsgi build Flask
  hosts:testservers                                                                   
  remote_user: root
  tasks:
       - name: install nginx and uwsgi and uwsgi-plugin-python
       action: yum name={{ item.name }} state=present
       with_items:
              - { name:'nginx'}
              - { name:'uwsgi'}
              - { name:'uwsgi-plugin-python'}
        - name: create directory
          file: state=directory dest=/root/testb/conf
        - name: copy file
          copy: src={{ item.src }} dest={{ item.dest }}
          with_items:
               - { src:'/root/app/test_uwsgi.ini',dest: '/root/testb/test_uwsgi.ini'}
               - { src:'/root/app/hello.py', dest:'/root/testb/hello.py'}
               - { src:'/root/app/conf/nginx.conf', dest:'/root/testb/conf/nginx.conf'}
          - name: build flask
            command: uwsgi --http-socket127.0.0.1:8088--plugin python --ini /root/testb/test_uwsgi.ini
  handlers:         #handler 啓動nginx
     - name: start nginx
       command: /root/nginx-1.2.7-c /root/app/conf/nginx.conf   #啓動nginx指令爲:nginx安裝目錄地址 -c nginx配置文件地址

 

5.

運行playbook文件test_build.yml
>ansible-playbook  test_build.yml

 運行結果截圖:


6.

檢測是否搭建成功
>curl127.0.0.1:8088


 返回 Hello World!!  即成功


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章