Skip to content

Commit

Permalink
feat: duration calc
Browse files Browse the repository at this point in the history
  • Loading branch information
Nemental committed Jul 4, 2024
1 parent b3e290a commit 2d78bdd
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions plugins/modules/grafana_silence.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@
"""

import json
from datetime import datetime, timedelta

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url, basic_auth_header
Expand Down Expand Up @@ -393,6 +394,18 @@ def setup_module_object():
)


def parse_iso8601_duration(duration):
# Remove the leading 'P' and split days ('D'), hours ('H'), minutes ('M')
duration = duration[1:] # Remove 'P'
days, time = duration.split("T") if "T" in duration else (None, duration)

days = int(days[:-1]) if days and "D" in days else 0
hours = int(time.split("H")[0][:-1]) if "H" in time else 0
minutes = int(time.split("M")[0][-1:]) if "M" in time else 0

return timedelta(days=days, hours=hours, minutes=minutes)


def main():
module = setup_module_object()
grafana_iface = GrafanaSilenceInterface(module)
Expand All @@ -407,14 +420,27 @@ def main():
"silenceID": module.params.get("silence_id"),
}

state = module.params.get("state")

if module.params.get("ends_at"):
silence_payload["endsAt"] = module.params.get("ends_at")
elif module.params.get("duration"):
silence_payload["duration"] = module.params.get("duration")
starts_at = module.params.get("starts_at")
duration = module.params.get("duration")

silence = grafana_iface.get_silence(silence_payload)
# Parse starts_at into datetime object
starts_at_dt = datetime.strptime(starts_at, "%Y-%m-%dT%H:%M:%S.%fZ")

state = module.params.get("state")
# Parse ISO 8601 duration into timedelta
duration_timedelta = parse_iso8601_duration(duration)

# Calculate ends_at
ends_at_dt = starts_at_dt + duration_timedelta

# Format ends_at as ISO 8601
silence_payload["endsAt"] = ends_at_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

silence = grafana_iface.get_silence(silence_payload)

if state == "present":
if not silence:
Expand Down

0 comments on commit 2d78bdd

Please sign in to comment.