Home > front end >  Flask returning only the last value or first value using boto3
Flask returning only the last value or first value using boto3

Time:04-27

I'm using below script to generate the list of specific IAM Role Names which works perfectly fine on console and list IAM Role Names as expected.

import boto3 
import logging
from botocore.exceptions import ClientError

logging.basicConfig(format='%(message)s')
logger = logging.getLogger('LUCIFER')
logger.setLevel(logging.INFO)

def main():
    try:
        client = boto3.client('iam')
        roles = client.list_roles(PathPrefix='/', MaxItems=1000)
        for i in roles["Roles"]:
            if "sts:AssumeRoleWithSAML".lower() in str(i).lower():
                logger.info(i["RoleName"])
        return i["RoleName"]
    
    except ClientError:
        logger.exception("Couldn't list roles for the account")
        raise

if __name__ == "__main__":
    main()

But when I try to serve this script via below flask script it only returns last value.

from flask import Flask
from main import main

app = Flask(__name__)

@app.route("/", methods = ['GET'])
def index():
    return main()

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

Any hints? Do I need another html template to serve it?

My end goal is to serve it via Vue.js frontend framework, any ideas on it will be highly appreciated.

CodePudding user response:

You are probably confusing it with the output you are logging to console. Just the last value is returned from main(), you are doing nothing with it when running on console.

Actually return a list of the values, this also fixes an error if roles["Roles"] is an emtpy list, since i would not be set:

def main():
    try:
        client = boto3.client('iam')
        roles = client.list_roles(PathPrefix='/', MaxItems=1000)
        result = []
        for i in roles["Roles"]:
            if "sts:AssumeRoleWithSAML".lower() in str(i).lower():
                logger.info(i["RoleName"])
                result.append(i["RoleName"])
        return result
    
    except ClientError:
        logger.exception("Couldn't list roles for the account")
        raise

Update: return JSON list

from flask import jsonify

@app.route("/", methods = ['GET'])
def index():
    rolenames = main()
    return jsonify(rolenames)
  • Related