Hetzner Cloud - How to create a Snapshot or Backup with Ansible
Table Of Contents
Introduction
The Hetzner Cloud provides an API that lets you manage your servers in an automated way. In this tutorial I will use the API to:
- Get the server IDs for all servers provisioned from my Ansible host inventory with their hostname.
- Use these server IDs to create automated snapshots or backups for the corresponding systems with custom descriptions and labels.
- Check the snapshot/backup creation progress against the image ID and action ID I received in step 2
You can for example add the hcloud_token
variable and the block of tasks to the ansible playbook in my tutorial for running system updates with an automated downtime in CheckMK.
Instructions
Create an API Token
Before you can use the API you need to create an API Token for your project in the Hetzner Cloud. For this select your project, change to the “Security” section on the left pane and under “Api-Token” add a new token with read and write permission. Store the key somewhere save as you can only see it once.
The Ansible Playbook
This is my example ansible playbook that I use all the time. You can change some things to your liking:
- Add your API token in the vars section
- In the
body
section of the taskCreate system snapshot
you can:- change the description/name of the backup
- set/add labels
- choose between the two image types
backup
andsnapshot
.
- In the task
Wait until snapshot is finished
you can change the retries and delay (in seconds) between each try in the loop
For further informations check the Hetzner Cloud API Docs.
---
- name: "Create backup of server"
hosts: '{{ target }}'
vars:
hcloud_token: YOUR_API_TOKEN_HERE
tasks:
- block:
- name: Get server ID from Hetzner API
delegate_to: localhost
register: response
uri:
url: "https://api.hetzner.cloud/v1/servers?name={{ inventory_hostname }}"
method: GET
headers:
Authorization: "Bearer {{ hcloud_token }}"
return_content: yes
status_code: 200
body_format: json
- name: Create system backup
delegate_to: localhost
register: response
uri:
url: "https://api.hetzner.cloud/v1/servers/{{ response.json.servers[0].id }}/actions/create_image"
method: POST
headers:
Authorization: "Bearer {{ hcloud_token }}"
Content-Type: "application/json"
body: '{"description":"Backup before update installation with ansible","labels":{"author":"ansible"},"type":"backup"}'
return_content: yes
status_code: 201
body_format: json
- name: Wait until backup is finished
delegate_to: localhost
register: response
uri:
url: "https://api.hetzner.cloud/v1/images/{{ response.json.image.id }}/actions/{{ response.json.action.id }}"
method: GET
headers:
Authorization: "Bearer {{ hcloud_token }}"
return_content: yes
status_code: 200
body_format: json
until: response.json.action.progress == 100
retries: 30
delay: 10