| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, Nurfet Becirevic <[email protected]> |
| 4 |
# Copyright (c) 2017, Tomas Karasek <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: packet_ip_subnet |
| 12 |
|
| 13 |
short_description: Assign IP subnet to a bare metal server |
| 14 |
|
| 15 |
description: |
| 16 |
- Assign or unassign IPv4 or IPv6 subnets to or from a device in the Packet host. |
| 17 |
- IPv4 subnets must come from already reserved block. |
| 18 |
- IPv6 subnets must come from publicly routable /56 block from your project. |
| 19 |
- See U(https://support.packet.com/kb/articles/elastic-ips) for more info on IP block reservation. |
| 20 |
version_added: '0.2.0' |
| 21 |
|
| 22 |
author: |
| 23 |
- Tomas Karasek (@t0mk) <[email protected]> |
| 24 |
- Nurfet Becirevic (@nurfet-becirevic) <[email protected]> |
| 25 |
|
| 26 |
extends_documentation_fragment: |
| 27 |
- community.general._attributes |
| 28 |
|
| 29 |
attributes: |
| 30 |
check_mode: |
| 31 |
support: full |
| 32 |
diff_mode: |
| 33 |
support: none |
| 34 |
|
| 35 |
options: |
| 36 |
auth_token: |
| 37 |
description: |
| 38 |
- Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN). |
| 39 |
type: str |
| 40 |
|
| 41 |
hostname: |
| 42 |
description: |
| 43 |
- A hostname of a device to/from which to assign/remove a subnet. |
| 44 |
type: str |
| 45 |
|
| 46 |
device_id: |
| 47 |
description: |
| 48 |
- UUID of a device to/from which to assign/remove a subnet. |
| 49 |
type: str |
| 50 |
|
| 51 |
project_id: |
| 52 |
description: |
| 53 |
- UUID of a project of the device to/from which to assign/remove a subnet. |
| 54 |
type: str |
| 55 |
|
| 56 |
device_count: |
| 57 |
description: |
| 58 |
- The number of devices to retrieve from the project. The max allowed value is 1000. |
| 59 |
- See U(https://www.packet.com/developers/api/#retrieve-all-devices-of-a-project) for more info. |
| 60 |
default: 100 |
| 61 |
type: int |
| 62 |
|
| 63 |
cidr: |
| 64 |
description: |
| 65 |
- IPv4 or IPv6 subnet which you want to manage. It must come from a reserved block for your project in the Packet Host. |
| 66 |
aliases: [name] |
| 67 |
type: str |
| 68 |
required: true |
| 69 |
|
| 70 |
state: |
| 71 |
description: |
| 72 |
- Desired state of the IP subnet on the specified device. |
| 73 |
- With O(state=present), you must specify either O(hostname) or O(device_id). Subnet with given CIDR is then assigned |
| 74 |
to the specified device. |
| 75 |
- With O(state=absent), you can specify either O(hostname) or O(device_id). The subnet is then removed from specified |
| 76 |
devices. |
| 77 |
- If you leave both O(hostname) and O(device_id) empty, the subnet is then removed from any device it is assigned to. |
| 78 |
choices: ['present', 'absent'] |
| 79 |
default: 'present' |
| 80 |
type: str |
| 81 |
|
| 82 |
requirements: |
| 83 |
- "packet-python >= 1.35" |
| 84 |
""" |
| 85 |
|
| 86 |
EXAMPLES = r""" |
| 87 |
# All the examples assume that you have your Packet API token in env var PACKET_API_TOKEN. |
| 88 |
# You can also pass it to the auth_token parameter of the module instead. |
| 89 |
|
| 90 |
- name: Create 1 device and assign an arbitrary public IPv4 subnet to it |
| 91 |
hosts: localhost |
| 92 |
tasks: |
| 93 |
|
| 94 |
- packet_device: |
| 95 |
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df |
| 96 |
hostnames: myserver |
| 97 |
operating_system: ubuntu_16_04 |
| 98 |
plan: baremetal_0 |
| 99 |
facility: sjc1 |
| 100 |
state: active |
| 101 |
|
| 102 |
# Pick an IPv4 address from a block allocated to your project. |
| 103 |
|
| 104 |
- community.general.packet_ip_subnet: |
| 105 |
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df |
| 106 |
hostname: myserver |
| 107 |
cidr: "147.75.201.78/32" |
| 108 |
|
| 109 |
# Release IP address 147.75.201.78 |
| 110 |
|
| 111 |
- name: Unassign IP address from any device in your project |
| 112 |
hosts: localhost |
| 113 |
tasks: |
| 114 |
- community.general.packet_ip_subnet: |
| 115 |
project_id: 89b497ee-5afc-420a-8fb5-56984898f4df |
| 116 |
cidr: "147.75.201.78/32" |
| 117 |
state: absent |
| 118 |
""" |
| 119 |
|
| 120 |
RETURN = r""" |
| 121 |
device_id: |
| 122 |
type: str |
| 123 |
description: UUID of the device associated with the specified IP address. |
| 124 |
returned: success |
| 125 |
|
| 126 |
subnet: |
| 127 |
description: Dict with data about the handled IP subnet. |
| 128 |
type: dict |
| 129 |
sample: |
| 130 |
address: 147.75.90.241 |
| 131 |
address_family: 4 |
| 132 |
assigned_to: {href: /devices/61f9aa5e-0530-47f5-97c2-113828e61ed0} |
| 133 |
cidr: 31 |
| 134 |
created_at: '2017-08-07T15:15:30Z' |
| 135 |
enabled: true |
| 136 |
gateway: 147.75.90.240 |
| 137 |
href: /ips/31eda960-0a16-4c0f-b196-f3dc4928529f |
| 138 |
id: 1eda960-0a16-4c0f-b196-f3dc4928529f |
| 139 |
manageable: true |
| 140 |
management: true |
| 141 |
netmask: 255.255.255.254 |
| 142 |
network: 147.75.90.240 |
| 143 |
public: true |
| 144 |
returned: success |
| 145 |
""" |
| 146 |
|
| 147 |
|
| 148 |
import re |
| 149 |
import uuid |
| 150 |
|
| 151 |
from ansible.module_utils.basic import AnsibleModule, env_fallback |
| 152 |
|
| 153 |
HAS_PACKET_SDK = True |
| 154 |
|
| 155 |
try: |
| 156 |
import packet |
| 157 |
except ImportError: |
| 158 |
HAS_PACKET_SDK = False |
| 159 |
|
| 160 |
|
| 161 |
NAME_RE = r"([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])" |
| 162 |
HOSTNAME_RE = rf"({NAME_RE}\.)*{NAME_RE}$" |
| 163 |
PROJECT_MAX_DEVICES = 100 |
| 164 |
|
| 165 |
|
| 166 |
PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN" |
| 167 |
|
| 168 |
|
| 169 |
ALLOWED_STATES = ["absent", "present"] |
| 170 |
|
| 171 |
|
| 172 |
def is_valid_hostname(hostname): |
| 173 |
return re.match(HOSTNAME_RE, hostname) is not None |
| 174 |
|
| 175 |
|
| 176 |
def is_valid_uuid(myuuid): |
| 177 |
try: |
| 178 |
val = uuid.UUID(myuuid, version=4) |
| 179 |
except ValueError: |
| 180 |
return False |
| 181 |
return str(val) == myuuid |
| 182 |
|
| 183 |
|
| 184 |
def get_existing_devices(module, packet_conn): |
| 185 |
project_id = module.params.get("project_id") |
| 186 |
if not is_valid_uuid(project_id): |
| 187 |
raise Exception(f"Project ID {project_id} does not seem to be valid") |
| 188 |
|
| 189 |
per_page = module.params.get("device_count") |
| 190 |
return packet_conn.list_devices(project_id, params={"per_page": per_page}) |
| 191 |
|
| 192 |
|
| 193 |
def get_specified_device_identifiers(module): |
| 194 |
if module.params.get("device_id"): |
| 195 |
_d_id = module.params.get("device_id") |
| 196 |
if not is_valid_uuid(_d_id): |
| 197 |
raise Exception(f"Device ID '{_d_id}' does not seem to be valid") |
| 198 |
return {"device_id": _d_id, "hostname": None} |
| 199 |
elif module.params.get("hostname"): |
| 200 |
_hn = module.params.get("hostname") |
| 201 |
if not is_valid_hostname(_hn): |
| 202 |
raise Exception(f"Hostname '{_hn}' does not seem to be valid") |
| 203 |
return {"hostname": _hn, "device_id": None} |
| 204 |
else: |
| 205 |
return {"hostname": None, "device_id": None} |
| 206 |
|
| 207 |
|
| 208 |
def parse_subnet_cidr(cidr): |
| 209 |
if "/" not in cidr: |
| 210 |
raise Exception("CIDR expression in wrong format, must be address/prefix_len") |
| 211 |
addr, prefixlen = cidr.split("/") |
| 212 |
try: |
| 213 |
prefixlen = int(prefixlen) |
| 214 |
except ValueError as e: |
| 215 |
raise Exception(f"Wrong prefix length in CIDR expression {cidr}") from e |
| 216 |
return addr, prefixlen |
| 217 |
|
| 218 |
|
| 219 |
def act_on_assignment(target_state, module, packet_conn): |
| 220 |
return_dict = {"changed": False} |
| 221 |
specified_cidr = module.params.get("cidr") |
| 222 |
address, prefixlen = parse_subnet_cidr(specified_cidr) |
| 223 |
|
| 224 |
specified_identifier = get_specified_device_identifiers(module) |
| 225 |
|
| 226 |
if module.check_mode: |
| 227 |
return return_dict |
| 228 |
|
| 229 |
if (specified_identifier["hostname"] is None) and (specified_identifier["device_id"] is None): |
| 230 |
if target_state == "absent": |
| 231 |
# The special case to release the IP from any assignment |
| 232 |
for d in get_existing_devices(module, packet_conn): |
| 233 |
for ia in d.ip_addresses: |
| 234 |
if address == ia["address"] and prefixlen == ia["cidr"]: |
| 235 |
packet_conn.call_api(ia["href"], "DELETE") |
| 236 |
return_dict["changed"] = True |
| 237 |
return_dict["subnet"] = ia |
| 238 |
return_dict["device_id"] = d.id |
| 239 |
return return_dict |
| 240 |
raise Exception("If you assign an address, you must specify either target device ID or target unique hostname.") |
| 241 |
|
| 242 |
if specified_identifier["device_id"] is not None: |
| 243 |
device = packet_conn.get_device(specified_identifier["device_id"]) |
| 244 |
else: |
| 245 |
all_devices = get_existing_devices(module, packet_conn) |
| 246 |
hn = specified_identifier["hostname"] |
| 247 |
matching_devices = [d for d in all_devices if d.hostname == hn] |
| 248 |
if len(matching_devices) > 1: |
| 249 |
raise Exception(f"There are more than one devices matching given hostname {hn}") |
| 250 |
if len(matching_devices) == 0: |
| 251 |
raise Exception(f"There is no device matching given hostname {hn}") |
| 252 |
device = matching_devices[0] |
| 253 |
|
| 254 |
return_dict["device_id"] = device.id |
| 255 |
assignment_dicts = [i for i in device.ip_addresses if i["address"] == address and i["cidr"] == prefixlen] |
| 256 |
if len(assignment_dicts) > 1: |
| 257 |
raise Exception(f"IP address {specified_cidr} is assigned more than once for device {device.hostname}") |
| 258 |
|
| 259 |
if target_state == "absent": |
| 260 |
if len(assignment_dicts) == 1: |
| 261 |
packet_conn.call_api(assignment_dicts[0]["href"], "DELETE") |
| 262 |
return_dict["subnet"] = assignment_dicts[0] |
| 263 |
return_dict["changed"] = True |
| 264 |
elif target_state == "present": |
| 265 |
if len(assignment_dicts) == 0: |
| 266 |
new_assignment = packet_conn.call_api(f"devices/{device.id}/ips", "POST", {"address": f"{specified_cidr}"}) |
| 267 |
return_dict["changed"] = True |
| 268 |
return_dict["subnet"] = new_assignment |
| 269 |
return return_dict |
| 270 |
|
| 271 |
|
| 272 |
def main(): |
| 273 |
module = AnsibleModule( |
| 274 |
argument_spec=dict( |
| 275 |
auth_token=dict(type="str", fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]), no_log=True), |
| 276 |
device_id=dict(type="str"), |
| 277 |
hostname=dict(type="str"), |
| 278 |
project_id=dict(type="str"), |
| 279 |
device_count=dict(type="int", default=PROJECT_MAX_DEVICES), |
| 280 |
cidr=dict(type="str", required=True, aliases=["name"]), |
| 281 |
state=dict(choices=ALLOWED_STATES, default="present"), |
| 282 |
), |
| 283 |
supports_check_mode=True, |
| 284 |
mutually_exclusive=[("hostname", "device_id")], |
| 285 |
required_one_of=[["hostname", "device_id", "project_id"]], |
| 286 |
required_by=dict( |
| 287 |
hostname=("project_id",), |
| 288 |
), |
| 289 |
) |
| 290 |
|
| 291 |
if not HAS_PACKET_SDK: |
| 292 |
module.fail_json(msg="packet required for this module") |
| 293 |
|
| 294 |
if not module.params.get("auth_token"): |
| 295 |
_fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required" |
| 296 |
module.fail_json(msg=_fail_msg) |
| 297 |
|
| 298 |
auth_token = module.params.get("auth_token") |
| 299 |
|
| 300 |
packet_conn = packet.Manager(auth_token=auth_token) |
| 301 |
|
| 302 |
state = module.params.get("state") |
| 303 |
|
| 304 |
try: |
| 305 |
module.exit_json(**act_on_assignment(state, module, packet_conn)) |
| 306 |
except Exception as e: |
| 307 |
module.fail_json(msg=f"failed to set IP subnet to state {state}, error: {e}") |
| 308 |
|
| 309 |
|
| 310 |
if __name__ == "__main__": |
| 311 |
main() |