chore: setup pre-commit (#234)

* chore: add pre-commit config

* chore: fix pre-commit errors

* chore: add black pre-commit hook

* style: format python files with black

* chore: add isort pre-commit hook

* style: format python files using isort

* chore: add pyupgrade pre-commit hook

* refactor: upgrade code to python3.7

* Allow stacking PRs

Co-authored-by: Julian Tölle <julian.toelle97@gmail.com>

---------

Co-authored-by: Julian Tölle <julian.toelle97@gmail.com>
This commit is contained in:
Jonas L 2023-06-27 11:50:13 +02:00 committed by GitHub
parent e83997517d
commit dfff49e31f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 904 additions and 1091 deletions

View file

@ -7,8 +7,6 @@ Keep in mind that Azure Pipelines does not enforce unique job display names (onl
It is up to pipeline authors to avoid name collisions when deviating from the recommended format.
"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
@ -20,12 +18,12 @@ def main():
"""Main program entry point."""
source_directory = sys.argv[1]
if '/ansible_collections/' in os.getcwd():
if "/ansible_collections/" in os.getcwd():
output_path = "tests/output"
else:
output_path = "test/results"
destination_directory = os.path.join(output_path, 'coverage')
destination_directory = os.path.join(output_path, "coverage")
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
@ -34,27 +32,27 @@ def main():
count = 0
for name in os.listdir(source_directory):
match = re.search('^Coverage (?P<attempt>[0-9]+) (?P<label>.+)$', name)
label = match.group('label')
attempt = int(match.group('attempt'))
match = re.search("^Coverage (?P<attempt>[0-9]+) (?P<label>.+)$", name)
label = match.group("label")
attempt = int(match.group("attempt"))
jobs[label] = max(attempt, jobs.get(label, 0))
for label, attempt in jobs.items():
name = 'Coverage {attempt} {label}'.format(label=label, attempt=attempt)
name = f"Coverage {attempt} {label}"
source = os.path.join(source_directory, name)
source_files = os.listdir(source)
for source_file in source_files:
source_path = os.path.join(source, source_file)
destination_path = os.path.join(destination_directory, source_file + '.' + label)
print('"%s" -> "%s"' % (source_path, destination_path))
destination_path = os.path.join(destination_directory, source_file + "." + label)
print(f'"{source_path}" -> "{destination_path}"')
shutil.copyfile(source_path, destination_path)
count += 1
print('Coverage file count: %d' % count)
print('##vso[task.setVariable variable=coverageFileCount]%d' % count)
print('##vso[task.setVariable variable=outputPath]%s' % output_path)
print("Coverage file count: %d" % count)
print("##vso[task.setVariable variable=coverageFileCount]%d" % count)
print("##vso[task.setVariable variable=outputPath]%s" % output_path)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python
"""Prepends a relative timestamp to each input line from stdin and writes it to stdout."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
@ -12,14 +10,14 @@ def main():
"""Main program entry point."""
start = time.time()
sys.stdin.reconfigure(errors='surrogateescape')
sys.stdout.reconfigure(errors='surrogateescape')
sys.stdin.reconfigure(errors="surrogateescape")
sys.stdout.reconfigure(errors="surrogateescape")
for line in sys.stdin:
seconds = time.time() - start
sys.stdout.write('%02d:%02d %s' % (seconds // 60, seconds % 60, line))
sys.stdout.write("%02d:%02d %s" % (seconds // 60, seconds % 60, line))
sys.stdout.flush()
if __name__ == '__main__':
if __name__ == "__main__":
main()

23
.github/workflows/lint.yml vendored Normal file
View file

@ -0,0 +1,23 @@
name: Lint
on:
push:
branches: [main]
pull_request:
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup python
uses: actions/setup-python@v4
with:
python-version: 3.x
- name: Install dependencies
run: pip install pre-commit
- name: Run pre-commit
run: pre-commit run --all-files --show-diff-on-failure

View file

@ -1,4 +1,5 @@
stages:
- lint
- sanity
- integration
@ -8,6 +9,16 @@ variables:
default:
image: python:$PYTHON_VERSION
pre-commit:
stage: lint
image: python:3.11-alpine
before_script:
- apk add build-base git
- pip install pre-commit
script:
- pre-commit run --all-files --show-diff-on-failure
sanity:
stage: sanity
allow_failure: true

43
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,43 @@
---
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
- id: check-symlinks
- id: destroyed-symlinks
- id: check-json
- id: check-yaml
- id: check-toml
- id: check-merge-conflict
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
- id: prettier
files: \.(md|ya?ml)$
exclude: ^changelogs/changelog.yaml$
- repo: https://github.com/asottile/pyupgrade
rev: v3.7.0
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black

View file

@ -1,13 +1,9 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
DOCUMENTATION = '''
class ModuleDocFragment:
DOCUMENTATION = """
options:
api_token:
description:
@ -26,4 +22,4 @@ seealso:
- name: Documentation for Hetzner Cloud API
description: Complete reference for the Hetzner Cloud API.
link: https://docs.hetzner.cloud/
'''
"""

View file

@ -1,11 +1,8 @@
# Copyright (c) 2019 Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
DOCUMENTATION = r"""
name: hcloud
author:
- Lukas Kaemmerling (@lkaemmerling)
@ -84,7 +81,7 @@ DOCUMENTATION = r'''
type: list
elements: str
required: false
'''
"""
EXAMPLES = r"""
# Minimal example. `HCLOUD_TOKEN` is exposed in environment.
@ -118,27 +115,30 @@ keyed_groups:
"""
import os
from ipaddress import IPv6Network
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
from ansible.release import __version__
from ipaddress import IPv6Network
try:
from hcloud import hcloud
from hcloud import APIException
from hcloud import APIException, hcloud
HAS_HCLOUD = True
except ImportError:
HAS_HCLOUD = False
class InventoryModule(BaseInventoryPlugin, Constructable):
NAME = 'hetzner.hcloud.hcloud'
NAME = "hetzner.hcloud.hcloud"
def _configure_hcloud_client(self):
self.token_env = self.get_option("token_env")
self.templar.available_variables = self._vars
self.api_token = self.templar.template(self.get_option("token"), fail_on_undefined=False) or os.getenv(self.token_env)
self.api_token = self.templar.template(self.get_option("token"), fail_on_undefined=False) or os.getenv(
self.token_env
)
if self.api_token is None:
raise AnsibleError(
"Please specify a token, via the option token, via environment variable HCLOUD_TOKEN "
@ -147,10 +147,12 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
self.endpoint = os.getenv("HCLOUD_ENDPOINT") or "https://api.hetzner.cloud/v1"
self.client = hcloud.Client(token=self.api_token,
api_endpoint=self.endpoint,
application_name="ansible-inventory",
application_version=__version__)
self.client = hcloud.Client(
token=self.api_token,
api_endpoint=self.endpoint,
application_name="ansible-inventory",
application_version=__version__,
)
def _test_hcloud_token(self):
try:
@ -168,14 +170,15 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
def _filter_servers(self):
if self.get_option("network"):
network = self.templar.template(self.get_option("network"), fail_on_undefined=False) or self.get_option("network")
network = self.templar.template(self.get_option("network"), fail_on_undefined=False) or self.get_option(
"network"
)
try:
self.network = self.client.networks.get_by_name(network)
if self.network is None:
self.network = self.client.networks.get_by_id(network)
except APIException:
raise AnsibleError(
"The given network is not found.")
raise AnsibleError("The given network is not found.")
tmp = []
for server in self.servers:
@ -225,16 +228,17 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
if server.public_net.ipv6:
self.inventory.set_variable(server.name, "ipv6_network", to_native(server.public_net.ipv6.network))
self.inventory.set_variable(server.name, "ipv6_network_mask", to_native(server.public_net.ipv6.network_mask))
self.inventory.set_variable(server.name, "ipv6", to_native(self._first_ipv6_address(server.public_net.ipv6.ip)))
self.inventory.set_variable(
server.name, "ipv6_network_mask", to_native(server.public_net.ipv6.network_mask)
)
self.inventory.set_variable(
server.name, "ipv6", to_native(self._first_ipv6_address(server.public_net.ipv6.ip))
)
self.inventory.set_variable(
server.name,
"private_networks",
[
{"name": n.network.name, "id": n.network.id, "ip": n.ip}
for n in server.private_net
],
[{"name": n.network.name, "id": n.network.id, "ip": n.ip} for n in server.private_net],
)
if self.get_option("network"):
@ -306,21 +310,17 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
return to_native(server_private_network.ip)
else:
raise AnsibleError(
"You can only connect via private IPv4 if you specify a network")
raise AnsibleError("You can only connect via private IPv4 if you specify a network")
def _first_ipv6_address(self, network):
return next(IPv6Network(network).hosts())
def verify_file(self, path):
"""Return the possibly of a file being consumable by this plugin."""
return (
super(InventoryModule, self).verify_file(path) and
path.endswith(("hcloud.yaml", "hcloud.yml"))
)
return super().verify_file(path) and path.endswith(("hcloud.yaml", "hcloud.yml"))
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path, cache)
super().parse(inventory, loader, path, cache)
if not HAS_HCLOUD:
raise AnsibleError("The Hetzner Cloud dynamic inventory plugin requires hcloud-python.")
@ -339,13 +339,15 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
self._set_server_attributes(server)
# Use constructed if applicable
strict = self.get_option('strict')
strict = self.get_option("strict")
# Composed variables
self._set_composite_vars(self.get_option('compose'), self.inventory.get_host(server.name).get_vars(), server.name, strict=strict)
self._set_composite_vars(
self.get_option("compose"), self.inventory.get_host(server.name).get_vars(), server.name, strict=strict
)
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
self._add_host_to_composed_groups(self.get_option('groups'), {}, server.name, strict=strict)
self._add_host_to_composed_groups(self.get_option("groups"), {}, server.name, strict=strict)
# Create groups based on variable values and add the corresponding hosts to it
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), {}, server.name, strict=strict)
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), {}, server.name, strict=strict)

View file

@ -1,11 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.ansible_release import __version__
from ansible.module_utils.basic import env_fallback, missing_required_lib
@ -18,7 +14,7 @@ except ImportError:
HAS_HCLOUD = False
class Hcloud(object):
class Hcloud:
def __init__(self, module, represent):
self.module = module
self.represent = represent

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_certificate
@ -68,7 +64,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic certificate
@ -138,8 +134,8 @@ hcloud_certificate:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -158,36 +154,28 @@ class AnsibleHcloudCertificate(Hcloud):
"not_valid_before": to_native(self.hcloud_certificate.not_valid_before),
"not_valid_after": to_native(self.hcloud_certificate.not_valid_after),
"domain_names": [to_native(domain) for domain in self.hcloud_certificate.domain_names],
"labels": self.hcloud_certificate.labels
"labels": self.hcloud_certificate.labels,
}
def _get_certificate(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_certificate = self.client.certificates.get_by_id(
self.module.params.get("id")
)
self.hcloud_certificate = self.client.certificates.get_by_id(self.module.params.get("id"))
elif self.module.params.get("name") is not None:
self.hcloud_certificate = self.client.certificates.get_by_name(
self.module.params.get("name")
)
self.hcloud_certificate = self.client.certificates.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_certificate(self):
self.module.fail_on_missing_params(
required_params=["name"]
)
self.module.fail_on_missing_params(required_params=["name"])
params = {
"name": self.module.params.get("name"),
"labels": self.module.params.get("labels")
"labels": self.module.params.get("labels"),
}
if self.module.params.get('type') == 'uploaded':
self.module.fail_on_missing_params(
required_params=["certificate", "private_key"]
)
if self.module.params.get("type") == "uploaded":
self.module.fail_on_missing_params(required_params=["certificate", "private_key"])
params["certificate"] = self.module.params.get("certificate")
params["private_key"] = self.module.params.get("private_key")
if not self.module.check_mode:
@ -196,9 +184,7 @@ class AnsibleHcloudCertificate(Hcloud):
except Exception as e:
self.module.fail_json(msg=e.message)
else:
self.module.fail_on_missing_params(
required_params=["domain_names"]
)
self.module.fail_on_missing_params(required_params=["domain_names"])
params["domain_names"] = self.module.params.get("domain_names")
if not self.module.check_mode:
try:
@ -214,9 +200,7 @@ class AnsibleHcloudCertificate(Hcloud):
try:
name = self.module.params.get("name")
if name is not None and self.hcloud_certificate.name != name:
self.module.fail_on_missing_params(
required_params=["id"]
)
self.module.fail_on_missing_params(required_params=["id"])
if not self.module.check_mode:
self.hcloud_certificate.update(name=name)
self._mark_as_changed()
@ -268,8 +252,8 @@ class AnsibleHcloudCertificate(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_if=[['state', 'present', ['name']]],
required_one_of=[["id", "name"]],
required_if=[["state", "present", ["name"]]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_certificate_info
short_description: Gather infos about your Hetzner Cloud certificates.
@ -32,7 +28,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud certificate infos
@ -86,8 +82,8 @@ hcloud_certificate_info:
returned: always
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -101,31 +97,30 @@ class AnsibleHcloudCertificateInfo(Hcloud):
for certificate in self.hcloud_certificate_info:
if certificate:
certificates.append({
"id": to_native(certificate.id),
"name": to_native(certificate.name),
"fingerprint": to_native(certificate.fingerprint),
"certificate": to_native(certificate.certificate),
"not_valid_before": to_native(certificate.not_valid_before),
"not_valid_after": to_native(certificate.not_valid_after),
"domain_names": [to_native(domain) for domain in certificate.domain_names],
"labels": certificate.labels
})
certificates.append(
{
"id": to_native(certificate.id),
"name": to_native(certificate.name),
"fingerprint": to_native(certificate.fingerprint),
"certificate": to_native(certificate.certificate),
"not_valid_before": to_native(certificate.not_valid_before),
"not_valid_after": to_native(certificate.not_valid_after),
"domain_names": [to_native(domain) for domain in certificate.domain_names],
"labels": certificate.labels,
}
)
return certificates
def get_certificates(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_certificate_info = [self.client.certificates.get_by_id(
self.module.params.get("id")
)]
self.hcloud_certificate_info = [self.client.certificates.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_certificate_info = [self.client.certificates.get_by_name(
self.module.params.get("name")
)]
self.hcloud_certificate_info = [self.client.certificates.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_certificate_info = self.client.certificates.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_certificate_info = self.client.certificates.get_all()
@ -152,9 +147,7 @@ def main():
hcloud.get_certificates()
result = hcloud.get_result()
ansible_info = {
'hcloud_certificate_info': result['hcloud_certificate_info']
}
ansible_info = {"hcloud_certificate_info": result["hcloud_certificate_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_datacenter_info
@ -34,7 +30,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud datacenter info
@ -81,8 +77,8 @@ hcloud_datacenter_info:
sample: fsn1
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -96,25 +92,23 @@ class AnsibleHcloudDatacenterInfo(Hcloud):
for datacenter in self.hcloud_datacenter_info:
if datacenter is not None:
tmp.append({
"id": to_native(datacenter.id),
"name": to_native(datacenter.name),
"description": to_native(datacenter.description),
"location": to_native(datacenter.location.name)
})
tmp.append(
{
"id": to_native(datacenter.id),
"name": to_native(datacenter.name),
"description": to_native(datacenter.description),
"location": to_native(datacenter.location.name),
}
)
return tmp
def get_datacenters(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_datacenter_info = [self.client.datacenters.get_by_id(
self.module.params.get("id")
)]
self.hcloud_datacenter_info = [self.client.datacenters.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_datacenter_info = [self.client.datacenters.get_by_name(
self.module.params.get("name")
)]
self.hcloud_datacenter_info = [self.client.datacenters.get_by_name(self.module.params.get("name"))]
else:
self.hcloud_datacenter_info = self.client.datacenters.get_all()
@ -127,7 +121,7 @@ class AnsibleHcloudDatacenterInfo(Hcloud):
argument_spec=dict(
id={"type": "int"},
name={"type": "str"},
**Hcloud.base_module_arguments()
**Hcloud.base_module_arguments(),
),
supports_check_mode=True,
)
@ -136,23 +130,23 @@ class AnsibleHcloudDatacenterInfo(Hcloud):
def main():
module = AnsibleHcloudDatacenterInfo.define_module()
is_old_facts = module._name == 'hcloud_datacenter_facts'
is_old_facts = module._name == "hcloud_datacenter_facts"
if is_old_facts:
module.deprecate("The 'hcloud_datacenter_facts' module has been renamed to 'hcloud_datacenter_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_datacenter_facts' module has been renamed to 'hcloud_datacenter_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudDatacenterInfo(module)
hcloud.get_datacenters()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_datacenter_facts': result['hcloud_datacenter_info']
}
ansible_info = {"hcloud_datacenter_facts": result["hcloud_datacenter_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_datacenter_info': result['hcloud_datacenter_info']
}
ansible_info = {"hcloud_datacenter_info": result["hcloud_datacenter_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_firewall
@ -80,7 +76,7 @@ options:
type: str
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic firewall
@ -170,14 +166,15 @@ hcloud_firewall:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
import time
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
from hcloud.firewalls.domain import FirewallRule
from hcloud import APIException
from hcloud.firewalls.domain import FirewallRule
except ImportError:
APIException = None
FirewallRule = None
@ -193,7 +190,7 @@ class AnsibleHcloudFirewall(Hcloud):
"id": to_native(self.hcloud_firewall.id),
"name": to_native(self.hcloud_firewall.name),
"rules": [self._prepare_result_rule(rule) for rule in self.hcloud_firewall.rules],
"labels": self.hcloud_firewall.labels
"labels": self.hcloud_firewall.labels,
}
def _prepare_result_rule(self, rule):
@ -209,24 +206,18 @@ class AnsibleHcloudFirewall(Hcloud):
def _get_firewall(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_firewall = self.client.firewalls.get_by_id(
self.module.params.get("id")
)
self.hcloud_firewall = self.client.firewalls.get_by_id(self.module.params.get("id"))
elif self.module.params.get("name") is not None:
self.hcloud_firewall = self.client.firewalls.get_by_name(
self.module.params.get("name")
)
self.hcloud_firewall = self.client.firewalls.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_firewall(self):
self.module.fail_on_missing_params(
required_params=["name"]
)
self.module.fail_on_missing_params(required_params=["name"])
params = {
"name": self.module.params.get("name"),
"labels": self.module.params.get("labels")
"labels": self.module.params.get("labels"),
}
rules = self.module.params.get("rules")
if rules is not None:
@ -252,9 +243,7 @@ class AnsibleHcloudFirewall(Hcloud):
def _update_firewall(self):
name = self.module.params.get("name")
if name is not None and self.hcloud_firewall.name != name:
self.module.fail_on_missing_params(
required_params=["id"]
)
self.module.fail_on_missing_params(required_params=["id"])
if not self.module.check_mode:
self.hcloud_firewall.update(name=name)
self._mark_as_changed()
@ -336,8 +325,8 @@ class AnsibleHcloudFirewall(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_if=[['state', 'present', ['name']]],
required_one_of=[["id", "name"]],
required_if=[["state", "present", ["name"]]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_floating_ip
@ -77,7 +73,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic IPv4 Floating IP
@ -165,8 +161,8 @@ hcloud_floating_ip:
mylabel: 123
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -195,20 +191,14 @@ class AnsibleHcloudFloatingIP(Hcloud):
def _get_floating_ip(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_floating_ip = self.client.floating_ips.get_by_id(
self.module.params.get("id")
)
self.hcloud_floating_ip = self.client.floating_ips.get_by_id(self.module.params.get("id"))
else:
self.hcloud_floating_ip = self.client.floating_ips.get_by_name(
self.module.params.get("name")
)
self.hcloud_floating_ip = self.client.floating_ips.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_floating_ip(self):
self.module.fail_on_missing_params(
required_params=["type"]
)
self.module.fail_on_missing_params(required_params=["type"])
try:
params = {
"description": self.module.params.get("description"),
@ -216,13 +206,9 @@ class AnsibleHcloudFloatingIP(Hcloud):
"name": self.module.params.get("name"),
}
if self.module.params.get("home_location") is not None:
params["home_location"] = self.client.locations.get_by_name(
self.module.params.get("home_location")
)
params["home_location"] = self.client.locations.get_by_name(self.module.params.get("home_location"))
elif self.module.params.get("server") is not None:
params["server"] = self.client.servers.get_by_name(
self.module.params.get("server")
)
params["server"] = self.client.servers.get_by_name(self.module.params.get("server"))
else:
self.module.fail_json(msg="one of the following is required: home_location, server")
@ -258,9 +244,7 @@ class AnsibleHcloudFloatingIP(Hcloud):
if server is not None and self.hcloud_floating_ip.server is not None:
if self.module.params.get("force") and server != self.hcloud_floating_ip.server.name:
if not self.module.check_mode:
self.hcloud_floating_ip.assign(
self.client.servers.get_by_name(server)
)
self.hcloud_floating_ip.assign(self.client.servers.get_by_name(server))
self._mark_as_changed()
elif server != self.hcloud_floating_ip.server.name:
self.module.warn(
@ -270,9 +254,7 @@ class AnsibleHcloudFloatingIP(Hcloud):
self._mark_as_changed()
elif server is not None and self.hcloud_floating_ip.server is None:
if not self.module.check_mode:
self.hcloud_floating_ip.assign(
self.client.servers.get_by_name(server)
)
self.hcloud_floating_ip.assign(self.client.servers.get_by_name(server))
self._mark_as_changed()
elif server is None and self.hcloud_floating_ip.server is not None:
if not self.module.check_mode:
@ -332,8 +314,8 @@ class AnsibleHcloudFloatingIP(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
mutually_exclusive=[['home_location', 'server']],
required_one_of=[["id", "name"]],
mutually_exclusive=[["home_location", "server"]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_floating_ip_info
@ -34,7 +30,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud Floating ip infos
@ -98,8 +94,8 @@ hcloud_floating_ip_info:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -116,29 +112,30 @@ class AnsibleHcloudFloatingIPInfo(Hcloud):
server_name = None
if floating_ip.server is not None:
server_name = floating_ip.server.name
tmp.append({
"id": to_native(floating_ip.id),
"name": to_native(floating_ip.name),
"description": to_native(floating_ip.description),
"ip": to_native(floating_ip.ip),
"type": to_native(floating_ip.type),
"server": to_native(server_name),
"home_location": to_native(floating_ip.home_location.name),
"labels": floating_ip.labels,
"delete_protection": floating_ip.protection["delete"],
})
tmp.append(
{
"id": to_native(floating_ip.id),
"name": to_native(floating_ip.name),
"description": to_native(floating_ip.description),
"ip": to_native(floating_ip.ip),
"type": to_native(floating_ip.type),
"server": to_native(server_name),
"home_location": to_native(floating_ip.home_location.name),
"labels": floating_ip.labels,
"delete_protection": floating_ip.protection["delete"],
}
)
return tmp
def get_floating_ips(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_floating_ip_info = [self.client.floating_ips.get_by_id(
self.module.params.get("id")
)]
self.hcloud_floating_ip_info = [self.client.floating_ips.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_floating_ip_info = self.client.floating_ips.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_floating_ip_info = self.client.floating_ips.get_all()
@ -151,7 +148,7 @@ class AnsibleHcloudFloatingIPInfo(Hcloud):
argument_spec=dict(
id={"type": "int"},
label_selector={"type": "str"},
**Hcloud.base_module_arguments()
**Hcloud.base_module_arguments(),
),
supports_check_mode=True,
)
@ -160,24 +157,24 @@ class AnsibleHcloudFloatingIPInfo(Hcloud):
def main():
module = AnsibleHcloudFloatingIPInfo.define_module()
is_old_facts = module._name == 'hcloud_floating_ip_facts'
is_old_facts = module._name == "hcloud_floating_ip_facts"
if is_old_facts:
module.deprecate("The 'hcloud_floating_ip_facts' module has been renamed to 'hcloud_floating_ip_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_floating_ip_facts' module has been renamed to 'hcloud_floating_ip_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudFloatingIPInfo(module)
hcloud.get_floating_ips()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_floating_ip_facts': result['hcloud_floating_ip_info']
}
ansible_info = {"hcloud_floating_ip_facts": result["hcloud_floating_ip_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_floating_ip_info': result['hcloud_floating_ip_info']
}
ansible_info = {"hcloud_floating_ip_info": result["hcloud_floating_ip_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_image_info
@ -50,7 +46,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud image infos
@ -114,8 +110,8 @@ hcloud_image_info:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -129,35 +125,37 @@ class AnsibleHcloudImageInfo(Hcloud):
for image in self.hcloud_image_info:
if image is not None:
tmp.append({
"id": to_native(image.id),
"status": to_native(image.status),
"type": to_native(image.type),
"name": to_native(image.name),
"description": to_native(image.description),
"os_flavor": to_native(image.os_flavor),
"os_version": to_native(image.os_version),
"architecture": to_native(image.architecture),
"labels": image.labels,
})
tmp.append(
{
"id": to_native(image.id),
"status": to_native(image.status),
"type": to_native(image.type),
"name": to_native(image.name),
"description": to_native(image.description),
"os_flavor": to_native(image.os_flavor),
"os_version": to_native(image.os_version),
"architecture": to_native(image.architecture),
"labels": image.labels,
}
)
return tmp
def get_images(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_image_info = [self.client.images.get_by_id(
self.module.params.get("id")
)]
self.hcloud_image_info = [self.client.images.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None and self.module.params.get("architecture") is not None:
self.hcloud_image_info = [self.client.images.get_by_name_and_architecture(
self.module.params.get("name"),
self.module.params.get("architecture")
)]
self.hcloud_image_info = [
self.client.images.get_by_name_and_architecture(
self.module.params.get("name"),
self.module.params.get("architecture"),
)
]
elif self.module.params.get("name") is not None:
self.module.warn("This module only returns x86 images by default. Please set architecture:x86|arm to hide this message.")
self.hcloud_image_info = [self.client.images.get_by_name(
self.module.params.get("name")
)]
self.module.warn(
"This module only returns x86 images by default. Please set architecture:x86|arm to hide this message."
)
self.hcloud_image_info = [self.client.images.get_by_name(self.module.params.get("name"))]
else:
params = {}
label_selector = self.module.params.get("label_selector")
@ -195,24 +193,24 @@ class AnsibleHcloudImageInfo(Hcloud):
def main():
module = AnsibleHcloudImageInfo.define_module()
is_old_facts = module._name == 'hcloud_image_facts'
is_old_facts = module._name == "hcloud_image_facts"
if is_old_facts:
module.deprecate("The 'hcloud_image_facts' module has been renamed to 'hcloud_image_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_image_facts' module has been renamed to 'hcloud_image_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudImageInfo(module)
hcloud.get_images()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_imagen_facts': result['hcloud_image_info']
}
ansible_info = {"hcloud_imagen_facts": result["hcloud_image_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_image_info': result['hcloud_image_info']
}
ansible_info = {"hcloud_image_info": result["hcloud_image_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer
@ -71,7 +67,7 @@ extends_documentation_fragment:
requirements:
- hcloud-python >= 1.8.0
'''
"""
EXAMPLES = """
- name: Create a basic Load Balancer
@ -145,8 +141,8 @@ hcloud_load_balancer:
sample: false
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -156,8 +152,11 @@ class AnsibleHcloudLoadBalancer(Hcloud):
self.hcloud_load_balancer = None
def _prepare_result(self):
private_ipv4_address = None if len(self.hcloud_load_balancer.private_net) == 0 else to_native(
self.hcloud_load_balancer.private_net[0].ip)
private_ipv4_address = (
None
if len(self.hcloud_load_balancer.private_net) == 0
else to_native(self.hcloud_load_balancer.private_net[0].ip)
)
return {
"id": to_native(self.hcloud_load_balancer.id),
"name": to_native(self.hcloud_load_balancer.name),
@ -174,21 +173,14 @@ class AnsibleHcloudLoadBalancer(Hcloud):
def _get_load_balancer(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_load_balancer = self.client.load_balancers.get_by_id(
self.module.params.get("id")
)
self.hcloud_load_balancer = self.client.load_balancers.get_by_id(self.module.params.get("id"))
else:
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(
self.module.params.get("name")
)
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_load_balancer(self):
self.module.fail_on_missing_params(
required_params=["name", "load_balancer_type"]
)
self.module.fail_on_missing_params(required_params=["name", "load_balancer_type"])
try:
params = {
"name": self.module.params.get("name"),
@ -201,9 +193,7 @@ class AnsibleHcloudLoadBalancer(Hcloud):
if self.module.params.get("location") is None and self.module.params.get("network_zone") is None:
self.module.fail_json(msg="one of the following is required: location, network_zone")
elif self.module.params.get("location") is not None and self.module.params.get("network_zone") is None:
params["location"] = self.client.locations.get_by_name(
self.module.params.get("location")
)
params["location"] = self.client.locations.get_by_name(self.module.params.get("location"))
elif self.module.params.get("location") is None and self.module.params.get("network_zone") is not None:
params["network_zone"] = self.module.params.get("network_zone")
@ -236,7 +226,9 @@ class AnsibleHcloudLoadBalancer(Hcloud):
self._get_load_balancer()
disable_public_interface = self.module.params.get("disable_public_interface")
if disable_public_interface is not None and disable_public_interface != (not self.hcloud_load_balancer.public_net.enabled):
if disable_public_interface is not None and disable_public_interface != (
not self.hcloud_load_balancer.public_net.enabled
):
if not self.module.check_mode:
if disable_public_interface is True:
self.hcloud_load_balancer.disable_public_interface().wait_until_finished()
@ -245,7 +237,10 @@ class AnsibleHcloudLoadBalancer(Hcloud):
self._mark_as_changed()
load_balancer_type = self.module.params.get("load_balancer_type")
if load_balancer_type is not None and self.hcloud_load_balancer.load_balancer_type.name != load_balancer_type:
if (
load_balancer_type is not None
and self.hcloud_load_balancer.load_balancer_type.name != load_balancer_type
):
new_load_balancer_type = self.client.load_balancer_types.get_by_name(load_balancer_type)
if not new_load_balancer_type:
self.module.fail_json(msg="unknown load balancer type")
@ -295,7 +290,7 @@ class AnsibleHcloudLoadBalancer(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_one_of=[["id", "name"]],
mutually_exclusive=[["location", "network_zone"]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer_info
@ -37,7 +33,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud load_balancer infos
@ -260,8 +256,8 @@ hcloud_load_balancer_info:
sample: false
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -278,22 +274,25 @@ class AnsibleHcloudLoadBalancerInfo(Hcloud):
services = [self._prepare_service_result(service) for service in load_balancer.services]
targets = [self._prepare_target_result(target) for target in load_balancer.targets]
private_ipv4_address = None if len(load_balancer.private_net) == 0 else to_native(
load_balancer.private_net[0].ip)
tmp.append({
"id": to_native(load_balancer.id),
"name": to_native(load_balancer.name),
"ipv4_address": to_native(load_balancer.public_net.ipv4.ip),
"ipv6_address": to_native(load_balancer.public_net.ipv6.ip),
"private_ipv4_address": private_ipv4_address,
"load_balancer_type": to_native(load_balancer.load_balancer_type.name),
"location": to_native(load_balancer.location.name),
"labels": load_balancer.labels,
"delete_protection": load_balancer.protection["delete"],
"disable_public_interface": False if load_balancer.public_net.enabled else True,
"targets": targets,
"services": services
})
private_ipv4_address = (
None if len(load_balancer.private_net) == 0 else to_native(load_balancer.private_net[0].ip)
)
tmp.append(
{
"id": to_native(load_balancer.id),
"name": to_native(load_balancer.name),
"ipv4_address": to_native(load_balancer.public_net.ipv4.ip),
"ipv6_address": to_native(load_balancer.public_net.ipv6.ip),
"private_ipv4_address": private_ipv4_address,
"load_balancer_type": to_native(load_balancer.load_balancer_type.name),
"location": to_native(load_balancer.location.name),
"labels": load_balancer.labels,
"delete_protection": load_balancer.protection["delete"],
"disable_public_interface": False if load_balancer.public_net.enabled else True,
"targets": targets,
"services": services,
}
)
return tmp
@staticmethod
@ -305,8 +304,7 @@ class AnsibleHcloudLoadBalancerInfo(Hcloud):
"cookie_lifetime": service.http.cookie_name,
"redirect_http": service.http.redirect_http,
"sticky_sessions": service.http.sticky_sessions,
"certificates": [to_native(certificate.name) for certificate in
service.http.certificates],
"certificates": [to_native(certificate.name) for certificate in service.http.certificates],
}
health_check = {
"protocol": to_native(service.health_check.protocol),
@ -320,8 +318,7 @@ class AnsibleHcloudLoadBalancerInfo(Hcloud):
"domain": to_native(service.health_check.http.domain),
"path": to_native(service.health_check.http.path),
"response": to_native(service.health_check.http.response),
"certificates": [to_native(status_code) for status_code in
service.health_check.http.status_codes],
"certificates": [to_native(status_code) for status_code in service.health_check.http.status_codes],
"tls": service.health_check.http.tls,
}
return {
@ -337,7 +334,7 @@ class AnsibleHcloudLoadBalancerInfo(Hcloud):
def _prepare_target_result(target):
result = {
"type": to_native(target.type),
"use_private_ip": target.use_private_ip
"use_private_ip": target.use_private_ip,
}
if target.type == "server":
result["server"] = to_native(target.server.name)
@ -350,13 +347,11 @@ class AnsibleHcloudLoadBalancerInfo(Hcloud):
def get_load_balancers(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_load_balancer_info = [self.client.load_balancers.get_by_id(
self.module.params.get("id")
)]
self.hcloud_load_balancer_info = [self.client.load_balancers.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_load_balancer_info = [self.client.load_balancers.get_by_name(
self.module.params.get("name")
)]
self.hcloud_load_balancer_info = [
self.client.load_balancers.get_by_name(self.module.params.get("name"))
]
else:
params = {}
label_selector = self.module.params.get("label_selector")
@ -388,9 +383,7 @@ def main():
hcloud.get_load_balancers()
result = hcloud.get_result()
ansible_info = {
'hcloud_load_balancer_info': result['hcloud_load_balancer_info']
}
ansible_info = {"hcloud_load_balancer_info": result["hcloud_load_balancer_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer_network
@ -49,7 +45,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic Load Balancer network
@ -95,8 +91,8 @@ hcloud_load_balancer_network:
sample: 10.0.0.8
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -122,9 +118,7 @@ class AnsibleHcloudLoadBalancerNetwork(Hcloud):
self.module.fail_json(msg="Network does not exist: %s" % network)
load_balancer_name = self.module.params.get("load_balancer")
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(
load_balancer_name
)
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(load_balancer_name)
if not self.hcloud_load_balancer:
self.module.fail_json(msg="Load balancer does not exist: %s" % load_balancer_name)
@ -139,7 +133,7 @@ class AnsibleHcloudLoadBalancerNetwork(Hcloud):
def _create_load_balancer_network(self):
params = {
"network": self.hcloud_network
"network": self.hcloud_network,
}
if self.module.params.get("ip") is not None:
@ -168,7 +162,8 @@ class AnsibleHcloudLoadBalancerNetwork(Hcloud):
if not self.module.check_mode:
try:
self.hcloud_load_balancer.detach_from_network(
self.hcloud_load_balancer_network.network).wait_until_finished()
self.hcloud_load_balancer_network.network
).wait_until_finished()
self._mark_as_changed()
except Exception as e:
self.module.fail_json(msg=e.message)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer_service
@ -140,7 +136,7 @@ extends_documentation_fragment:
requirements:
- hcloud-python >= 1.8.1
'''
"""
EXAMPLES = """
- name: Create a basic Load Balancer service with Port 80
@ -283,14 +279,18 @@ hcloud_load_balancer_service:
sample: false
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
from hcloud.load_balancers.domain import LoadBalancerService, LoadBalancerServiceHttp, \
LoadBalancerHealthCheck, LoadBalancerHealtCheckHttp
from hcloud import APIException
from hcloud.load_balancers.domain import (
LoadBalancerHealtCheckHttp,
LoadBalancerHealthCheck,
LoadBalancerService,
LoadBalancerServiceHttp,
)
except ImportError:
APIException = None
@ -309,8 +309,9 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
"cookie_lifetime": self.hcloud_load_balancer_service.http.cookie_name,
"redirect_http": self.hcloud_load_balancer_service.http.redirect_http,
"sticky_sessions": self.hcloud_load_balancer_service.http.sticky_sessions,
"certificates": [to_native(certificate.name) for certificate in
self.hcloud_load_balancer_service.http.certificates],
"certificates": [
to_native(certificate.name) for certificate in self.hcloud_load_balancer_service.http.certificates
],
}
health_check = {
"protocol": to_native(self.hcloud_load_balancer_service.health_check.protocol),
@ -324,8 +325,10 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
"domain": to_native(self.hcloud_load_balancer_service.health_check.http.domain),
"path": to_native(self.hcloud_load_balancer_service.health_check.http.path),
"response": to_native(self.hcloud_load_balancer_service.health_check.http.response),
"certificates": [to_native(status_code) for status_code in
self.hcloud_load_balancer_service.health_check.http.status_codes],
"certificates": [
to_native(status_code)
for status_code in self.hcloud_load_balancer_service.health_check.http.status_codes
],
"tls": self.hcloud_load_balancer_service.health_check.http.tls,
}
return {
@ -341,9 +344,7 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
def _get_load_balancer(self):
try:
load_balancer_name = self.module.params.get("load_balancer")
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(
load_balancer_name
)
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(load_balancer_name)
if not self.hcloud_load_balancer:
self.module.fail_json(msg="Load balancer does not exist: %s" % load_balancer_name)
@ -352,19 +353,14 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
self.module.fail_json(msg=e.message)
def _create_load_balancer_service(self):
self.module.fail_on_missing_params(
required_params=["protocol"]
)
self.module.fail_on_missing_params(required_params=["protocol"])
if self.module.params.get("protocol") == "tcp":
self.module.fail_on_missing_params(
required_params=["destination_port"]
)
self.module.fail_on_missing_params(required_params=["destination_port"])
params = {
"protocol": self.module.params.get("protocol"),
"listen_port": self.module.params.get("listen_port"),
"proxyprotocol": self.module.params.get("proxyprotocol")
"proxyprotocol": self.module.params.get("proxyprotocol"),
}
if self.module.params.get("destination_port"):
@ -375,12 +371,14 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
if self.module.params.get("health_check"):
params["health_check"] = self.__get_service_health_checks(
health_check=self.module.params.get("health_check"))
health_check=self.module.params.get("health_check")
)
if not self.module.check_mode:
try:
self.hcloud_load_balancer.add_service(LoadBalancerService(**params)).wait_until_finished(
max_retries=1000)
max_retries=1000
)
except Exception as e:
self.module.fail_json(msg=e.message)
self._mark_as_changed()
@ -404,13 +402,9 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
hcloud_cert = None
try:
try:
hcloud_cert = self.client.certificates.get_by_name(
certificate
)
hcloud_cert = self.client.certificates.get_by_name(certificate)
except Exception:
hcloud_cert = self.client.certificates.get_by_id(
certificate
)
hcloud_cert = self.client.certificates.get_by_id(certificate)
except Exception as e:
self.module.fail_json(msg=e.message)
service_http.certificates.append(hcloud_cert)
@ -473,12 +467,14 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
if self.module.params.get("health_check") is not None:
params["health_check"] = self.__get_service_health_checks(
health_check=self.module.params.get("health_check"))
health_check=self.module.params.get("health_check")
)
changed = True
if not self.module.check_mode:
self.hcloud_load_balancer.update_service(LoadBalancerService(**params)).wait_until_finished(
max_retries=1000)
max_retries=1000
)
except Exception as e:
self.module.fail_json(msg=e.message)
self._get_load_balancer()
@ -505,7 +501,8 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
if not self.module.check_mode:
try:
self.hcloud_load_balancer.delete_service(self.hcloud_load_balancer_service).wait_until_finished(
max_retries=1000)
max_retries=1000
)
except Exception as e:
self.module.fail_json(msg=e.message)
self._mark_as_changed()
@ -528,26 +525,12 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
http={
"type": "dict",
"options": dict(
cookie_name={
"type": "str"
},
cookie_lifetime={
"type": "int"
},
sticky_sessions={
"type": "bool",
"default": False
},
redirect_http={
"type": "bool",
"default": False
},
certificates={
"type": "list",
"elements": "str"
},
)
cookie_name={"type": "str"},
cookie_lifetime={"type": "int"},
sticky_sessions={"type": "bool", "default": False},
redirect_http={"type": "bool", "default": False},
certificates={"type": "list", "elements": "str"},
),
},
health_check={
"type": "dict",
@ -556,42 +539,21 @@ class AnsibleHcloudLoadBalancerService(Hcloud):
"type": "str",
"choices": ["http", "https", "tcp"],
},
port={
"type": "int"
},
interval={
"type": "int"
},
timeout={
"type": "int"
},
retries={
"type": "int"
},
port={"type": "int"},
interval={"type": "int"},
timeout={"type": "int"},
retries={"type": "int"},
http={
"type": "dict",
"options": dict(
domain={
"type": "str"
},
path={
"type": "str"
},
response={
"type": "str"
},
status_codes={
"type": "list",
"elements": "str"
},
tls={
"type": "bool",
"default": False
},
)
}
)
domain={"type": "str"},
path={"type": "str"},
response={"type": "str"},
status_codes={"type": "list", "elements": "str"},
tls={"type": "bool", "default": False},
),
},
),
},
state={
"choices": ["absent", "present"],

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer_target
@ -67,7 +63,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a server Load Balancer target
@ -139,12 +135,16 @@ hcloud_load_balancer_target:
returned: always
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
from hcloud.load_balancers.domain import LoadBalancerTarget, LoadBalancerTargetLabelSelector, LoadBalancerTargetIP
from hcloud.load_balancers.domain import (
LoadBalancerTarget,
LoadBalancerTargetIP,
LoadBalancerTargetLabelSelector,
)
except ImportError:
LoadBalancerTarget = None
LoadBalancerTargetLabelSelector = None
@ -162,7 +162,7 @@ class AnsibleHcloudLoadBalancerTarget(Hcloud):
result = {
"type": to_native(self.hcloud_load_balancer_target.type),
"load_balancer": to_native(self.hcloud_load_balancer.name),
"use_private_ip": self.hcloud_load_balancer_target.use_private_ip
"use_private_ip": self.hcloud_load_balancer_target.use_private_ip,
}
if self.hcloud_load_balancer_target.type == "server":
@ -176,9 +176,7 @@ class AnsibleHcloudLoadBalancerTarget(Hcloud):
def _get_load_balancer_and_target(self):
try:
load_balancer_name = self.module.params.get("load_balancer")
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(
load_balancer_name
)
self.hcloud_load_balancer = self.client.load_balancers.get_by_name(load_balancer_name)
if not self.hcloud_load_balancer:
self.module.fail_json(msg="Load balancer does not exist: %s" % load_balancer_name)
@ -205,31 +203,29 @@ class AnsibleHcloudLoadBalancerTarget(Hcloud):
self.hcloud_load_balancer_target = target
def _create_load_balancer_target(self):
params = {
"target": None
}
params = {"target": None}
if self.module.params.get("type") == "server":
self.module.fail_on_missing_params(
required_params=["server"]
self.module.fail_on_missing_params(required_params=["server"])
params["target"] = LoadBalancerTarget(
type=self.module.params.get("type"),
server=self.hcloud_server,
use_private_ip=self.module.params.get("use_private_ip"),
)
params["target"] = LoadBalancerTarget(type=self.module.params.get("type"), server=self.hcloud_server,
use_private_ip=self.module.params.get("use_private_ip"))
elif self.module.params.get("type") == "label_selector":
self.module.fail_on_missing_params(
required_params=["label_selector"]
self.module.fail_on_missing_params(required_params=["label_selector"])
params["target"] = LoadBalancerTarget(
type=self.module.params.get("type"),
label_selector=LoadBalancerTargetLabelSelector(selector=self.module.params.get("label_selector")),
use_private_ip=self.module.params.get("use_private_ip"),
)
params["target"] = LoadBalancerTarget(type=self.module.params.get("type"),
label_selector=LoadBalancerTargetLabelSelector(
selector=self.module.params.get("label_selector")),
use_private_ip=self.module.params.get("use_private_ip"))
elif self.module.params.get("type") == "ip":
self.module.fail_on_missing_params(
required_params=["ip"]
self.module.fail_on_missing_params(required_params=["ip"])
params["target"] = LoadBalancerTarget(
type=self.module.params.get("type"),
ip=LoadBalancerTargetIP(ip=self.module.params.get("ip")),
use_private_ip=False,
)
params["target"] = LoadBalancerTarget(type=self.module.params.get("type"),
ip=LoadBalancerTargetIP(ip=self.module.params.get("ip")),
use_private_ip=False)
if not self.module.check_mode:
try:
@ -257,26 +253,24 @@ class AnsibleHcloudLoadBalancerTarget(Hcloud):
if not self.module.check_mode:
target = None
if self.module.params.get("type") == "server":
self.module.fail_on_missing_params(
required_params=["server"]
)
target = LoadBalancerTarget(type=self.module.params.get("type"),
server=self.hcloud_server)
self.module.fail_on_missing_params(required_params=["server"])
target = LoadBalancerTarget(type=self.module.params.get("type"), server=self.hcloud_server)
elif self.module.params.get("type") == "label_selector":
self.module.fail_on_missing_params(
required_params=["label_selector"]
self.module.fail_on_missing_params(required_params=["label_selector"])
target = LoadBalancerTarget(
type=self.module.params.get("type"),
label_selector=LoadBalancerTargetLabelSelector(
selector=self.module.params.get("label_selector")
),
use_private_ip=self.module.params.get("use_private_ip"),
)
target = LoadBalancerTarget(type=self.module.params.get("type"),
label_selector=LoadBalancerTargetLabelSelector(
selector=self.module.params.get("label_selector")),
use_private_ip=self.module.params.get("use_private_ip"))
elif self.module.params.get("type") == "ip":
self.module.fail_on_missing_params(
required_params=["ip"]
self.module.fail_on_missing_params(required_params=["ip"])
target = LoadBalancerTarget(
type=self.module.params.get("type"),
ip=LoadBalancerTargetIP(ip=self.module.params.get("ip")),
use_private_ip=False,
)
target = LoadBalancerTarget(type=self.module.params.get("type"),
ip=LoadBalancerTargetIP(ip=self.module.params.get("ip")),
use_private_ip=False)
try:
self.hcloud_load_balancer.remove_target(target).wait_until_finished()
except Exception as e:

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_load_balancer_type_info
@ -33,7 +29,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud Load Balancer type infos
@ -88,8 +84,8 @@ hcloud_load_balancer_type_info:
sample: 5
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -103,27 +99,29 @@ class AnsibleHcloudLoadBalancerTypeInfo(Hcloud):
for load_balancer_type in self.hcloud_load_balancer_type_info:
if load_balancer_type is not None:
tmp.append({
"id": to_native(load_balancer_type.id),
"name": to_native(load_balancer_type.name),
"description": to_native(load_balancer_type.description),
"max_connections": load_balancer_type.max_connections,
"max_services": load_balancer_type.max_services,
"max_targets": load_balancer_type.max_targets,
"max_assigned_certificates": load_balancer_type.max_assigned_certificates
})
tmp.append(
{
"id": to_native(load_balancer_type.id),
"name": to_native(load_balancer_type.name),
"description": to_native(load_balancer_type.description),
"max_connections": load_balancer_type.max_connections,
"max_services": load_balancer_type.max_services,
"max_targets": load_balancer_type.max_targets,
"max_assigned_certificates": load_balancer_type.max_assigned_certificates,
}
)
return tmp
def get_load_balancer_types(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_load_balancer_type_info = [self.client.load_balancer_types.get_by_id(
self.module.params.get("id")
)]
self.hcloud_load_balancer_type_info = [
self.client.load_balancer_types.get_by_id(self.module.params.get("id"))
]
elif self.module.params.get("name") is not None:
self.hcloud_load_balancer_type_info = [self.client.load_balancer_types.get_by_name(
self.module.params.get("name")
)]
self.hcloud_load_balancer_type_info = [
self.client.load_balancer_types.get_by_name(self.module.params.get("name"))
]
else:
self.hcloud_load_balancer_type_info = self.client.load_balancer_types.get_all()
@ -136,7 +134,7 @@ class AnsibleHcloudLoadBalancerTypeInfo(Hcloud):
argument_spec=dict(
id={"type": "int"},
name={"type": "str"},
**Hcloud.base_module_arguments()
**Hcloud.base_module_arguments(),
),
supports_check_mode=True,
)
@ -148,9 +146,7 @@ def main():
hcloud = AnsibleHcloudLoadBalancerTypeInfo(module)
hcloud.get_load_balancer_types()
result = hcloud.get_result()
ansible_info = {
'hcloud_load_balancer_type_info': result['hcloud_load_balancer_type_info']
}
ansible_info = {"hcloud_load_balancer_type_info": result["hcloud_load_balancer_type_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_location_info
@ -35,7 +31,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud location infos
@ -80,8 +76,8 @@ hcloud_location_info:
sample: Falkenstein
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -95,25 +91,23 @@ class AnsibleHcloudLocationInfo(Hcloud):
for location in self.hcloud_location_info:
if location is not None:
tmp.append({
"id": to_native(location.id),
"name": to_native(location.name),
"description": to_native(location.description),
"city": to_native(location.city),
"country": to_native(location.country)
})
tmp.append(
{
"id": to_native(location.id),
"name": to_native(location.name),
"description": to_native(location.description),
"city": to_native(location.city),
"country": to_native(location.country),
}
)
return tmp
def get_locations(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_location_info = [self.client.locations.get_by_id(
self.module.params.get("id")
)]
self.hcloud_location_info = [self.client.locations.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_location_info = [self.client.locations.get_by_name(
self.module.params.get("name")
)]
self.hcloud_location_info = [self.client.locations.get_by_name(self.module.params.get("name"))]
else:
self.hcloud_location_info = self.client.locations.get_all()
@ -126,7 +120,7 @@ class AnsibleHcloudLocationInfo(Hcloud):
argument_spec=dict(
id={"type": "int"},
name={"type": "str"},
**Hcloud.base_module_arguments()
**Hcloud.base_module_arguments(),
),
supports_check_mode=True,
)
@ -135,23 +129,23 @@ class AnsibleHcloudLocationInfo(Hcloud):
def main():
module = AnsibleHcloudLocationInfo.define_module()
is_old_facts = module._name == 'hcloud_location_facts'
is_old_facts = module._name == "hcloud_location_facts"
if is_old_facts:
module.deprecate("The 'hcloud_location_info' module has been renamed to 'hcloud_location_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_location_info' module has been renamed to 'hcloud_location_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudLocationInfo(module)
hcloud.get_locations()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_location_facts': result['hcloud_location_info']
}
ansible_info = {"hcloud_location_facts": result["hcloud_location_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_location_info': result['hcloud_location_info']
}
ansible_info = {"hcloud_location_info": result["hcloud_location_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_network
@ -64,7 +60,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic network
@ -120,8 +116,8 @@ hcloud_network:
mylabel: 123
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -143,21 +139,14 @@ class AnsibleHcloudNetwork(Hcloud):
def _get_network(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_network = self.client.networks.get_by_id(
self.module.params.get("id")
)
self.hcloud_network = self.client.networks.get_by_id(self.module.params.get("id"))
else:
self.hcloud_network = self.client.networks.get_by_name(
self.module.params.get("name")
)
self.hcloud_network = self.client.networks.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_network(self):
self.module.fail_on_missing_params(
required_params=["name", "ip_range"]
)
self.module.fail_on_missing_params(required_params=["name", "ip_range"])
params = {
"name": self.module.params.get("name"),
"ip_range": self.module.params.get("ip_range"),
@ -196,7 +185,10 @@ class AnsibleHcloudNetwork(Hcloud):
self._mark_as_changed()
expose_routes_to_vswitch = self.module.params.get("expose_routes_to_vswitch")
if expose_routes_to_vswitch is not None and expose_routes_to_vswitch != self.hcloud_network.expose_routes_to_vswitch:
if (
expose_routes_to_vswitch is not None
and expose_routes_to_vswitch != self.hcloud_network.expose_routes_to_vswitch
):
if not self.module.check_mode:
self.hcloud_network.update(expose_routes_to_vswitch=expose_routes_to_vswitch)
self._mark_as_changed()
@ -244,7 +236,7 @@ class AnsibleHcloudNetwork(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_one_of=[["id", "name"]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_network_info
@ -37,7 +33,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud network info
@ -185,8 +181,8 @@ hcloud_network_info:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -211,10 +207,7 @@ class AnsibleHcloudNetworkInfo(Hcloud):
subnets.append(prepared_subnet)
routes = []
for route in network.routes:
prepared_route = {
"destination": route.destination,
"gateway": route.gateway
}
prepared_route = {"destination": route.destination, "gateway": route.gateway}
routes.append(prepared_route)
servers = []
@ -238,32 +231,31 @@ class AnsibleHcloudNetworkInfo(Hcloud):
}
servers.append(prepared_server)
tmp.append({
"id": to_native(network.id),
"name": to_native(network.name),
"ip_range": to_native(network.ip_range),
"subnetworks": subnets,
"routes": routes,
"expose_routes_to_vswitch": network.expose_routes_to_vswitch,
"servers": servers,
"labels": network.labels,
"delete_protection": network.protection["delete"],
})
tmp.append(
{
"id": to_native(network.id),
"name": to_native(network.name),
"ip_range": to_native(network.ip_range),
"subnetworks": subnets,
"routes": routes,
"expose_routes_to_vswitch": network.expose_routes_to_vswitch,
"servers": servers,
"labels": network.labels,
"delete_protection": network.protection["delete"],
}
)
return tmp
def get_networks(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_network_info = [self.client.networks.get_by_id(
self.module.params.get("id")
)]
self.hcloud_network_info = [self.client.networks.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_network_info = [self.client.networks.get_by_name(
self.module.params.get("name")
)]
self.hcloud_network_info = [self.client.networks.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_network_info = self.client.networks.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_network_info = self.client.networks.get_all()
@ -289,9 +281,7 @@ def main():
hcloud = AnsibleHcloudNetworkInfo(module)
hcloud.get_networks()
result = hcloud.get_result()
info = {
'hcloud_network_info': result['hcloud_network_info']
}
info = {"hcloud_network_info": result["hcloud_network_info"]}
module.exit_json(**info)

View file

@ -1,12 +1,8 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
---
@ -111,9 +107,9 @@ hcloud_placement_group:
- 4712
"""
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
class AnsibleHcloudPlacementGroup(Hcloud):
@ -133,20 +129,14 @@ class AnsibleHcloudPlacementGroup(Hcloud):
def _get_placement_group(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_placement_group = self.client.placement_groups.get_by_id(
self.module.params.get("id")
)
self.hcloud_placement_group = self.client.placement_groups.get_by_id(self.module.params.get("id"))
elif self.module.params.get("name") is not None:
self.hcloud_placement_group = self.client.placement_groups.get_by_name(
self.module.params.get("name")
)
self.hcloud_placement_group = self.client.placement_groups.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_placement_group(self):
self.module.fail_on_missing_params(
required_params=["name"]
)
self.module.fail_on_missing_params(required_params=["name"])
params = {
"name": self.module.params.get("name"),
"type": self.module.params.get("type"),
@ -163,9 +153,7 @@ class AnsibleHcloudPlacementGroup(Hcloud):
def _update_placement_group(self):
name = self.module.params.get("name")
if name is not None and self.hcloud_placement_group.name != name:
self.module.fail_on_missing_params(
required_params=["id"]
)
self.module.fail_on_missing_params(required_params=["id"])
if not self.module.check_mode:
self.hcloud_placement_group.update(name=name)
self._mark_as_changed()
@ -207,8 +195,8 @@ class AnsibleHcloudPlacementGroup(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_if=[['state', 'present', ['name']]],
required_one_of=[["id", "name"]],
required_if=[["state", "present", ["name"]]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_primary_ip
@ -69,7 +65,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic IPv4 Primary IP
@ -135,8 +131,8 @@ hcloud_primary_ip:
mylabel: 123
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -159,27 +155,19 @@ class AnsibleHcloudPrimaryIP(Hcloud):
def _get_primary_ip(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_primary_ip = self.client.primary_ips.get_by_id(
self.module.params.get("id")
)
self.hcloud_primary_ip = self.client.primary_ips.get_by_id(self.module.params.get("id"))
else:
self.hcloud_primary_ip = self.client.primary_ips.get_by_name(
self.module.params.get("name")
)
self.hcloud_primary_ip = self.client.primary_ips.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_primary_ip(self):
self.module.fail_on_missing_params(
required_params=["type", "datacenter"]
)
self.module.fail_on_missing_params(required_params=["type", "datacenter"])
try:
params = {
"type": self.module.params.get("type"),
"name": self.module.params.get("name"),
"datacenter": self.client.datacenters.get_by_name(
self.module.params.get("datacenter")
)
"datacenter": self.client.datacenters.get_by_name(self.module.params.get("datacenter")),
}
if self.module.params.get("labels") is not None:
@ -249,7 +237,7 @@ class AnsibleHcloudPrimaryIP(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_one_of=[["id", "name"]],
supports_check_mode=True,
)

View file

@ -1,12 +1,8 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
---
@ -121,8 +117,8 @@ hcloud_primary_ip_info:
type: bool
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -139,34 +135,35 @@ class AnsibleHcloudPrimaryIPInfo(Hcloud):
dns_ptr = None
if len(primary_ip.dns_ptr) > 0:
dns_ptr = primary_ip.dns_ptr[0]["dns_ptr"]
tmp.append({
"id": to_native(primary_ip.id),
"name": to_native(primary_ip.name),
"ip": to_native(primary_ip.ip),
"type": to_native(primary_ip.type),
"assignee_id": to_native(primary_ip.assignee_id) if primary_ip.assignee_id is not None else None,
"assignee_type": to_native(primary_ip.assignee_type),
"home_location": to_native(primary_ip.datacenter.name),
"dns_ptr": to_native(dns_ptr) if dns_ptr is not None else None,
"labels": primary_ip.labels,
"delete_protection": primary_ip.protection["delete"],
})
tmp.append(
{
"id": to_native(primary_ip.id),
"name": to_native(primary_ip.name),
"ip": to_native(primary_ip.ip),
"type": to_native(primary_ip.type),
"assignee_id": (
to_native(primary_ip.assignee_id) if primary_ip.assignee_id is not None else None
),
"assignee_type": to_native(primary_ip.assignee_type),
"home_location": to_native(primary_ip.datacenter.name),
"dns_ptr": to_native(dns_ptr) if dns_ptr is not None else None,
"labels": primary_ip.labels,
"delete_protection": primary_ip.protection["delete"],
}
)
return tmp
def get_primary_ips(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_primary_ip_info = [self.client.primary_ips.get_by_id(
self.module.params.get("id")
)]
self.hcloud_primary_ip_info = [self.client.primary_ips.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_primary_ip_info = [self.client.primary_ips.get_by_name(
self.module.params.get("name")
)]
self.hcloud_primary_ip_info = [self.client.primary_ips.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_primary_ip_info = self.client.primary_ips.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_primary_ip_info = self.client.primary_ips.get_all()
@ -194,9 +191,7 @@ def main():
hcloud.get_primary_ips()
result = hcloud.get_result()
ansible_info = {
'hcloud_primary_ip_info': result['hcloud_primary_ip_info']
}
ansible_info = {"hcloud_primary_ip_info": result["hcloud_primary_ip_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_rdns
@ -61,7 +57,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a reverse DNS entry for a server
@ -138,10 +134,12 @@ hcloud_rdns:
sample: example.com
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import (
utils,
)
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils
class AnsibleHcloudReverseDNS(Hcloud):
@ -172,27 +170,19 @@ class AnsibleHcloudReverseDNS(Hcloud):
def _get_resource(self):
try:
if self.module.params.get("server"):
self.hcloud_resource = self.client.servers.get_by_name(
self.module.params.get("server")
)
self.hcloud_resource = self.client.servers.get_by_name(self.module.params.get("server"))
if self.hcloud_resource is None:
self.module.fail_json(msg="The selected server does not exist")
elif self.module.params.get("floating_ip"):
self.hcloud_resource = self.client.floating_ips.get_by_name(
self.module.params.get("floating_ip")
)
self.hcloud_resource = self.client.floating_ips.get_by_name(self.module.params.get("floating_ip"))
if self.hcloud_resource is None:
self.module.fail_json(msg="The selected Floating IP does not exist")
elif self.module.params.get("primary_ip"):
self.hcloud_resource = self.client.primary_ips.get_by_name(
self.module.params.get("primary_ip")
)
self.hcloud_resource = self.client.primary_ips.get_by_name(self.module.params.get("primary_ip"))
if self.hcloud_resource is None:
self.module.fail_json(msg="The selected Floating IP does not exist")
elif self.module.params.get("load_balancer"):
self.hcloud_resource = self.client.load_balancers.get_by_name(
self.module.params.get("load_balancer")
)
self.hcloud_resource = self.client.load_balancers.get_by_name(self.module.params.get("load_balancer"))
if self.hcloud_resource is None:
self.module.fail_json(msg="The selected Load Balancer does not exist")
except Exception as e:
@ -267,9 +257,7 @@ class AnsibleHcloudReverseDNS(Hcloud):
self.module.fail_json(msg="The given IP address is not valid")
def _create_rdns(self):
self.module.fail_on_missing_params(
required_params=["dns_ptr"]
)
self.module.fail_on_missing_params(required_params=["dns_ptr"])
params = {
"ip": self.module.params.get("ip_address"),
"dns_ptr": self.module.params.get("dns_ptr"),
@ -315,7 +303,7 @@ class AnsibleHcloudReverseDNS(Hcloud):
if self.hcloud_rdns is not None:
if not self.module.check_mode:
try:
self.hcloud_resource.change_dns_ptr(ip=self.hcloud_rdns['ip_address'], dns_ptr=None)
self.hcloud_resource.change_dns_ptr(ip=self.hcloud_rdns["ip_address"], dns_ptr=None)
except Exception as e:
self.module.fail_json(msg=e.message)
self._mark_as_changed()
@ -337,8 +325,8 @@ class AnsibleHcloudReverseDNS(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['server', 'floating_ip', 'load_balancer', 'primary_ip']],
mutually_exclusive=[["server", "floating_ip", 'load_balancer', 'primary_ip']],
required_one_of=[["server", "floating_ip", "load_balancer", "primary_ip"]],
mutually_exclusive=[["server", "floating_ip", "load_balancer", "primary_ip"]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_route
@ -50,7 +46,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic route
@ -91,8 +87,8 @@ hcloud_route:
sample: 10.0.0.1
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
@ -130,8 +126,7 @@ class AnsibleHcloudRoute(Hcloud):
def _create_route(self):
route = NetworkRoute(
destination=self.module.params.get("destination"),
gateway=self.module.params.get('gateway')
destination=self.module.params.get("destination"), gateway=self.module.params.get("gateway")
)
if not self.module.check_mode:

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_server
@ -157,7 +153,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic server
@ -332,16 +328,17 @@ hcloud_server:
version_added: "0.1.0"
"""
from ansible.module_utils.basic import AnsibleModule
from datetime import datetime, timedelta, timezone
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
from datetime import timedelta, datetime, timezone
try:
from hcloud.volumes.domain import Volume
from hcloud.ssh_keys.domain import SSHKey
from hcloud.servers.domain import Server, ServerCreatePublicNetwork
from hcloud.firewalls.domain import FirewallResource
from hcloud.servers.domain import Server, ServerCreatePublicNetwork
from hcloud.ssh_keys.domain import SSHKey
from hcloud.volumes.domain import Volume
except ImportError:
Volume = None
SSHKey = None
@ -357,19 +354,25 @@ class AnsibleHcloudServer(Hcloud):
def _prepare_result(self):
image = None if self.hcloud_server.image is None else to_native(self.hcloud_server.image.name)
placement_group = None if self.hcloud_server.placement_group is None else to_native(
self.hcloud_server.placement_group.name)
ipv4_address = None if self.hcloud_server.public_net.ipv4 is None else to_native(
self.hcloud_server.public_net.ipv4.ip)
placement_group = (
None if self.hcloud_server.placement_group is None else to_native(self.hcloud_server.placement_group.name)
)
ipv4_address = (
None if self.hcloud_server.public_net.ipv4 is None else to_native(self.hcloud_server.public_net.ipv4.ip)
)
ipv6 = None if self.hcloud_server.public_net.ipv6 is None else to_native(self.hcloud_server.public_net.ipv6.ip)
backup_window = None if self.hcloud_server.backup_window is None else to_native(self.hcloud_server.backup_window)
backup_window = (
None if self.hcloud_server.backup_window is None else to_native(self.hcloud_server.backup_window)
)
return {
"id": to_native(self.hcloud_server.id),
"name": to_native(self.hcloud_server.name),
"ipv4_address": ipv4_address,
"ipv6": ipv6,
"private_networks": [to_native(net.network.name) for net in self.hcloud_server.private_net],
"private_networks_info": [{"name": to_native(net.network.name), "ip": net.ip} for net in self.hcloud_server.private_net],
"private_networks_info": [
{"name": to_native(net.network.name), "ip": net.ip} for net in self.hcloud_server.private_net
],
"image": image,
"server_type": to_native(self.hcloud_server.server_type.name),
"datacenter": to_native(self.hcloud_server.datacenter.name),
@ -386,20 +389,14 @@ class AnsibleHcloudServer(Hcloud):
def _get_server(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_server = self.client.servers.get_by_id(
self.module.params.get("id")
)
self.hcloud_server = self.client.servers.get_by_id(self.module.params.get("id"))
else:
self.hcloud_server = self.client.servers.get_by_name(
self.module.params.get("name")
)
self.hcloud_server = self.client.servers.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_server(self):
self.module.fail_on_missing_params(
required_params=["name", "server_type", "image"]
)
self.module.fail_on_missing_params(required_params=["name", "server_type", "image"])
server_type = self._get_server_type()
@ -412,8 +409,8 @@ class AnsibleHcloudServer(Hcloud):
"placement_group": self._get_placement_group(),
"public_net": ServerCreatePublicNetwork(
enable_ipv4=self.module.params.get("enable_ipv4"),
enable_ipv6=self.module.params.get("enable_ipv6")
)
enable_ipv6=self.module.params.get("enable_ipv6"),
),
}
if self.module.params.get("ipv4") is not None:
@ -438,15 +435,10 @@ class AnsibleHcloudServer(Hcloud):
params["networks"] = _networks
if self.module.params.get("ssh_keys") is not None:
params["ssh_keys"] = [
SSHKey(name=ssh_key_name)
for ssh_key_name in self.module.params.get("ssh_keys")
]
params["ssh_keys"] = [SSHKey(name=ssh_key_name) for ssh_key_name in self.module.params.get("ssh_keys")]
if self.module.params.get("volumes") is not None:
params["volumes"] = [
Volume(id=volume_id) for volume_id in self.module.params.get("volumes")
]
params["volumes"] = [Volume(id=volume_id) for volume_id in self.module.params.get("volumes")]
if self.module.params.get("firewalls") is not None:
params["firewalls"] = []
for fw in self.module.params.get("firewalls"):
@ -462,13 +454,9 @@ class AnsibleHcloudServer(Hcloud):
params["location"] = None
params["datacenter"] = None
elif self.module.params.get("location") is not None and self.module.params.get("datacenter") is None:
params["location"] = self.client.locations.get_by_name(
self.module.params.get("location")
)
params["location"] = self.client.locations.get_by_name(self.module.params.get("location"))
elif self.module.params.get("location") is None and self.module.params.get("datacenter") is not None:
params["datacenter"] = self.client.datacenters.get_by_name(
self.module.params.get("datacenter")
)
params["datacenter"] = self.client.datacenters.get_by_name(self.module.params.get("datacenter"))
if self.module.params.get("state") == "stopped":
params["start_after_create"] = False
@ -493,16 +481,22 @@ class AnsibleHcloudServer(Hcloud):
rebuild_protection = self.module.params.get("rebuild_protection")
if delete_protection is not None and rebuild_protection is not None:
self._get_server()
self.hcloud_server.change_protection(delete=delete_protection,
rebuild=rebuild_protection).wait_until_finished()
self.hcloud_server.change_protection(
delete=delete_protection,
rebuild=rebuild_protection,
).wait_until_finished()
except Exception as e:
self.module.fail_json(msg=e.message)
self._mark_as_changed()
self._get_server()
def _get_image(self, server_type):
image_resp = self.client.images.get_list(name=self.module.params.get("image"), architecture=server_type.architecture, include_deprecated=True)
images = getattr(image_resp, 'images')
image_resp = self.client.images.get_list(
name=self.module.params.get("image"),
architecture=server_type.architecture,
include_deprecated=True,
)
images = getattr(image_resp, "images")
image = None
if images is not None and len(images) > 0:
# If image name is not available look for id instead
@ -511,29 +505,31 @@ class AnsibleHcloudServer(Hcloud):
try:
image = self.client.images.get_by_id(self.module.params.get("image"))
except Exception:
self.module.fail_json(msg="Image %s was not found" % self.module.params.get('image'))
self.module.fail_json(msg="Image %s was not found" % self.module.params.get("image"))
if image.deprecated is not None:
available_until = image.deprecated + timedelta(days=90)
if self.module.params.get("allow_deprecated_image"):
self.module.warn(
"You try to use a deprecated image. The image %s will continue to be available until %s." % (
image.name, available_until.strftime('%Y-%m-%d')))
"You try to use a deprecated image. The image %s will continue to be available until %s."
% (image.name, available_until.strftime("%Y-%m-%d"))
)
else:
self.module.fail_json(
msg=("You try to use a deprecated image. The image %s will continue to be available until %s." +
" If you want to use this image use allow_deprecated_image=true."
) % (image.name, available_until.strftime('%Y-%m-%d')))
msg=(
"You try to use a deprecated image. The image %s will continue to be available until %s."
" If you want to use this image use allow_deprecated_image=true."
)
% (image.name, available_until.strftime("%Y-%m-%d"))
)
return image
def _get_server_type(self):
server_type = self.client.server_types.get_by_name(
self.module.params.get("server_type")
)
server_type = self.client.server_types.get_by_name(self.module.params.get("server_type"))
if server_type is None:
try:
server_type = self.client.server_types.get_by_id(self.module.params.get("server_type"))
except Exception:
self.module.fail_json(msg="server_type %s was not found" % self.module.params.get('server_type'))
self.module.fail_json(msg="server_type %s was not found" % self.module.params.get("server_type"))
self._check_and_warn_deprecated_server(server_type)
@ -545,31 +541,33 @@ class AnsibleHcloudServer(Hcloud):
if server_type.deprecation.unavailable_after < datetime.now(timezone.utc):
self.module.warn(
'Attention: The server plan %s is deprecated and can no longer be ordered. Existing servers of ' % server_type.name
+ 'that plan will continue to work as before and no action is required on your part. It is possible '
'to migrate this server to another server plan by setting the server_type parameter on the hetzner.hcloud.hcloud_server module.'
"Attention: The server plan %s is deprecated and can no longer be ordered. Existing servers of "
% server_type.name
+ "that plan will continue to work as before and no action is required on your part. It is possible "
"to migrate this server to another server plan by setting the server_type parameter on the hetzner.hcloud.hcloud_server module."
)
else:
self.module.warn(
'Attention: The server plan % is deprecated and will no longer be available for order as of ' % server_type.name
+ '%s. Existing servers of that plan will continue to work as before ' % server_type.deprecation.unavailable_after.strftime("%Y-%m-%d")
+ 'and no action is required on your part. It is possible to migrate this server to another server plan by setting '
'the server_type parameter on the hetzner.hcloud.hcloud_server module.'
"Attention: The server plan % is deprecated and will no longer be available for order as of "
% server_type.name
+ "%s. Existing servers of that plan will continue to work as before "
% server_type.deprecation.unavailable_after.strftime("%Y-%m-%d")
+ "and no action is required on your part. It is possible to migrate this server to another server plan by setting "
"the server_type parameter on the hetzner.hcloud.hcloud_server module."
)
def _get_placement_group(self):
if self.module.params.get("placement_group") is None:
return None
placement_group = self.client.placement_groups.get_by_name(
self.module.params.get("placement_group")
)
placement_group = self.client.placement_groups.get_by_name(self.module.params.get("placement_group"))
if placement_group is None:
try:
placement_group = self.client.placement_groups.get_by_id(self.module.params.get("placement_group"))
except Exception:
self.module.fail_json(
msg="placement_group %s was not found" % self.module.params.get("placement_group"))
msg="placement_group %s was not found" % self.module.params.get("placement_group")
)
return placement_group
@ -577,15 +575,12 @@ class AnsibleHcloudServer(Hcloud):
if self.module.params.get(field) is None:
return None
primary_ip = self.client.primary_ips.get_by_name(
self.module.params.get(field)
)
primary_ip = self.client.primary_ips.get_by_name(self.module.params.get(field))
if primary_ip is None:
try:
primary_ip = self.client.primary_ips.get_by_id(self.module.params.get(field))
except Exception as e:
self.module.fail_json(
msg="primary_ip %s was not found" % self.module.params.get(field))
self.module.fail_json(msg="primary_ip %s was not found" % self.module.params.get(field))
return primary_ip
@ -660,12 +655,9 @@ class AnsibleHcloudServer(Hcloud):
self._mark_as_changed()
else:
placement_group = self._get_placement_group()
if (
placement_group is not None and
(
self.hcloud_server.placement_group is None or
self.hcloud_server.placement_group.id != placement_group.id
)
if placement_group is not None and (
self.hcloud_server.placement_group is None
or self.hcloud_server.placement_group.id != placement_group.id
):
self.stop_server_if_forced()
if not self.module.check_mode:
@ -674,9 +666,9 @@ class AnsibleHcloudServer(Hcloud):
if "ipv4" in self.module.params:
if (
self.module.params["ipv4"] is None and
self.hcloud_server.public_net.primary_ipv4 is not None and
not self.module.params.get("enable_ipv4")
self.module.params["ipv4"] is None
and self.hcloud_server.public_net.primary_ipv4 is not None
and not self.module.params.get("enable_ipv4")
):
self.stop_server_if_forced()
if not self.module.check_mode:
@ -684,12 +676,9 @@ class AnsibleHcloudServer(Hcloud):
self._mark_as_changed()
else:
primary_ip = self._get_primary_ip("ipv4")
if (
primary_ip is not None and
(
self.hcloud_server.public_net.primary_ipv4 is None or
self.hcloud_server.public_net.primary_ipv4.id != primary_ip.id
)
if primary_ip is not None and (
self.hcloud_server.public_net.primary_ipv4 is None
or self.hcloud_server.public_net.primary_ipv4.id != primary_ip.id
):
self.stop_server_if_forced()
if not self.module.check_mode:
@ -699,9 +688,9 @@ class AnsibleHcloudServer(Hcloud):
self._mark_as_changed()
if "ipv6" in self.module.params:
if (
(self.module.params["ipv6"] is None or self.module.params["ipv6"] == "") and
self.hcloud_server.public_net.primary_ipv6 is not None and
not self.module.params.get("enable_ipv6")
(self.module.params["ipv6"] is None or self.module.params["ipv6"] == "")
and self.hcloud_server.public_net.primary_ipv6 is not None
and not self.module.params.get("enable_ipv6")
):
self.stop_server_if_forced()
if not self.module.check_mode:
@ -709,12 +698,9 @@ class AnsibleHcloudServer(Hcloud):
self._mark_as_changed()
else:
primary_ip = self._get_primary_ip("ipv6")
if (
primary_ip is not None and
(
self.hcloud_server.public_net.primary_ipv6 is None or
self.hcloud_server.public_net.primary_ipv6.id != primary_ip.id
)
if primary_ip is not None and (
self.hcloud_server.public_net.primary_ipv6 is None
or self.hcloud_server.public_net.primary_ipv6.id != primary_ip.id
):
self.stop_server_if_forced()
if not self.module.check_mode:
@ -729,11 +715,10 @@ class AnsibleHcloudServer(Hcloud):
else:
_networks = {}
for network_name_or_id in self.module.params.get("private_networks"):
_found_network = self.client.networks.get_by_name(network_name_or_id) \
or self.client.networks.get_by_id(network_name_or_id)
_networks.update(
{_found_network.id: _found_network}
)
_found_network = self.client.networks.get_by_name(
network_name_or_id
) or self.client.networks.get_by_id(network_name_or_id)
_networks.update({_found_network.id: _found_network})
networks_target = _networks
networks_is = dict()
for p_network in self.hcloud_server.private_net:
@ -762,9 +747,7 @@ class AnsibleHcloudServer(Hcloud):
timeout = 100
if self.module.params.get("upgrade_disk"):
timeout = (
1000
) # When we upgrade the disk to the resize progress takes some more time.
timeout = 1000 # When we upgrade the disk to the resize progress takes some more time.
if not self.module.check_mode:
self.hcloud_server.change_type(
server_type=self._get_server_type(),
@ -772,26 +755,23 @@ class AnsibleHcloudServer(Hcloud):
).wait_until_finished(timeout)
self._mark_as_changed()
if (
not self.module.check_mode and
(
(
self.module.params.get("state") == "present" and
previous_server_status == Server.STATUS_RUNNING
) or
self.module.params.get("state") == "started"
)
if not self.module.check_mode and (
(self.module.params.get("state") == "present" and previous_server_status == Server.STATUS_RUNNING)
or self.module.params.get("state") == "started"
):
self.start_server()
delete_protection = self.module.params.get("delete_protection")
rebuild_protection = self.module.params.get("rebuild_protection")
if (delete_protection is not None and rebuild_protection is not None) and (
delete_protection != self.hcloud_server.protection["delete"] or rebuild_protection !=
self.hcloud_server.protection["rebuild"]):
delete_protection != self.hcloud_server.protection["delete"]
or rebuild_protection != self.hcloud_server.protection["rebuild"]
):
if not self.module.check_mode:
self.hcloud_server.change_protection(delete=delete_protection,
rebuild=rebuild_protection).wait_until_finished()
self.hcloud_server.change_protection(
delete=delete_protection,
rebuild=rebuild_protection,
).wait_until_finished()
self._mark_as_changed()
self._get_server()
except Exception as e:
@ -799,11 +779,13 @@ class AnsibleHcloudServer(Hcloud):
def _set_rescue_mode(self, rescue_mode):
if self.module.params.get("ssh_keys"):
resp = self.hcloud_server.enable_rescue(type=rescue_mode,
ssh_keys=[self.client.ssh_keys.get_by_name(ssh_key_name).id
for
ssh_key_name in
self.module.params.get("ssh_keys")])
resp = self.hcloud_server.enable_rescue(
type=rescue_mode,
ssh_keys=[
self.client.ssh_keys.get_by_name(ssh_key_name).id
for ssh_key_name in self.module.params.get("ssh_keys")
],
)
else:
resp = self.hcloud_server.enable_rescue(type=rescue_mode)
resp.action.wait_until_finished()
@ -835,9 +817,9 @@ class AnsibleHcloudServer(Hcloud):
previous_server_status = self.hcloud_server.status
if previous_server_status == Server.STATUS_RUNNING and not self.module.check_mode:
if (
self.module.params.get("force_upgrade") or
self.module.params.get("force") or
self.module.params.get("state") == "stopped"
self.module.params.get("force_upgrade")
or self.module.params.get("force")
or self.module.params.get("state") == "stopped"
):
self.stop_server() # Only stopped server can be upgraded
return previous_server_status
@ -850,13 +832,12 @@ class AnsibleHcloudServer(Hcloud):
return None
def rebuild_server(self):
self.module.fail_on_missing_params(
required_params=["image"]
)
self.module.fail_on_missing_params(required_params=["image"])
try:
if not self.module.check_mode:
image = self._get_image(self.hcloud_server.server_type)
self.client.servers.rebuild(self.hcloud_server, image).wait_until_finished(1000) # When we rebuild the server progress takes some more time.
# When we rebuild the server progress takes some more time.
self.client.servers.rebuild(self.hcloud_server, image).wait_until_finished(1000)
self._mark_as_changed()
self._get_server()
@ -916,7 +897,7 @@ class AnsibleHcloudServer(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_one_of=[["id", "name"]],
mutually_exclusive=[["location", "datacenter"]],
required_together=[["delete_protection", "rebuild_protection"]],
supports_check_mode=True,

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_server_info
@ -39,7 +35,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud server infos
@ -143,8 +139,8 @@ hcloud_server_info:
version_added: "0.1.0"
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -163,40 +159,41 @@ class AnsibleHcloudServerInfo(Hcloud):
ipv4_address = None if server.public_net.ipv4 is None else to_native(server.public_net.ipv4.ip)
ipv6 = None if server.public_net.ipv6 is None else to_native(server.public_net.ipv6.ip)
backup_window = None if server.backup_window is None else to_native(server.backup_window)
tmp.append({
"id": to_native(server.id),
"name": to_native(server.name),
"ipv4_address": ipv4_address,
"ipv6": ipv6,
"private_networks": [to_native(net.network.name) for net in server.private_net],
"private_networks_info": [{"name": to_native(net.network.name), "ip": net.ip} for net in server.private_net],
"image": image,
"server_type": to_native(server.server_type.name),
"datacenter": to_native(server.datacenter.name),
"location": to_native(server.datacenter.location.name),
"placement_group": placement_group,
"rescue_enabled": server.rescue_enabled,
"backup_window": backup_window,
"labels": server.labels,
"status": to_native(server.status),
"delete_protection": server.protection["delete"],
"rebuild_protection": server.protection["rebuild"],
})
tmp.append(
{
"id": to_native(server.id),
"name": to_native(server.name),
"ipv4_address": ipv4_address,
"ipv6": ipv6,
"private_networks": [to_native(net.network.name) for net in server.private_net],
"private_networks_info": [
{"name": to_native(net.network.name), "ip": net.ip} for net in server.private_net
],
"image": image,
"server_type": to_native(server.server_type.name),
"datacenter": to_native(server.datacenter.name),
"location": to_native(server.datacenter.location.name),
"placement_group": placement_group,
"rescue_enabled": server.rescue_enabled,
"backup_window": backup_window,
"labels": server.labels,
"status": to_native(server.status),
"delete_protection": server.protection["delete"],
"rebuild_protection": server.protection["rebuild"],
}
)
return tmp
def get_servers(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_server_info = [self.client.servers.get_by_id(
self.module.params.get("id")
)]
self.hcloud_server_info = [self.client.servers.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_server_info = [self.client.servers.get_by_name(
self.module.params.get("name")
)]
self.hcloud_server_info = [self.client.servers.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_server_info = self.client.servers.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_server_info = self.client.servers.get_all()
@ -219,24 +216,24 @@ class AnsibleHcloudServerInfo(Hcloud):
def main():
module = AnsibleHcloudServerInfo.define_module()
is_old_facts = module._name == 'hcloud_server_facts'
is_old_facts = module._name == "hcloud_server_facts"
if is_old_facts:
module.deprecate("The 'hcloud_server_facts' module has been renamed to 'hcloud_server_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_server_facts' module has been renamed to 'hcloud_server_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudServerInfo(module)
hcloud.get_servers()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_server_facts': result['hcloud_server_info']
}
ansible_info = {"hcloud_server_facts": result["hcloud_server_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_server_info': result['hcloud_server_info']
}
ansible_info = {"hcloud_server_info": result["hcloud_server_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_server_network
@ -54,7 +50,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic server network
@ -115,8 +111,8 @@ hcloud_server_network:
sample: [10.1.0.1, ...]
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
@ -155,7 +151,7 @@ class AnsibleHcloudServerNetwork(Hcloud):
def _create_server_network(self):
params = {
"network": self.hcloud_network
"network": self.hcloud_network,
}
if self.module.params.get("ip") is not None:
@ -175,7 +171,7 @@ class AnsibleHcloudServerNetwork(Hcloud):
def _update_server_network(self):
params = {
"network": self.hcloud_network
"network": self.hcloud_network,
}
alias_ips = self.module.params.get("alias_ips")
if alias_ips is not None and sorted(self.hcloud_server_network.alias_ips) != sorted(alias_ips):

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_server_type_info
@ -35,7 +31,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud server type infos
@ -126,8 +122,8 @@ hcloud_server_type_info:
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -141,34 +137,34 @@ class AnsibleHcloudServerTypeInfo(Hcloud):
for server_type in self.hcloud_server_type_info:
if server_type is not None:
tmp.append({
"id": to_native(server_type.id),
"name": to_native(server_type.name),
"description": to_native(server_type.description),
"cores": server_type.cores,
"memory": server_type.memory,
"disk": server_type.disk,
"storage_type": to_native(server_type.storage_type),
"cpu_type": to_native(server_type.cpu_type),
"architecture": to_native(server_type.architecture),
"included_traffic": server_type.included_traffic,
"deprecation": {
"announced": server_type.deprecation.announced.isoformat(),
"unavailable_after": server_type.deprecation.unavailable_after.isoformat(),
} if server_type.deprecation is not None else None
})
tmp.append(
{
"id": to_native(server_type.id),
"name": to_native(server_type.name),
"description": to_native(server_type.description),
"cores": server_type.cores,
"memory": server_type.memory,
"disk": server_type.disk,
"storage_type": to_native(server_type.storage_type),
"cpu_type": to_native(server_type.cpu_type),
"architecture": to_native(server_type.architecture),
"included_traffic": server_type.included_traffic,
"deprecation": {
"announced": server_type.deprecation.announced.isoformat(),
"unavailable_after": server_type.deprecation.unavailable_after.isoformat(),
}
if server_type.deprecation is not None
else None,
}
)
return tmp
def get_server_types(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_server_type_info = [self.client.server_types.get_by_id(
self.module.params.get("id")
)]
self.hcloud_server_type_info = [self.client.server_types.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_server_type_info = [self.client.server_types.get_by_name(
self.module.params.get("name")
)]
self.hcloud_server_type_info = [self.client.server_types.get_by_name(self.module.params.get("name"))]
else:
self.hcloud_server_type_info = self.client.server_types.get_all()
@ -181,7 +177,7 @@ class AnsibleHcloudServerTypeInfo(Hcloud):
argument_spec=dict(
id={"type": "int"},
name={"type": "str"},
**Hcloud.base_module_arguments()
**Hcloud.base_module_arguments(),
),
supports_check_mode=True,
)
@ -190,23 +186,23 @@ class AnsibleHcloudServerTypeInfo(Hcloud):
def main():
module = AnsibleHcloudServerTypeInfo.define_module()
is_old_facts = module._name == 'hcloud_server_type_facts'
is_old_facts = module._name == "hcloud_server_type_facts"
if is_old_facts:
module.deprecate("The 'hcloud_server_type_info' module has been renamed to 'hcloud_server_type_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_server_type_info' module has been renamed to 'hcloud_server_type_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudServerTypeInfo(module)
hcloud.get_server_types()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_server_type_info': result['hcloud_server_type_info']
}
ansible_info = {"hcloud_server_type_info": result["hcloud_server_type_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_server_type_info': result['hcloud_server_type_info']
}
ansible_info = {"hcloud_server_type_info": result["hcloud_server_type_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_ssh_key
@ -55,7 +51,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic ssh_key
@ -114,8 +110,8 @@ hcloud_ssh_key:
mylabel: 123
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -136,29 +132,21 @@ class AnsibleHcloudSSHKey(Hcloud):
def _get_ssh_key(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_ssh_key = self.client.ssh_keys.get_by_id(
self.module.params.get("id")
)
self.hcloud_ssh_key = self.client.ssh_keys.get_by_id(self.module.params.get("id"))
elif self.module.params.get("fingerprint") is not None:
self.hcloud_ssh_key = self.client.ssh_keys.get_by_fingerprint(
self.module.params.get("fingerprint")
)
self.hcloud_ssh_key = self.client.ssh_keys.get_by_fingerprint(self.module.params.get("fingerprint"))
elif self.module.params.get("name") is not None:
self.hcloud_ssh_key = self.client.ssh_keys.get_by_name(
self.module.params.get("name")
)
self.hcloud_ssh_key = self.client.ssh_keys.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_ssh_key(self):
self.module.fail_on_missing_params(
required_params=["name", "public_key"]
)
self.module.fail_on_missing_params(required_params=["name", "public_key"])
params = {
"name": self.module.params.get("name"),
"public_key": self.module.params.get("public_key"),
"labels": self.module.params.get("labels")
"labels": self.module.params.get("labels"),
}
if not self.module.check_mode:
@ -172,9 +160,7 @@ class AnsibleHcloudSSHKey(Hcloud):
def _update_ssh_key(self):
name = self.module.params.get("name")
if name is not None and self.hcloud_ssh_key.name != name:
self.module.fail_on_missing_params(
required_params=["id"]
)
self.module.fail_on_missing_params(required_params=["id"])
if not self.module.check_mode:
self.hcloud_ssh_key.update(name=name)
self._mark_as_changed()
@ -220,8 +206,8 @@ class AnsibleHcloudSSHKey(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name', 'fingerprint']],
required_if=[['state', 'present', ['name']]],
required_one_of=[["id", "name", "fingerprint"]],
required_if=[["state", "present", ["name"]]],
supports_check_mode=True,
)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_ssh_key_info
short_description: Gather infos about your Hetzner Cloud ssh_keys.
@ -38,7 +34,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud sshkey infos
@ -80,8 +76,8 @@ hcloud_ssh_key_info:
returned: always
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -95,32 +91,31 @@ class AnsibleHcloudSSHKeyInfo(Hcloud):
for ssh_key in self.hcloud_ssh_key_info:
if ssh_key:
ssh_keys.append({
"id": to_native(ssh_key.id),
"name": to_native(ssh_key.name),
"fingerprint": to_native(ssh_key.fingerprint),
"public_key": to_native(ssh_key.public_key),
"labels": ssh_key.labels
})
ssh_keys.append(
{
"id": to_native(ssh_key.id),
"name": to_native(ssh_key.name),
"fingerprint": to_native(ssh_key.fingerprint),
"public_key": to_native(ssh_key.public_key),
"labels": ssh_key.labels,
}
)
return ssh_keys
def get_ssh_keys(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_ssh_key_info = [self.client.ssh_keys.get_by_id(
self.module.params.get("id")
)]
self.hcloud_ssh_key_info = [self.client.ssh_keys.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_ssh_key_info = [self.client.ssh_keys.get_by_name(
self.module.params.get("name")
)]
self.hcloud_ssh_key_info = [self.client.ssh_keys.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("fingerprint") is not None:
self.hcloud_ssh_key_info = [self.client.ssh_keys.get_by_fingerprint(
self.module.params.get("fingerprint")
)]
self.hcloud_ssh_key_info = [
self.client.ssh_keys.get_by_fingerprint(self.module.params.get("fingerprint"))
]
elif self.module.params.get("label_selector") is not None:
self.hcloud_ssh_key_info = self.client.ssh_keys.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_ssh_key_info = self.client.ssh_keys.get_all()
@ -144,24 +139,24 @@ class AnsibleHcloudSSHKeyInfo(Hcloud):
def main():
module = AnsibleHcloudSSHKeyInfo.define_module()
is_old_facts = module._name == 'hcloud_ssh_key_facts'
is_old_facts = module._name == "hcloud_ssh_key_facts"
if is_old_facts:
module.deprecate("The 'hcloud_ssh_key_facts' module has been renamed to 'hcloud_ssh_key_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_ssh_key_facts' module has been renamed to 'hcloud_ssh_key_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudSSHKeyInfo(module)
hcloud.get_ssh_keys()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_ssh_key_facts': result['hcloud_ssh_key_info']
}
ansible_info = {"hcloud_ssh_key_facts": result["hcloud_ssh_key_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_ssh_key_info': result['hcloud_ssh_key_info']
}
ansible_info = {"hcloud_ssh_key_info": result["hcloud_ssh_key_info"]}
module.exit_json(**ansible_info)

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_subnetwork
@ -61,7 +57,7 @@ requirements:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a basic subnetwork
@ -128,8 +124,8 @@ hcloud_subnetwork:
sample: 10.0.0.1
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
try:
@ -170,14 +166,12 @@ class AnsibleHcloudSubnetwork(Hcloud):
def _create_subnetwork(self):
params = {
"ip_range": self.module.params.get("ip_range"),
"type": self.module.params.get('type'),
"network_zone": self.module.params.get('network_zone')
"type": self.module.params.get("type"),
"network_zone": self.module.params.get("network_zone"),
}
if self.module.params.get('type') == NetworkSubnet.TYPE_VSWITCH:
self.module.fail_on_missing_params(
required_params=["vswitch_id"]
)
params["vswitch_id"] = self.module.params.get('vswitch_id')
if self.module.params.get("type") == NetworkSubnet.TYPE_VSWITCH:
self.module.fail_on_missing_params(required_params=["vswitch_id"])
params["vswitch_id"] = self.module.params.get("vswitch_id")
if not self.module.check_mode:
try:
@ -213,11 +207,7 @@ class AnsibleHcloudSubnetwork(Hcloud):
argument_spec=dict(
network={"type": "str", "required": True},
network_zone={"type": "str", "required": True},
type={
"type": "str",
"required": True,
"choices": ["server", "cloud", "vswitch"]
},
type={"type": "str", "required": True, "choices": ["server", "cloud", "vswitch"]},
ip_range={"type": "str", "required": True},
vswitch_id={"type": "int"},
state={

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_volume
@ -75,7 +71,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Create a Volume
@ -161,8 +157,8 @@ hcloud_volume:
version_added: "0.1.0"
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -190,31 +186,25 @@ class AnsibleHcloudVolume(Hcloud):
def _get_volume(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_volume = self.client.volumes.get_by_id(
self.module.params.get("id")
)
self.hcloud_volume = self.client.volumes.get_by_id(self.module.params.get("id"))
else:
self.hcloud_volume = self.client.volumes.get_by_name(
self.module.params.get("name")
)
self.hcloud_volume = self.client.volumes.get_by_name(self.module.params.get("name"))
except Exception as e:
self.module.fail_json(msg=e.message)
def _create_volume(self):
self.module.fail_on_missing_params(
required_params=["name", "size"]
)
self.module.fail_on_missing_params(required_params=["name", "size"])
params = {
"name": self.module.params.get("name"),
"size": self.module.params.get("size"),
"automount": self.module.params.get("automount"),
"format": self.module.params.get("format"),
"labels": self.module.params.get("labels")
"labels": self.module.params.get("labels"),
}
if self.module.params.get("server") is not None:
params['server'] = self.client.servers.get_by_name(self.module.params.get("server"))
params["server"] = self.client.servers.get_by_name(self.module.params.get("server"))
elif self.module.params.get("location") is not None:
params['location'] = self.client.locations.get_by_name(self.module.params.get("location"))
params["location"] = self.client.locations.get_by_name(self.module.params.get("location"))
else:
self.module.fail_json(msg="server or location is required")
@ -304,9 +294,7 @@ class AnsibleHcloudVolume(Hcloud):
server={"type": "str"},
labels={"type": "dict"},
automount={"type": "bool", "default": False},
format={"type": "str",
"choices": ['xfs', 'ext4'],
},
format={"type": "str", "choices": ["xfs", "ext4"]},
delete_protection={"type": "bool"},
state={
"choices": ["absent", "present"],
@ -314,7 +302,7 @@ class AnsibleHcloudVolume(Hcloud):
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_one_of=[["id", "name"]],
mutually_exclusive=[["location", "server"]],
supports_check_mode=True,
)
@ -326,9 +314,7 @@ def main():
hcloud = AnsibleHcloudVolume(module)
state = module.params.get("state")
if state == "absent":
module.fail_on_missing_params(
required_params=["name"]
)
module.fail_on_missing_params(required_params=["name"])
hcloud.delete_volume()
else:
hcloud.present_volume()

View file

@ -1,14 +1,10 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_volume_info
@ -36,7 +32,7 @@ options:
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""
EXAMPLES = """
- name: Gather hcloud Volume infos
@ -95,8 +91,8 @@ hcloud_volume_info:
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.hetzner.hcloud.plugins.module_utils.hcloud import Hcloud
@ -113,32 +109,31 @@ class AnsibleHcloudVolumeInfo(Hcloud):
server_name = None
if volume.server is not None:
server_name = to_native(volume.server.name)
tmp.append({
"id": to_native(volume.id),
"name": to_native(volume.name),
"size": volume.size,
"location": to_native(volume.location.name),
"labels": volume.labels,
"server": server_name,
"linux_device": to_native(volume.linux_device),
"delete_protection": volume.protection["delete"],
})
tmp.append(
{
"id": to_native(volume.id),
"name": to_native(volume.name),
"size": volume.size,
"location": to_native(volume.location.name),
"labels": volume.labels,
"server": server_name,
"linux_device": to_native(volume.linux_device),
"delete_protection": volume.protection["delete"],
}
)
return tmp
def get_volumes(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_volume_info = [self.client.volumes.get_by_id(
self.module.params.get("id")
)]
self.hcloud_volume_info = [self.client.volumes.get_by_id(self.module.params.get("id"))]
elif self.module.params.get("name") is not None:
self.hcloud_volume_info = [self.client.volumes.get_by_name(
self.module.params.get("name")
)]
self.hcloud_volume_info = [self.client.volumes.get_by_name(self.module.params.get("name"))]
elif self.module.params.get("label_selector") is not None:
self.hcloud_volume_info = self.client.volumes.get_all(
label_selector=self.module.params.get("label_selector"))
label_selector=self.module.params.get("label_selector")
)
else:
self.hcloud_volume_info = self.client.volumes.get_all()
@ -161,24 +156,24 @@ class AnsibleHcloudVolumeInfo(Hcloud):
def main():
module = AnsibleHcloudVolumeInfo.define_module()
is_old_facts = module._name == 'hcloud_volume_facts'
is_old_facts = module._name == "hcloud_volume_facts"
if is_old_facts:
module.deprecate("The 'hcloud_volume_facts' module has been renamed to 'hcloud_volume_info', "
"and the renamed one no longer returns ansible_facts", version='2.0.0', collection_name="hetzner.hcloud")
module.deprecate(
"The 'hcloud_volume_facts' module has been renamed to 'hcloud_volume_info', "
"and the renamed one no longer returns ansible_facts",
version="2.0.0",
collection_name="hetzner.hcloud",
)
hcloud = AnsibleHcloudVolumeInfo(module)
hcloud.get_volumes()
result = hcloud.get_result()
if is_old_facts:
ansible_info = {
'hcloud_volume_facts': result['hcloud_volume_info']
}
ansible_info = {"hcloud_volume_facts": result["hcloud_volume_info"]}
module.exit_json(ansible_facts=ansible_info)
else:
ansible_info = {
'hcloud_volume_info': result['hcloud_volume_info']
}
ansible_info = {"hcloud_volume_info": result["hcloud_volume_info"]}
module.exit_json(**ansible_info)

6
pyproject.toml Normal file
View file

@ -0,0 +1,6 @@
[tool.black]
line-length = 120
[tool.isort]
profile = "black"
combine_as_imports = true

View file

@ -4,4 +4,4 @@
hcloud_server_type_name: "cx11"
hcloud_server_type_id: 1
hcloud_server_type_id_deprecated: "2" # cx11-ceph
hcloud_server_type_id_deprecated: "2" # cx11-ceph

View file

@ -1,7 +1,6 @@
#!/usr/bin/env python
"""Verify the currently executing Shippable test matrix matches the one defined in the "shippable.yml" file."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import json
@ -25,41 +24,45 @@ except ImportError:
def main(): # type: () -> None
"""Main entry point."""
repo_full_name = os.environ['REPO_FULL_NAME']
required_repo_full_name = 'ansible-collections/hetzner.hcloud'
repo_full_name = os.environ["REPO_FULL_NAME"]
required_repo_full_name = "ansible-collections/hetzner.hcloud"
if repo_full_name != required_repo_full_name:
sys.stderr.write('Skipping matrix check on repo "%s" which is not "%s".\n' % (repo_full_name, required_repo_full_name))
sys.stderr.write(
f'Skipping matrix check on repo "{repo_full_name}" which is not "{required_repo_full_name}".\n'
)
return
with open('shippable.yml', 'rb') as yaml_file:
yaml = yaml_file.read().decode('utf-8').splitlines()
with open("shippable.yml", "rb") as yaml_file:
yaml = yaml_file.read().decode("utf-8").splitlines()
defined_matrix = [match.group(1) for match in [re.search(r'^ *- env: T=(.*)$', line) for line in yaml] if match and match.group(1) != 'none']
defined_matrix = [
match.group(1)
for match in [re.search(r"^ *- env: T=(.*)$", line) for line in yaml]
if match and match.group(1) != "none"
]
if not defined_matrix:
fail('No matrix entries found in the "shippable.yml" file.',
'Did you modify the "shippable.yml" file?')
fail('No matrix entries found in the "shippable.yml" file.', 'Did you modify the "shippable.yml" file?')
run_id = os.environ['SHIPPABLE_BUILD_ID']
run_id = os.environ["SHIPPABLE_BUILD_ID"]
sleep = 1
jobs = []
for attempts_remaining in range(4, -1, -1):
try:
jobs = json.loads(urlopen('https://api.shippable.com/jobs?runIds=%s' % run_id).read())
jobs = json.loads(urlopen("https://api.shippable.com/jobs?runIds=%s" % run_id).read())
if not isinstance(jobs, list):
raise Exception('Shippable run %s data is not a list.' % run_id)
raise Exception("Shippable run %s data is not a list." % run_id)
break
except Exception as ex:
if not attempts_remaining:
fail('Unable to retrieve Shippable run %s matrix.' % run_id,
str(ex))
fail("Unable to retrieve Shippable run %s matrix." % run_id, str(ex))
sys.stderr.write('Unable to retrieve Shippable run %s matrix: %s\n' % (run_id, ex))
sys.stderr.write('Trying again in %d seconds...\n' % sleep)
sys.stderr.write(f"Unable to retrieve Shippable run {run_id} matrix: {ex}\n")
sys.stderr.write("Trying again in %d seconds...\n" % sleep)
time.sleep(sleep)
sleep *= 2
@ -67,54 +70,68 @@ def main(): # type: () -> None
if len(jobs) == 1:
hint = '\n\nMake sure you do not use the "Rebuild with SSH" option.'
else:
hint = ''
hint = ""
fail('Shippable run %s has %d jobs instead of the expected %d jobs.' % (run_id, len(jobs), len(defined_matrix)),
'Try re-running the entire matrix.%s' % hint)
fail(
"Shippable run %s has %d jobs instead of the expected %d jobs." % (run_id, len(jobs), len(defined_matrix)),
"Try re-running the entire matrix.%s" % hint,
)
actual_matrix = dict((job.get('jobNumber'), dict(tuple(line.split('=', 1)) for line in job.get('env', [])).get('T', '')) for job in jobs)
errors = [(job_number, test, actual_matrix.get(job_number)) for job_number, test in enumerate(defined_matrix, 1) if actual_matrix.get(job_number) != test]
actual_matrix = {
job.get("jobNumber"): dict(tuple(line.split("=", 1)) for line in job.get("env", [])).get("T", "")
for job in jobs
}
errors = [
(job_number, test, actual_matrix.get(job_number))
for job_number, test in enumerate(defined_matrix, 1)
if actual_matrix.get(job_number) != test
]
if len(errors):
error_summary = '\n'.join('Job %s expected "%s" but found "%s" instead.' % (job_number, expected, actual) for job_number, expected, actual in errors)
error_summary = "\n".join(
f'Job {job_number} expected "{expected}" but found "{actual}" instead.'
for job_number, expected, actual in errors
)
fail('Shippable run %s has a job matrix mismatch.' % run_id,
'Try re-running the entire matrix.\n\n%s' % error_summary)
fail(
"Shippable run %s has a job matrix mismatch." % run_id,
"Try re-running the entire matrix.\n\n%s" % error_summary,
)
def fail(message, output): # type: (str, str) -> NoReturn
# Include a leading newline to improve readability on Shippable "Tests" tab.
# Without this, the first line becomes indented.
output = '\n' + output.strip()
output = "\n" + output.strip()
timestamp = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
# hack to avoid requiring junit-xml, which isn't pre-installed on Shippable outside our test containers
xml = '''
xml = f"""
<?xml version="1.0" encoding="utf-8"?>
<testsuites disabled="0" errors="1" failures="0" tests="1" time="0.0">
\t<testsuite disabled="0" errors="1" failures="0" file="None" log="None" name="ansible-test" skipped="0" tests="1" time="0" timestamp="%s" url="None">
\t<testsuite disabled="0" errors="1" failures="0" file="None" log="None" name="ansible-test" skipped="0" tests="1" time="0" timestamp="{timestamp}" url="None">
\t\t<testcase classname="timeout" name="timeout">
\t\t\t<error message="%s" type="error">%s</error>
\t\t\t<error message="{message}" type="error">{output}</error>
\t\t</testcase>
\t</testsuite>
</testsuites>
''' % (timestamp, message, output)
"""
path = 'shippable/testresults/check-matrix.xml'
path = "shippable/testresults/check-matrix.xml"
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
with open(path, 'w') as junit_fd:
with open(path, "w") as junit_fd:
junit_fd.write(xml.lstrip())
sys.stderr.write(message + '\n')
sys.stderr.write(output + '\n')
sys.stderr.write(message + "\n")
sys.stderr.write(output + "\n")
sys.exit(1)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -1,16 +1,15 @@
#!/usr/bin/env python3.7
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
start = time.time()
sys.stdin.reconfigure(errors='surrogateescape')
sys.stdout.reconfigure(errors='surrogateescape')
sys.stdin.reconfigure(errors="surrogateescape")
sys.stdout.reconfigure(errors="surrogateescape")
for line in sys.stdin:
seconds = time.time() - start
sys.stdout.write('%02d:%02d %s' % (seconds // 60, seconds % 60, line))
sys.stdout.write("%02d:%02d %s" % (seconds // 60, seconds % 60, line))
sys.stdout.flush()