Skip to content

Instantly share code, notes, and snippets.

@n3tsurge
Last active August 18, 2021 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n3tsurge/896a36f80339e9793978b2b8c1e12ec0 to your computer and use it in GitHub Desktop.
Save n3tsurge/896a36f80339e9793978b2b8c1e12ec0 to your computer and use it in GitHub Desktop.
Close Elasticsearch indices older than X days
import requests
import json
import datetime
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('elastic', '')
index_pattern = "winlogbeat-*"
days = 90
response = requests.get(f'https://mtllppsecelk01:9200/{index_pattern}/_settings/index.creation_date_string?flat_settings=true&human&expand_wildcards=open', verify=False, auth=auth)
if response.status_code == 200:
indices = response.json()
else:
print(response.__dict__)
def parse_date(date):
for fmt in ('%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%SZ'):
try:
return datetime.datetime.strptime(date, fmt)
except ValueError:
pass
raise ValueError(("no valid date format found"))
old_indices = []
for i in indices:
date = indices[i]['settings']['index.creation_date_string']
creation_date = parse_date(date)
if creation_date < datetime.datetime.now()-datetime.timedelta(days=days):
response = requests.post(f'https://mtllppsecelk01:9200/{i}/_close', verify=False, auth=auth)
if response.status_code == 200:
print(f"Closed index {i}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment