Skip to content

Commit

Permalink
Merge pull request #20 from kiraum/kiraum/lightsail
Browse files Browse the repository at this point in the history
feat(lightsail): adding ansiv resume
  • Loading branch information
kiraum authored Oct 24, 2024
2 parents 3885b1f + 0417a7a commit 14da02c
Show file tree
Hide file tree
Showing 13 changed files with 1,496 additions and 30 deletions.
48 changes: 45 additions & 3 deletions environments/prod/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ module "billing_report" {
enable_email_notification = true
enable_slack_notification = true
slack_webhook_url = var.slack_webhook_url
daily_cost_threshold = "0.01"
daily_cost_threshold = "0.15"
weekly_cost_threshold = "1.00"
monthly_cost_threshold = "5.00"
yearly_cost_threshold = "60.00"
Expand Down Expand Up @@ -166,7 +166,22 @@ module "route53" {
type = "CNAME"
ttl = 300
records = ["protonmail3.domainkey.dempd74kuxcjabpnbahdxnyoscyzm34xj6e5of6vyqwjrw64bwqoq.domains.proton.ch."]
},
# lightsail
{
name = "ansiv"
type = "CNAME"
ttl = 300
records = [module.lightsail_ansiv.container_url]
},
# lightsail cert
{
name = module.lightsail_ansiv.domain_validation_records["ansiv.kiraum.it"].name
type = module.lightsail_ansiv.domain_validation_records["ansiv.kiraum.it"].type
ttl = 300
records = [module.lightsail_ansiv.domain_validation_records["ansiv.kiraum.it"].value]
}

]
},
"xpto_it" = {
Expand Down Expand Up @@ -271,7 +286,22 @@ module "route53" {
type = "CNAME"
ttl = 300
records = ["protonmail3.domainkey.d5cgr4quagzmaa5rqmmtnppt6lo46zuzu2zjylpuruv5luk4vmkuq.domains.proton.ch."]
},
# lightsail
{
name = "ansiv"
type = "CNAME"
ttl = 300
records = [module.lightsail_ansiv.container_url]
},
# lightsail cert
{
name = module.lightsail_ansiv.domain_validation_records["ansiv.xpto.it"].name
type = module.lightsail_ansiv.domain_validation_records["ansiv.xpto.it"].type
ttl = 300
records = [module.lightsail_ansiv.domain_validation_records["ansiv.xpto.it"].value]
}

]
}
}
Expand All @@ -287,8 +317,7 @@ module "route53" {
module "static_website" {
source = "../../modules/static_website"

bucket_name = "xpto-static-website-bucket"
# domain_names = ["kiraum.it"]
bucket_name = "xpto-static-website-bucket"
domain_names = ["xpto.it", "kiraum.it"]
cloudfront_price_class = "PriceClass_100"

Expand All @@ -303,3 +332,16 @@ module "static_website" {
aws.us_east_1 = aws.us_east_1
}
}


# Lightsail module
module "lightsail_ansiv" {
source = "../../modules/lightsail_ansiv"

container_name = "ansiv"
container_image = ":ansiv.resume.7"
availability_zone = "${var.aws_region}a"
bundle_id = "nano"
custom_domain_name = ["ansiv.xpto.it", "ansiv.kiraum.it"]
monthly_budget_limit = "10"
}
26 changes: 17 additions & 9 deletions modules/billing_report/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ def send_slack_notification(message):
)
with urllib.request.urlopen(req) as response:
if response.getcode() != 200:
print(f"Failed to send Slack notification. Status code: {response.getcode()}")
print(
f"Failed to send Slack notification. Status code: {response.getcode()}"
)


