init
This commit is contained in:
62
s3_api/s3api.py
Normal file
62
s3_api/s3api.py
Normal file
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import requests, json, os
|
||||
from dotenv import load_dotenv
|
||||
from marshmallow import Schema, fields, ValidationError
|
||||
from flask import Flask, request, Response, jsonify
|
||||
from python_terraform import Terraform
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
API_KEY = os.getenv('API_KEY')
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
class BucketSchema(Schema):
|
||||
environment = fields.Str(required=True)
|
||||
bucket_name = fields.Str(required=True)
|
||||
versioning = fields.Str(required=True)
|
||||
encryption = fields.Str(required=True)
|
||||
api_key = fields.Str(required=True)
|
||||
|
||||
def create_bucket(ENVIRONMENT, ENCRYPTED, BUCKET_NAME, VERSIONING):
|
||||
tfstate_bucket = os.getenv("TFSTATE_BUCKET", "company-s3-tfstate-bucket-eu-central-1")
|
||||
tfstate_region = os.getenv("AWS_REGION", "eu-central-1")
|
||||
with open("terraform/backend.tf", "w") as f:
|
||||
f.write('terraform {\n')
|
||||
f.write('backend "s3" {\n')
|
||||
f.write(f'bucket = "{tfstate_bucket}"\n')
|
||||
f.write(f'region = "{tfstate_region}"\n')
|
||||
f.write(f'key = "s3-{ENVIRONMENT}-{BUCKET_NAME}"\n')
|
||||
f.write('}\n}')
|
||||
tf = Terraform(working_dir='terraform',
|
||||
variables={'ENCRYPTED': ENCRYPTED, 'VERSIONING': VERSIONING, 'BUCKET_NAME': BUCKET_NAME, 'ENVIRONMENT': ENVIRONMENT}
|
||||
)
|
||||
return tf.apply(capture_output=True, skip_plan=True, auto_approve=True, var={'ENCRYPTED': ENCRYPTED, 'VERSIONING': VERSIONING, 'BUCKET_NAME': BUCKET_NAME, 'ENVIRONMENT': ENVIRONMENT})
|
||||
|
||||
@app.route('/', methods = ['GET'])
|
||||
def ping():
|
||||
return ["Pong"]
|
||||
|
||||
@app.route('/create_bucket', methods = ['POST'])
|
||||
def bucket_data():
|
||||
request_data = BucketSchema().load(request.json)
|
||||
if request_data["api_key"] == API_KEY:
|
||||
try:
|
||||
ENVIRONMENT = request_data["environment"]
|
||||
BUCKET_NAME = request_data["bucket_name"]
|
||||
ENCRYPTED = request_data["encryption"]
|
||||
VERSIONING = request_data["versioning"]
|
||||
if create_bucket(ENVIRONMENT, ENCRYPTED, BUCKET_NAME, VERSIONING)[0] == 1:
|
||||
return "Something went wrong trying to create the bucket"
|
||||
return f"Creating bucket {BUCKET_NAME} in {ENVIRONMENT} with encryption={ENCRYPTED} and versioning={VERSIONING}"
|
||||
except ValidationError as err:
|
||||
return jsonify(err.messages), 400
|
||||
else:
|
||||
return "Authentication error", 403
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(port = 8080, host="0.0.0.0")
|
||||
Reference in New Issue
Block a user