Skip to content

Commit

Permalink
changed flask run command
Browse files Browse the repository at this point in the history
  • Loading branch information
proquickly committed Nov 19, 2024
1 parent 5426126 commit 4a8a8b5
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 77 deletions.
50 changes: 50 additions & 0 deletions src/tfgha/th.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from pydantic import BaseModel, EmailStr, Field
from typing import List, Optional
from datetime import datetime


class User(BaseModel):
id: int
username: str = Field(..., min_length=3, max_length=50)
email: EmailStr
age: int = Field(..., ge=0, le=120)
is_active: bool = True
created_at: datetime = Field(default_factory=datetime.now)
tags: List[str] = []
profile: Optional[dict] = None



def main():
# Valid user
try:
user1 = User(
id=1,
username="JohnDoe",
email="[email protected]",
age=30,
tags=["user", "premium"],
profile={"bio": "Hello World"}
)
print("\nValid user:")
print(user1.model_dump_json(indent=2))

except Exception as e:
print(f"Error creating user1: {e}")

# Invalid user (will raise validation error)
try:
user2 = User(
id="invalid", # Should be int
username="J", # Too short
email="invalid-email", # Invalid email
age=150, # Age too high
)
print(user2)
except Exception as e:
print("\nValidation errors:")
print(e)


if __name__ == "__main__":
main()
111 changes: 34 additions & 77 deletions terraform/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -5,106 +5,63 @@ provider "aws" {
resource "aws_instance" "py_server" {
ami = "ami-0709112b97e5accb1"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.allow_app.id]

user_data = <<-EOF
user_data = <<-EOF
#!/bin/bash
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
# Update system
yum update -y
yum install -y python3 python3-pip git curl
# Install system dependencies
yum install -y python3-devel gcc
# Create app user
useradd -m -s /bin/bash appuser
# Set up application directory
mkdir -p /app
chown appuser:appuser /app
# Switch to app user
su - appuser << 'EOSU'
# Set up Python environment
python3 -m pip install --user poetry
export PATH="$HOME/.local/bin:$PATH"
# Clone and set up application
cd /app
git clone https://github.com/proquickly/tfgha.git
cd tfgha
# Install dependencies
$HOME/.local/bin/poetry install
$HOME/.local/bin/poetry lock
# Create systemd service file
sudo tee /etc/systemd/system/flask-app.service << 'EOF2'
[Unit]
Description=Flask Application
After=network.target
[Service]
User=appuser
WorkingDirectory=/app/tfgha
Environment="PATH=/home/appuser/.local/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=/home/appuser/.local/bin/poetry run flask run --host=0.0.0.0 --port=5000
Restart=always
[Install]
WantedBy=multi-user.target
EOF2
EOSU
# Set proper permissions
chmod 644 /etc/systemd/system/flask-app.service
# Start and enable the service
systemctl daemon-reload
systemctl start flask-app
systemctl enable flask-app
# Add logging
echo "Setup completed at $(date)" >> /var/log/user-data.log
sudo apt-get update
sudo apt-get install -y python3 python3-pip
# Install Flask
pip3 install flask
# Create application directory
mkdir -p /home/ubuntu/app
# Write the Python script to a file
cat <<EOL > /home/ubuntu/app/app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello from Python!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
EOL
# Change to the application directory and run the app
cd /home/ubuntu/app
python3 app.py &
EOF

tags = {
Name = "GitHubActionsEC2"
Name = "FlaskAppInstance"
}

# Define a security group to allow HTTP traffic
vpc_security_group_ids = [aws_security_group.allow_http.id]
}

resource "aws_security_group" "allow_app" {
name = "allow_app"
description = "Allow inbound traffic for Python app"
lifecycle {
create_before_destroy = true
}
resource "aws_security_group" "allow_http" {
name = "allow_http"
description = "Allow inbound HTTP traffic"

ingress {
description = "App Port"
from_port = 5000
to_port = 5000
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

tags = {
Name = "allow_app"
Expand Down

0 comments on commit 4a8a8b5

Please sign in to comment.