def calculate_time_periods(time_period, current_date):
Expand All @@ -63,9 +65,9 @@ def calculate_time_periods(time_period, current_date):
elif time_period == "yearly":
start = end.replace(month=1, day=1)
compare_start = start.replace(year=start.year - 1)
compare_end = compare_start.replace(year=compare_start.year + 1) - datetime.timedelta(
days=1
)
compare_end = compare_start.replace(
year=compare_start.year + 1
) - datetime.timedelta(days=1)
else:
raise ValueError(
f"Invalid time period: {time_period}. Must be daily, weekly, monthly, or yearly."
Expand Down Expand Up @@ -144,7 +146,9 @@ def generate_text_report(
"""

service_breakdown = ""
for service, cost in sorted(current_services.items(), key=lambda x: x[1], reverse=True):
for service, cost in sorted(
current_services.items(), key=lambda x: x[1], reverse=True
):
if cost >= 0.01:
previous_cost = compare_services.get(service, 0)
difference = cost - previous_cost
Expand Down Expand Up @@ -223,7 +227,9 @@ def generate_slack_block_report(
divider = {"type": "divider"}
service_breakdown = []

for service, cost in sorted(current_services.items(), key=lambda x: x[1], reverse=True):
for service, cost in sorted(
current_services.items(), key=lambda x: x[1], reverse=True
):
if cost >= 0.01:
previous_cost = compare_services.get(service, 0)
difference = cost - previous_cost
Expand Down Expand Up @@ -283,7 +289,9 @@ def lambda_handler(event, context):

try:
aws_account = sts.get_caller_identity()["Account"]
start, end, compare_start, compare_end = calculate_time_periods(time_period, current_date)
start, end, compare_start, compare_end = calculate_time_periods(
time_period, current_date
)

response = ce.get_cost_and_usage(
TimePeriod={
Expand All @@ -304,8 +312,8 @@ def lambda_handler(event, context):
GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
)

current_costs, compare_costs, unit, current_services, compare_services = process_cost_data(
response, compare_response
current_costs, compare_costs, unit, current_services, compare_services = (
process_cost_data(response, compare_response)
)

if current_costs is None:
Expand Down
1 change: 1 addition & 0 deletions modules/billing_report/lambda_mock_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from unittest.mock import MagicMock

import boto3

from lambda_function import lambda_handler


Expand Down
37 changes: 37 additions & 0 deletions modules/lightsail_ansiv/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: 'v4.5.0'
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: local
hooks:
- id: isort
name: isort
entry: isort -m3 --tc
language: system
- repo: local
hooks:
- id: black
name: black
entry: black
language: python
types_or: [python, pyi]
- repo: local
hooks:
- id: ruff
name: ruff
entry: ruff check --force-exclude
language: python
types_or: [python, pyi]
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
args:
- --rcfile=${PWD}/pyproject.toml
- -d format
language: system
types: [python]
62 changes: 62 additions & 0 deletions modules/lightsail_ansiv/disable_lightsail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""
Lightsail Container Service Disabler for AWS Lambda.
Disables a Lightsail container service in response to a budget alert.
Uses boto3 to interact with AWS services and sends notifications via SNS.
"""

import json
import os

import boto3


def lambda_handler(event, context):
"""
AWS Lambda function to disable a Lightsail container service and send notifications.
Args:
event (dict): The event dict that contains the parameters passed when the function
is invoked.
context (object): The context in which the function is called.
Returns:
dict: A dictionary containing a statusCode and a JSON-formatted body message.
Environment Variables:
CONTAINER_SERVICE_NAME (str): The name of the Lightsail container service to be disabled.
SNS_TOPIC_ARN (str): The ARN of the SNS topic to publish notifications.
"""
lightsail = boto3.client("lightsail")
sns = boto3.client("sns")
container_service_name = os.environ["CONTAINER_SERVICE_NAME"]

try:
# Disable the container service
lightsail.update_container_service(
serviceName=container_service_name,
isDisabled=True
)

message = f"Lightsail container service {container_service_name} has been disabled due to budget alert."

# Send SNS notification
sns.publish(
TopicArn=os.environ["SNS_TOPIC_ARN"],
Message=message,
Subject="Lightsail Container Service Disabled"
)

return {"statusCode": 200, "body": json.dumps(message)}
except Exception as exc:
error_message = f"Error disabling Lightsail container service: {str(exc)}"
print(error_message)

# Send SNS notification for error
sns.publish(
TopicArn=os.environ["SNS_TOPIC_ARN"],
Message=error_message,
Subject="Error Disabling Lightsail Container Service"
)

return {"statusCode": 500, "body": json.dumps(error_message)}

Loading

0 comments on commit 14da02c

Please sign in to comment.