Ansinterface/app.py

83 lines
2.5 KiB
Python

import subprocess
import os
from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
FILE_PATH = '/data/interface/fichier.txt'
class path:
ansible_scripts = '/data/Ansible-Playbook/'
default_hosts = '/data/Ansible-Playbook/hosts'
binary = '/usr/bin/ansible-playbook '
class flask_config:
port=8000
host='0.0.0.0'
thread=True
debug=False
@app.route('/')
def index():
playbooks=[]
for file in os.listdir(path.ansible_scripts):
if file.endswith(".yml"):
playbooks.append(file)
return render_template('index.html',list=playbooks)
@app.route('/edit', methods=['POST'])
def edit():
if request.form['file_edit']:
FILE_PATH = path.ansible_scripts+request.form['file_edit']
with open(FILE_PATH, 'r') as file:
file_content = file.read()
return render_template('edit_file.html', file_content=file_content, filepath=FILE_PATH)
@app.route('/edit_file', methods=['POST'])
def edit_file():
new_content = request.form.get('file_content')
FILE_PATH = request.form.get('file_path')
print("edit "+FILE_PATH)
with open(FILE_PATH, 'w') as file:
file.write(new_content)
return redirect(url_for('index'))
@app.route('/run')
def run():
return render_template('run.html')
@socketio.on('submit_playbook')
def handle_submit_playbook(data):
playbook = data['playbook']
hosts = data['hosts']
argument = data['argument']
limitation = data['limitation']
if playbook:
command = path.binary+path.ansible_scripts+playbook
if limitation:
command = command +" -l "+limitation
if argument:
command = command +' -e "'+argument+'"'
if hosts:
command = command +" -i "+inventory
else:
command = command +" -i "+path.default_hosts
print(command)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
socketio.emit('ansible_output', {'data': output.strip()})
process.wait()
socketio.emit('ansible_output', {'data': '*** La tâche Ansible est terminée ***'})
if __name__ == '__main__':
socketio.run(app, host=flask_config.host, port=flask_config.port, debug=flask_config.debug)