Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 34 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,38 @@ This collection provides Ansible modules to manage Hostinger Virtual Private Ser

## Included Modules

| Module Name | Description |
| ------------------------------------------------ | ------------------------------------------------------------ |
| `hostinger.vps.hostinger_vps_firewall` | Manage Hostinger VPS firewalls (create, delete, get, update) |
| `hostinger.vps.hostinger_vps_firewall_binding` | Attach, detach, or sync firewalls to/from a VPS |
| `hostinger.vps.hostinger_vps_firewall_rule` | Create, update, delete firewall rules |
| `hostinger.vps.hostinger_vps_get_info` | Retrieve details about a specific Hostinger VPS |
| `hostinger.vps.hostinger_vps_hostname` | Set or reset the hostname of VPS |
| `hostinger.vps.hostinger_vps_malware_scanner` | Install or uninstall the malware scanner on a VPS |
| `hostinger.vps.hostinger_vps_metrics` | Fetch VPS metrics within a specified time range |
| `hostinger.vps.hostinger_vps_payment_method_info`| Retrieve a list of available payment methods |
| `hostinger.vps.hostinger_vps_postinstall_create` | Create post-install scripts |
| `hostinger.vps.hostinger_vps_postinstall_delete` | Delete a post-install script |
| `hostinger.vps.hostinger_vps_postinstall_list` | List available post-install scripts |
| `hostinger.vps.hostinger_vps_power` | Start, stop, or restart a VPS instance |
| `hostinger.vps.hostinger_vps_provision` | Order and set up a new VPS instance from catalog |
| `hostinger.vps.hostinger_vps_reinstall` | Reinstall a VPS with a different OS/template |
| `hostinger.vps.hostinger_vps_snapshot` | Create, delete, restore, or get snapshot info |
| `hostinger.vps.hostinger_vps_ssh_key` | Create, delete, or list SSH public keys |
| `hostinger.vps.hostinger_vps_ssh_key_binding` | Attach SSH keys to a virtual machine |
| `hostinger.vps.hostinger_vps_subscription_info` | Retrieve active subscription information |
| Module Name | Description |
| -------------------------------------------------------- | ------------------------------------------------------------ |
| `hostinger.vps.hostinger_vps_action_info` | List the actions performed on a VPS, or get one |
| `hostinger.vps.hostinger_vps_backup` | List or restore VPS backups |
| `hostinger.vps.hostinger_vps_backup_info` | List the backups of a VPS |
| `hostinger.vps.hostinger_vps_catalog_info` | List purchasable products and their prices |
| `hostinger.vps.hostinger_vps_data_center_info` | List the data centers a VPS can be set up in |
| `hostinger.vps.hostinger_vps_firewall` | Create, delete, or get Hostinger VPS firewalls |
| `hostinger.vps.hostinger_vps_firewall_binding` | Activate, deactivate, or sync firewalls on a VPS |
| `hostinger.vps.hostinger_vps_firewall_info` | List firewalls and their rules, or get one |
| `hostinger.vps.hostinger_vps_firewall_rule` | Create, update, delete firewall rules |
| `hostinger.vps.hostinger_vps_get_info` | Retrieve details about a specific Hostinger VPS |
| `hostinger.vps.hostinger_vps_hostname` | Set or reset the hostname of VPS |
| `hostinger.vps.hostinger_vps_malware_scanner` | Install or uninstall the malware scanner on a VPS |
| `hostinger.vps.hostinger_vps_malware_scanner_info` | Get the malware scanner's status and last scan results |
| `hostinger.vps.hostinger_vps_metrics` | Fetch VPS metrics within a specified time range |
| `hostinger.vps.hostinger_vps_payment_method_info` | Retrieve a list of available payment methods |
| `hostinger.vps.hostinger_vps_post_install_script_info` | List post-install scripts, or get one |
| `hostinger.vps.hostinger_vps_postinstall_create` | Create post-install scripts |
| `hostinger.vps.hostinger_vps_postinstall_delete` | Delete a post-install script |
| `hostinger.vps.hostinger_vps_postinstall_list` | List available post-install scripts |
| `hostinger.vps.hostinger_vps_power` | Start, stop, or restart a VPS instance |
| `hostinger.vps.hostinger_vps_provision` | Order and set up a new VPS instance from catalog |
| `hostinger.vps.hostinger_vps_reinstall` | Reinstall a VPS with a different OS/template |
| `hostinger.vps.hostinger_vps_snapshot` | Create, delete, restore, or get snapshot info |
| `hostinger.vps.hostinger_vps_snapshot_info` | Get the snapshot of a VPS |
| `hostinger.vps.hostinger_vps_ssh_key` | Create, delete, or list SSH public keys |
| `hostinger.vps.hostinger_vps_ssh_key_binding` | Attach SSH keys to a virtual machine |
| `hostinger.vps.hostinger_vps_ssh_key_info` | List the SSH public keys of the account |
| `hostinger.vps.hostinger_vps_subscription_info` | Retrieve active subscription information |
| `hostinger.vps.hostinger_vps_template_info` | List OS templates, or get one |
| `hostinger.vps.hostinger_vps_vm_info` | List virtual machines, or get one |

