ansible-collection-hetzner-.../plugins/modules/primary_ip.py
renovate[bot] 9adb8b3981
chore(deps): update dependency hcloud to v2 (#523)
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [hcloud](https://togithub.com/hetznercloud/hcloud-python)
([changelog](https://togithub.com/hetznercloud/hcloud-python/blob/main/CHANGELOG.md))
| `1.35.0` -> `2.0.1` |
[![age](https://developer.mend.io/api/mc/badges/age/pypi/hcloud/2.0.1?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/pypi/hcloud/2.0.1?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/pypi/hcloud/1.35.0/2.0.1?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/hcloud/1.35.0/2.0.1?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>hetznercloud/hcloud-python (hcloud)</summary>

###
[`v2.0.1`](https://togithub.com/hetznercloud/hcloud-python/blob/HEAD/CHANGELOG.md#201-2024-07-03)

[Compare
Source](https://togithub.com/hetznercloud/hcloud-python/compare/v2.0.0...v2.0.1)

##### Bug Fixes

- `assignee_type` is required when creating a primary ip
([#&#8203;409](https://togithub.com/hetznercloud/hcloud-python/issues/409))
([bce5e94](bce5e940e2))
- clean unused arguments in the `Client.servers.rebuild` method
([#&#8203;407](https://togithub.com/hetznercloud/hcloud-python/issues/407))
([6d33c3c](6d33c3cff5))
- details are optional in API errors
([#&#8203;411](https://togithub.com/hetznercloud/hcloud-python/issues/411))
([f1c6594](f1c6594dee))
- rename `trace_id` variable to `correlation_id`
([#&#8203;408](https://togithub.com/hetznercloud/hcloud-python/issues/408))
([66a0f54](66a0f54699))

###
[`v2.0.0`](https://togithub.com/hetznercloud/hcloud-python/blob/HEAD/CHANGELOG.md#200-2024-07-03)

[Compare
Source](https://togithub.com/hetznercloud/hcloud-python/compare/v1.35.0...v2.0.0)

##### ⚠ BREAKING CHANGES

- return full rebuild response in `Client.servers.rebuild`
([#&#8203;406](https://togithub.com/hetznercloud/hcloud-python/issues/406))
- make `datacenter` argument optional when creating a primary ip
([#&#8203;363](https://togithub.com/hetznercloud/hcloud-python/issues/363))
- remove deprecated `include_wildcard_architecture` argument in
`IsosClient.get_list` and `IsosClient.get_all`
([#&#8203;402](https://togithub.com/hetznercloud/hcloud-python/issues/402))
- make `Client.request` `tries` a private argument
([#&#8203;399](https://togithub.com/hetznercloud/hcloud-python/issues/399))
- make `Client.poll_interval` a private property
([#&#8203;398](https://togithub.com/hetznercloud/hcloud-python/issues/398))
- return empty dict on empty responses in `Client.request`
([#&#8203;400](https://togithub.com/hetznercloud/hcloud-python/issues/400))
- remove deprecated `hcloud.hcloud` module
([#&#8203;401](https://togithub.com/hetznercloud/hcloud-python/issues/401))
- move `hcloud.__version__.VERSION` to `hcloud.__version__`
([#&#8203;397](https://togithub.com/hetznercloud/hcloud-python/issues/397))

##### Features

- add `trace_id` to API exceptions
([#&#8203;404](https://togithub.com/hetznercloud/hcloud-python/issues/404))
([8375261](8375261da3))
- allow using a custom poll_interval function
([#&#8203;403](https://togithub.com/hetznercloud/hcloud-python/issues/403))
([93eb56b](93eb56ba4d))
- make `Client.poll_interval` a private property
([#&#8203;398](https://togithub.com/hetznercloud/hcloud-python/issues/398))
([d5f24db](d5f24db281))
- make `Client.request` `tries` a private argument
([#&#8203;399](https://togithub.com/hetznercloud/hcloud-python/issues/399))
([428ea7e](428ea7e3be))
- move `hcloud.__version__.VERSION` to `hcloud.__version__`
([#&#8203;397](https://togithub.com/hetznercloud/hcloud-python/issues/397))
([4e3f638](4e3f638862)),
closes
[#&#8203;234](https://togithub.com/hetznercloud/hcloud-python/issues/234)
- remove deprecated `hcloud.hcloud` module
([#&#8203;401](https://togithub.com/hetznercloud/hcloud-python/issues/401))
([db37e63](db37e633eb))
- remove deprecated `include_wildcard_architecture` argument in
`IsosClient.get_list` and `IsosClient.get_all`
([#&#8203;402](https://togithub.com/hetznercloud/hcloud-python/issues/402))
([6b977e2](6b977e2da5))
- return empty dict on empty responses in `Client.request`
([#&#8203;400](https://togithub.com/hetznercloud/hcloud-python/issues/400))
([9f46adb](9f46adb946))
- return full rebuild response in `Client.servers.rebuild`
([#&#8203;406](https://togithub.com/hetznercloud/hcloud-python/issues/406))
([1970d84](1970d84bec))

##### Bug Fixes

- make `datacenter` argument optional when creating a primary ip
([#&#8203;363](https://togithub.com/hetznercloud/hcloud-python/issues/363))
([ebef774](ebef77464c))

##### Dependencies

- update dependency coverage to >=7.5,<7.6
([#&#8203;386](https://togithub.com/hetznercloud/hcloud-python/issues/386))
([5660691](5660691ebd))
- update dependency mypy to >=1.10,<1.11
([#&#8203;387](https://togithub.com/hetznercloud/hcloud-python/issues/387))
([35c933b](35c933bd21))
- update dependency myst-parser to v3
([#&#8203;385](https://togithub.com/hetznercloud/hcloud-python/issues/385))
([9f18270](9f18270489))
- update dependency pylint to >=3,<3.3
([#&#8203;391](https://togithub.com/hetznercloud/hcloud-python/issues/391))
([4a6f005](4a6f005cb0))
- update dependency pytest to >=8,<8.3
([#&#8203;390](https://togithub.com/hetznercloud/hcloud-python/issues/390))
([584a36b](584a36b658))
- update dependency sphinx to >=7.3.4,<7.4
([#&#8203;383](https://togithub.com/hetznercloud/hcloud-python/issues/383))
([69c2e16](69c2e16073))
- update pre-commit hook asottile/pyupgrade to v3.16.0
([0ce5fbc](0ce5fbccba))
- update pre-commit hook pre-commit/pre-commit-hooks to v4.6.0
([5ef25ab](5ef25ab396))
- update pre-commit hook psf/black-pre-commit-mirror to v24.4.0
([0941fbf](0941fbfab2))
- update pre-commit hook psf/black-pre-commit-mirror to v24.4.1
([fec08c5](fec08c5323))
- update pre-commit hook psf/black-pre-commit-mirror to v24.4.2
([#&#8203;389](https://togithub.com/hetznercloud/hcloud-python/issues/389))
([2b2e21f](2b2e21f613))
- update pre-commit hook pycqa/flake8 to v7.1.0
([3bc651d](3bc651d50d))

##### Documentation

- add v2 upgrade notes
([#&#8203;405](https://togithub.com/hetznercloud/hcloud-python/issues/405))
([c77f771](c77f771e2b))
- cx11 is name, not an id
([#&#8203;381](https://togithub.com/hetznercloud/hcloud-python/issues/381))
([b745d40](b745d4049f))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/ansible-collections/hetzner.hcloud).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy40MjEuOSIsInVwZGF0ZWRJblZlciI6IjM3LjQyMS45IiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: jo <ljonas@riseup.net>
2024-07-03 15:05:12 +02:00

324 lines
11 KiB
Python

#!/usr/bin/python
# 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 annotations
DOCUMENTATION = """
---
module: primary_ip
short_description: Create and manage cloud Primary IPs on the Hetzner Cloud.
description:
- Create, update and manage cloud Primary IPs on the Hetzner Cloud.
author:
- Lukas Kaemmerling (@lkaemmerling)
version_added: 1.8.0
options:
id:
description:
- The ID of the Hetzner Cloud Primary IPs to manage.
- Only required if no Primary IP I(name) is given.
type: int
name:
description:
- The Name of the Hetzner Cloud Primary IPs to manage.
- Only required if no Primary IP I(id) is given or a Primary IP does not exist.
type: str
datacenter:
description:
- Home Location of the Hetzner Cloud Primary IP.
- Required if no I(server) is given and Primary IP does not exist.
type: str
server:
description:
- Name or ID of the Hetzner Cloud Server the Primary IP should be assigned to.
- The Primary IP cannot be assigned to a running server.
- Required if no O(datacenter) is given and the Primary IP does not exist.
type: str
type:
description:
- Type of the Primary IP.
- Required if Primary IP does not exist
choices: [ ipv4, ipv6 ]
type: str
auto_delete:
description:
- Delete the Primary IP when the resource it is assigned to is deleted.
type: bool
default: false
delete_protection:
description:
- Protect the Primary IP for deletion.
type: bool
labels:
description:
- User-defined labels (key-value pairs).
type: dict
state:
description:
- State of the Primary IP.
default: present
choices: [ absent, present ]
type: str
extends_documentation_fragment:
- hetzner.hcloud.hcloud
"""
EXAMPLES = """
- name: Create a IPv4 Primary IP
hetzner.hcloud.primary_ip:
name: my-primary-ip
datacenter: fsn1-dc14
type: ipv4
state: present
- name: Create a IPv6 Primary IP
hetzner.hcloud.primary_ip:
name: my-primary-ip
datacenter: fsn1-dc14
type: ipv6
state: present
- name: Delete a Primary IP
hetzner.hcloud.primary_ip:
name: my-primary-ip
state: absent
- name: Ensure the server is stopped
hetzner.hcloud.server:
name: my-server
state: stopped
- name: Create a Primary IP attached to a Server
hetzner.hcloud.primary_ip:
name: my-primary-ip
server: my-server
type: ipv4
state: present
- name: Ensure the server is started
hetzner.hcloud.server:
name: my-server
state: started
"""
RETURN = """
hcloud_primary_ip:
description: The Primary IP instance
returned: Always
type: complex
contains:
id:
description: ID of the Primary IP
type: int
returned: Always
sample: 12345
name:
description: Name of the Primary IP
type: str
returned: Always
sample: my-primary-ip
ip:
description: IP Address of the Primary IP
type: str
returned: Always
sample: 116.203.104.109
type:
description: Type of the Primary IP
type: str
returned: Always
sample: ipv4
datacenter:
description: Name of the datacenter of the Primary IP
type: str
returned: Always
sample: fsn1-dc14
delete_protection:
description: True if Primary IP is protected for deletion
type: bool
returned: always
sample: false
labels:
description: User-defined labels (key-value pairs)
type: dict
returned: Always
sample:
key: value
mylabel: 123
assignee_id:
description: ID of the resource the Primary IP is assigned to, null if it is not assigned.
type: int
returned: always
sample: 1937415
assignee_type:
description: Resource type the Primary IP can be assigned to.
type: str
returned: always
sample: server
auto_delete:
description: Delete the Primary IP when the resource it is assigned to is deleted.
type: bool
returned: always
sample: false
"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.primary_ips import BoundPrimaryIP
class AnsibleHCloudPrimaryIP(AnsibleHCloud):
represent = "hcloud_primary_ip"
hcloud_primary_ip: BoundPrimaryIP | None = None
def _prepare_result(self):
return {
"id": str(self.hcloud_primary_ip.id),
"name": self.hcloud_primary_ip.name,
"ip": self.hcloud_primary_ip.ip,
"type": self.hcloud_primary_ip.type,
"datacenter": self.hcloud_primary_ip.datacenter.name,
"labels": self.hcloud_primary_ip.labels,
"delete_protection": self.hcloud_primary_ip.protection["delete"],
"assignee_id": (
str(self.hcloud_primary_ip.assignee_id) if self.hcloud_primary_ip.assignee_id is not None else None
),
"assignee_type": self.hcloud_primary_ip.assignee_type,
"auto_delete": self.hcloud_primary_ip.auto_delete,
}
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"))
else:
self.hcloud_primary_ip = self.client.primary_ips.get_by_name(self.module.params.get("name"))
except HCloudException as exception:
self.fail_json_hcloud(exception)
def _create_primary_ip(self):
self.fail_on_invalid_params(
required=["type", "name"],
required_one_of=[["server", "datacenter"]],
)
try:
params = {
"type": self.module.params.get("type"),
"name": self.module.params.get("name"),
"auto_delete": self.module.params.get("auto_delete"),
}
if self.module.params.get("datacenter") is not None:
params["datacenter"] = self.client.datacenters.get_by_name(self.module.params.get("datacenter"))
elif self.module.params.get("server") is not None:
params["assignee_id"] = self._client_get_by_name_or_id("servers", self.module.params.get("server")).id
if self.module.params.get("labels") is not None:
params["labels"] = self.module.params.get("labels")
if not self.module.check_mode:
resp = self.client.primary_ips.create(**params)
if resp.action is not None:
resp.action.wait_until_finished()
self.hcloud_primary_ip = resp.primary_ip
delete_protection = self.module.params.get("delete_protection")
if delete_protection is not None:
action = self.hcloud_primary_ip.change_protection(delete=delete_protection)
action.wait_until_finished()
except HCloudException as exception:
self.fail_json_hcloud(exception)
self._mark_as_changed()
self._get_primary_ip()
def _update_primary_ip(self):
try:
changes = {}
auto_delete = self.module.params.get("auto_delete")
if auto_delete is not None and auto_delete != self.hcloud_primary_ip.auto_delete:
changes["auto_delete"] = auto_delete
labels = self.module.params.get("labels")
if labels is not None and labels != self.hcloud_primary_ip.labels:
changes["labels"] = labels
if changes:
if not self.module.check_mode:
self.hcloud_primary_ip.update(**changes)
self._mark_as_changed()
delete_protection = self.module.params.get("delete_protection")
if delete_protection is not None and delete_protection != self.hcloud_primary_ip.protection["delete"]:
if not self.module.check_mode:
action = self.hcloud_primary_ip.change_protection(delete=delete_protection)
action.wait_until_finished()
self._mark_as_changed()
self._get_primary_ip()
except HCloudException as exception:
self.fail_json_hcloud(exception)
def present_primary_ip(self):
self._get_primary_ip()
if self.hcloud_primary_ip is None:
self._create_primary_ip()
else:
self._update_primary_ip()
def delete_primary_ip(self):
try:
self._get_primary_ip()
if self.hcloud_primary_ip is not None:
if not self.module.check_mode:
self.client.primary_ips.delete(self.hcloud_primary_ip)
self._mark_as_changed()
self.hcloud_primary_ip = None
except HCloudException as exception:
self.fail_json_hcloud(exception)
@classmethod
def define_module(cls):
return AnsibleModule(
argument_spec=dict(
id={"type": "int"},
name={"type": "str"},
datacenter={"type": "str"},
server={"type": "str"},
auto_delete={"type": "bool", "default": False},
type={"choices": ["ipv4", "ipv6"]},
labels={"type": "dict"},
delete_protection={"type": "bool"},
state={
"choices": ["absent", "present"],
"default": "present",
},
**super().base_module_arguments(),
),
required_one_of=[["id", "name"]],
supports_check_mode=True,
)
def main():
module = AnsibleHCloudPrimaryIP.define_module()
hcloud = AnsibleHCloudPrimaryIP(module)
state = module.params["state"]
if state == "absent":
hcloud.delete_primary_ip()
elif state == "present":
hcloud.present_primary_ip()
module.exit_json(**hcloud.get_result())
if __name__ == "__main__":
main()