Home > Mobile >  User input from python flask to be sent to ansible variable
User input from python flask to be sent to ansible variable

Time:10-20

Say I have an example flask app which basically is a small webform that would take in user input data called applet.py.(The code is taken from a online blog that shows an example flask app build).

from flask import Flask,render_template,request
 
app = Flask(__name__)
 
@app.route('/form')
def form():
    return render_template('form.html')
 
@app.route('/data/', methods = ['POST', 'GET'])
def data():
    if request.method == 'GET':
        return f"The URL /data is accessed directly. Try going to '/form' to submit form"
    if request.method == 'POST':
        form_data = request.form
        return render_template('data.html',form_data = form_data)
 
 
app.run(host='localhost', port=5000)

The input is captured in this below form.

<form action="/data" method = "POST">
    <p>Name <input type = "text" name = "Name" /></p>
    <p>City <input type = "text" name = "City" /></p>
    <p>Country <input type = "text" name = "Country" /></p>
    <p><input type = "submit" value = "Submit" /></p>
</form>

If I were wanting to send this received user input into ansible variables and then trigger the ansible script to run and execute the playbook based on the given variables. How can I do that? I have googled a lot around this, couldn't find a suitable example that fits my use case. (Disclaimer, not very knowledgeable about both flask and ansible, learning as I do). Appreciate help, reference and advice.

CodePudding user response:

You can use the ansible_runner module to run your playbook (docs).

import ansible_runner

@app.route('/data/', methods = ['POST', 'GET'])
def data():
    if request.method == 'GET':
        return f"The URL /data is accessed directly. Try going to '/form' to submit form"
    if request.method == 'POST':
        form_data = request.form.to_dict()
        r = ansible_runner.run(playbook='test.yml', extravars=form_data)
        # check ansible return code
        if r.rc != 0:
            abort(400, 'Ansible error')  
        return ('', 204)

If your playbook takes some time to run you might be better adding the job of running it to a queue and processing it separately.

  • Related