## Inventory Plugin

Expand All @@ -38,6 +50,8 @@ This collection provides Ansible modules to manage Hostinger Virtual Private Ser

Every module accepts the token through the `token` option. When it is omitted, the `HOSTINGER_API_TOKEN` environment variable is used, which is also how the inventory plugin should receive it, because inventory files are not templated.

Modules that start an action on a virtual machine (power, recreate, snapshots, backups, hostname, PTR, firewall binding, SSH key binding and the malware scanner) return as soon as the action is accepted. Set `wait: true` to wait until it has finished; `wait_timeout` sets the limit in seconds (600 by default).

Note: A valid payment method (such as Google Pay or PayPal) added to your Hostinger account is optional, and only required when provisioning new resources through the API. If you're using this collection to manage existing VPS instances, no payment method is needed.

## Usage
Expand Down
26 changes: 26 additions & 0 deletions plugins/doc_fragments/action_wait.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


class ModuleDocFragment(object):

DOCUMENTATION = r'''
options:
wait:
description:
- Wait until the action started on the virtual machine has finished.
- When enabled, the returned action shows its final state, and the module fails if the action fails or does
not finish within I(wait_timeout).
type: bool
default: false
version_added: 1.1.0
wait_timeout:
description:
- Maximum number of seconds to wait when I(wait=true).
type: int
default: 600
version_added: 1.1.0
'''
42 changes: 42 additions & 0 deletions plugins/module_utils/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
__metaclass__ = type

import json
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode

Expand All @@ -14,6 +15,8 @@

DEFAULT_API_URL = "https://developers.hostinger.com"
DEFAULT_TIMEOUT = 60
DEFAULT_WAIT_TIMEOUT = 600
ACTION_POLL_INTERVAL = 5
TOKEN_ENV_VAR = "HOSTINGER_API_TOKEN"

# Cloudflare in front of the API rejects requests that do not identify themselves (issue #1).
Expand All @@ -29,6 +32,14 @@ def api_argument_spec():
)


def action_wait_argument_spec():
"""Options of modules that start an action; documented in the hostinger.vps.action_wait doc fragment."""
return dict(
wait=dict(type="bool", default=False),
wait_timeout=dict(type="int", default=DEFAULT_WAIT_TIMEOUT),
)


class HostingerApiError(Exception):
"""Raised for any failed API call; status_code and response are None for network errors."""

Expand Down Expand Up @@ -108,6 +119,30 @@ def get_all_pages(self, path, query=None):

page += 1

def wait_for_action(self, virtual_machine_id, action, timeout, interval=ACTION_POLL_INTERVAL):
"""Poll a virtual machine action until it succeeds and return its final state.

Raises HostingerApiError when the action fails or is still running after timeout seconds.
"""
if not isinstance(action, dict) or "id" not in action:
raise HostingerApiError(f"Cannot wait for the action: the API response has no action ID: {action}", response=action)

deadline = time.monotonic() + timeout
while action.get("state") != "success":
description = f"action '{action.get('name')}' ({action['id']}) on virtual machine {virtual_machine_id}"
if action.get("state") == "error":
raise HostingerApiError(f"The {description} failed.", response=action)
if time.monotonic() >= deadline:
raise HostingerApiError(
f"Timed out after {timeout} seconds waiting for the {description}; last state: {action.get('state')}.",
response=action,
)

time.sleep(interval)
action = self.get(f"/api/vps/v1/virtual-machines/{virtual_machine_id}/actions/{action['id']}")

return action

@staticmethod
def _decode(method, path, content):
if not content:
Expand Down Expand Up @@ -159,6 +194,13 @@ def client_from_module(module):
)


def wait_for_action_if_requested(module, client, virtual_machine_id, action):
"""Return the action as started, or its final state when the module's wait option is set."""
if not module.params["wait"]:
return action
return client.wait_for_action(virtual_machine_id, action, module.params["wait_timeout"])


def fail_on_api_error(module, error, action):
"""Fail the module with the API error, keeping the HTTP status and parsed body in the result."""
module.fail_json(
Expand Down
94 changes: 94 additions & 0 deletions plugins/modules/hostinger_vps_action_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = r'''
---
module: hostinger_vps_action_info
short_description: List actions of a Hostinger virtual machine
version_added: 1.1.0
description:
- Lists the actions (start, recreate, backup, and so on) performed on a virtual machine, newest first, or returns a
single action.
- Modules that start an action can wait for it themselves with their I(wait) option.
options:
virtual_machine_id:
description: ID of the virtual machine.
required: true
type: int
action_id:
description:
- ID of the action to return.
- When omitted, every action of the virtual machine is returned, collected from all pages of results.
type: int
extends_documentation_fragment:
- hostinger.vps.api
author:
- Hostinger Dev Team (@hostinger)
'''

EXAMPLES = r'''
- name: List the actions of a virtual machine
hostinger.vps.hostinger_vps_action_info:
virtual_machine_id: 123456
register: result

- name: Get one action
hostinger.vps.hostinger_vps_action_info:
virtual_machine_id: 123456
action_id: 8123712
register: result
'''

RETURN = r'''
actions:
description: Actions; a single-item list when I(action_id) is set.
returned: success
type: list
elements: dict
sample:
- id: 8123712
name: ct_restart
state: success
created_at: "2025-02-27T11:54:00Z"
updated_at: "2025-02-27T11:58:00Z"
'''

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hostinger.vps.plugins.module_utils.api import (
HostingerApiError,
api_argument_spec,
client_from_module,
fail_on_api_error,
)


def main():
module_args = api_argument_spec()
module_args.update(
virtual_machine_id=dict(type='int', required=True),
action_id=dict(type='int'),
)

module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

path = f"/api/vps/v1/virtual-machines/{module.params['virtual_machine_id']}/actions"
action_id = module.params['action_id']

try:
client = client_from_module(module)
if action_id:
actions = [client.get(f"{path}/{action_id}")]
else:
actions = client.get_all_pages(path)
except HostingerApiError as error:
fail_on_api_error(module, error, "Fetching actions")

module.exit_json(changed=False, actions=actions)


if __name__ == '__main__':
main()
7 changes: 6 additions & 1 deletion plugins/modules/hostinger_vps_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
state:
description:
- Desired operation.
- C(get) to list available backups.
- C(get) to list available backups. Use M(hostinger.vps.hostinger_vps_backup_info) instead; C(get) will be removed in version 2.0.0.
- C(delete) is no longer supported by the Hostinger API and always fails. It will be removed in version 2.0.0.
- C(restore) to restore from a backup.
required: true
Expand All @@ -31,6 +31,7 @@
required: false
extends_documentation_fragment:
- hostinger.vps.api
- hostinger.vps.action_wait
author:
- Hostinger Dev Team (@hostinger)
'''
Expand Down Expand Up @@ -60,14 +61,17 @@
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hostinger.vps.plugins.module_utils.api import (
HostingerApiError,
action_wait_argument_spec,
api_argument_spec,
client_from_module,
fail_on_api_error,
wait_for_action_if_requested,
)


def main():
module_args = api_argument_spec()
module_args.update(action_wait_argument_spec())
module_args.update(
virtual_machine_id=dict(type='str', required=True),
state=dict(type='str', required=True, choices=["get", "delete", "restore"]),
Expand All @@ -92,6 +96,7 @@ def main():
data = client.get(f"/api/vps/v1/virtual-machines/{vm_id}/backups")
else:
data = client.post(f"/api/vps/v1/virtual-machines/{vm_id}/backups/{backup_id}/restore")
data = wait_for_action_if_requested(module, client, vm_id, data)
except HostingerApiError as error:
fail_on_api_error(module, error, f"Backup '{state}'")

Expand Down
83 changes: 83 additions & 0 deletions plugins/modules/hostinger_vps_backup_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = r'''
---
module: hostinger_vps_backup_info
short_description: List backups of a Hostinger virtual machine
version_added: 1.1.0
description:
- Lists the backups of a virtual machine, collected from all pages of results.
- Restore a backup with M(hostinger.vps.hostinger_vps_backup).
options:
virtual_machine_id:
description: ID of the virtual machine.
required: true
type: int
extends_documentation_fragment:
- hostinger.vps.api
author:
- Hostinger Dev Team (@hostinger)
'''

EXAMPLES = r'''
- name: List backups
hostinger.vps.hostinger_vps_backup_info:
virtual_machine_id: 123456
register: result

- name: Restore the newest backup
hostinger.vps.hostinger_vps_backup:
virtual_machine_id: 123456
state: restore
backup_id: "{{ (result.backups | sort(attribute='created_at') | last).id }}"
wait: true
'''

RETURN = r'''
backups:
description: Backups of the virtual machine.
returned: success
type: list
elements: dict
sample:
- id: 325
location: nl-srv-nodebackups
size: 15240192
restore_time: 3600
created_at: "2025-02-27T11:54:22Z"
'''

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hostinger.vps.plugins.module_utils.api import (
HostingerApiError,
api_argument_spec,
client_from_module,
fail_on_api_error,
)


def main():
module_args = api_argument_spec()
module_args.update(
virtual_machine_id=dict(type='int', required=True),
)

module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

try:
backups = client_from_module(module).get_all_pages(
f"/api/vps/v1/virtual-machines/{module.params['virtual_machine_id']}/backups"
)
except HostingerApiError as error:
fail_on_api_error(module, error, "Fetching backups")

module.exit_json(changed=False, backups=backups)


if __name__ == '__main__':
main()
Loading
Loading