Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI
Comment thread
MarijusJanulis marked this conversation as resolved.
Resolved

on:
pull_request:
push:
branches:
- main

jobs:
test:
name: ${{ matrix.test }} (ansible-core ${{ matrix.ansible }})
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.ansible == 'devel' }}
strategy:
fail-fast: false
matrix:
test: [sanity, units]
# Lowest version declared in meta/runtime.yml, plus every maintained release.
ansible: [stable-2.13, stable-2.19, stable-2.20, stable-2.21, devel]
steps:
- uses: ansible-community/ansible-test-gh-action@release/v1
with:
ansible-core-version: ${{ matrix.ansible }}
testing-type: ${{ matrix.test }}
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
*.retry.ansible/
*.retry
.ansible/
__pycache__/
hostinger-vps-*.tar.gz
tests/output/
tests/integration/integration_config.yml
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ This collection provides Ansible modules to manage Hostinger Virtual Private Ser

| Plugin Name | Description |
| --------------------------- | ------------------------------------------- |
| `hostinger.vps.hostinger` | Dynamic inventory plugin for VPS instances |
| `hostinger.vps.inventory` | Dynamic inventory plugin for VPS instances |

## Requirements

- Ansible Core versions >= 2.13
- Ansible Core versions >= 2.13, with Python 3.6 or newer on the control node
- Hostinger API Token (bearer) - obtainable from your Hostinger account under the API section

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.

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
1 change: 0 additions & 1 deletion examples/inventory.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
plugin: hostinger.vps.inventory
token: "{{ hostinger_token }}"
1 change: 0 additions & 1 deletion examples/ping_all.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@
- name: Show ping results
debug:
var: ping_result.stdout_lines

2 changes: 1 addition & 1 deletion examples/postinstall_create.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
hostinger.vps.hostinger_vps_postinstall_create:
token: "{{ hostinger_token }}"
name: "Install Docker"
content: >
content: |
#!/bin/bash
apt update && apt install -y docker.io
1 change: 0 additions & 1 deletion examples/reinstall_vps.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@
virtual_machine_id: "{{ vm_id }}"
template_id: "{{ template_id }}"
password: "{{ password }}"
public_ssh_key_id: "{{ ssh_key_id | default(omit) }}"
post_install_script_id: "{{ script_id | default(omit) }}"
29 changes: 29 additions & 0 deletions plugins/doc_fragments/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function
__metaclass__ = type


class ModuleDocFragment(object):

DOCUMENTATION = r'''
options:
token:
description:
- Hostinger API token.
- If not set, the value of the C(HOSTINGER_API_TOKEN) environment variable is used.
required: true
type: str
api_url:
description:
- Base URL of the Hostinger API.
type: str
default: https://developers.hostinger.com
version_added: 1.1.0
api_timeout:
description:
- Timeout in seconds for each API request.
type: int
default: 60
version_added: 1.1.0
'''
103 changes: 60 additions & 43 deletions plugins/inventory/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import requests
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.module_utils._text import to_text
from ansible_collections.hostinger.vps.plugins.module_utils.headers import get_headers
from ansible_collections.hostinger.vps.plugins.module_utils.api import (
DEFAULT_API_URL,
DEFAULT_TIMEOUT,
HostingerApiClient,
HostingerApiError,
)

DOCUMENTATION = r'''
name: hostinger.vps.inventory
plugin_type: inventory
name: inventory
short_description: Hostinger VPS inventory plugin
description:
- Collects Hostinger VPS instances as dynamic Ansible inventory using the Hostinger VPS API.
Expand All @@ -20,12 +22,33 @@
description: Token to indicate this is a Hostinger inventory plugin
required: true
type: string
choices: [hostinger.vps.inventory]
token:
description: Bearer token to access the Hostinger API
description:
- Bearer token to access the Hostinger API.
- Inventory files are not templated, so set the token directly or through the C(HOSTINGER_API_TOKEN) environment variable.
required: true
type: string
env:
- name: HOSTINGER_API_TOKEN
api_url:
description: Base URL of the Hostinger API.
type: string
default: https://developers.hostinger.com
version_added: 1.1.0
api_timeout:
description: Timeout in seconds for each API request.
type: integer
default: 60
version_added: 1.1.0
'''

EXAMPLES = r'''
# hostinger.yml, used with HOSTINGER_API_TOKEN set in the environment
plugin: hostinger.vps.inventory
'''


class InventoryModule(BaseInventoryPlugin):
NAME = 'hostinger.vps.inventory'

Expand All @@ -34,43 +57,37 @@ def verify_file(self, path):

def parse(self, inventory, loader, path, cache=True):
super().parse(inventory, loader, path)
config = self._read_config_data(path)

token = config.get('token')
if not token:
raise AnsibleError("Missing required 'token' in Hostinger inventory config file.")
self._read_config_data(path)

headers = get_headers(token)
client = HostingerApiClient(
token=self.get_option('token'),
api_url=self.get_option('api_url') or DEFAULT_API_URL,
timeout=self.get_option('api_timeout') or DEFAULT_TIMEOUT,
)

try:
resp = requests.get("https://developers.hostinger.com/api/vps/v1/virtual-machines", headers=headers)
resp.raise_for_status()
vms = resp.json()

if not isinstance(vms, list):
raise AnsibleError("Unexpected response format from Hostinger API. Expected a list of VMs.")

for vm in vms:
if not isinstance(vm, dict):
continue

hostname = vm.get("hostname") or f"srv{vm.get('id', 'unknown')}.hstgr.cloud"
self.inventory.add_host(hostname)

ipv4_list = vm.get("ipv4") or []
ip = ipv4_list[0]["address"] if ipv4_list and "address" in ipv4_list[0] else None
if ip:
self.inventory.set_variable(hostname, "ansible_host", ip)

self.inventory.set_variable(hostname, "hostinger_id", vm.get("id"))
self.inventory.set_variable(hostname, "plan", vm.get("plan"))
self.inventory.set_variable(hostname, "state", vm.get("state"))
self.inventory.set_variable(hostname, "cpus", vm.get("cpus"))
self.inventory.set_variable(hostname, "memory", vm.get("memory"))
self.inventory.set_variable(hostname, "disk", vm.get("disk"))

except requests.exceptions.RequestException as e:
raise AnsibleError(f"Failed to connect to Hostinger API: {to_text(e)}")
except ValueError:
raise AnsibleError("Invalid JSON response from Hostinger API")

vms = client.get("/api/vps/v1/virtual-machines")
except HostingerApiError as error:
raise AnsibleError(f"Failed to fetch virtual machines from the Hostinger API: {error}")

if not isinstance(vms, list):
raise AnsibleError("Unexpected response format from Hostinger API. Expected a list of VMs.")

for vm in vms:
if not isinstance(vm, dict):
continue

hostname = vm.get("hostname") or f"srv{vm.get('id', 'unknown')}.hstgr.cloud"
self.inventory.add_host(hostname)

ipv4_list = vm.get("ipv4") or []
ip = ipv4_list[0]["address"] if ipv4_list and "address" in ipv4_list[0] else None
if ip:
self.inventory.set_variable(hostname, "ansible_host", ip)

self.inventory.set_variable(hostname, "hostinger_id", vm.get("id"))
self.inventory.set_variable(hostname, "plan", vm.get("plan"))
self.inventory.set_variable(hostname, "state", vm.get("state"))
self.inventory.set_variable(hostname, "cpus", vm.get("cpus"))
self.inventory.set_variable(hostname, "memory", vm.get("memory"))
self.inventory.set_variable(hostname, "disk", vm.get("disk"))
Loading
Loading