Created
May 13, 2021 17:02
-
-
Save Ridys/e0101ff123cafc174ebb21684635d7f8 to your computer and use it in GitHub Desktop.
File for creating Hetzner cloud server snapshots (CX)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Hetzner Snapshot Creation File | |
Python 3.7+ required | |
""" | |
import requests | |
import json | |
import pathlib | |
SAVE_FILE = str(pathlib.Path(__file__).parent.absolute()) + '/backups.json' | |
SAVE_FILE = pathlib.Path(SAVE_FILE) | |
TOKEN = '' # token | |
TOKEN = {'Authorization': 'Bearer ' + TOKEN} | |
SERVER_ID = '' # server id | |
# get exists copies | |
if SAVE_FILE.is_file(): | |
with open(SAVE_FILE) as json_file: | |
backups = json.load(json_file) | |
else: | |
backups = dict() | |
# create new copy | |
url = 'https://api.hetzner.cloud/v1/servers/{}/actions/create_image'.format(SERVER_ID) | |
data = {'type': 'snapshot'} | |
response = requests.post(url, json=data, headers=TOKEN) | |
response = response.json() | |
date = response['image']['created'] | |
image_id = response['image']['id'] | |
# write info about copy | |
backups[date] = image_id | |
# del old copy, if file have >= 7 copies | |
if len(backups) >= 7: | |
key, image_id = next(iter(backups.items())) | |
url = 'https://api.hetzner.cloud/v1/images/{}'.format(image_id) | |
response = requests.delete(url, headers=TOKEN) | |
del backups[key] | |
# save info in file | |
with open(SAVE_FILE, 'w', encoding='utf-8') as f: | |
json.dump(backups, f, ensure_ascii=False, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment