| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: ec2_vol |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Create and attach a volume, return volume ID and device map |
| 12 |
description: |
| 13 |
- Creates an EBS volume and optionally attaches it to an instance. |
| 14 |
- If both O(instance) and O(name) are given and the instance has a device at the device name, then no volume is created and no attachment is made. |
| 15 |
options: |
| 16 |
instance: |
| 17 |
description: |
| 18 |
- Instance ID if you wish to attach the volume. |
| 19 |
- Set to V(None) to detach the volume. |
| 20 |
type: str |
| 21 |
name: |
| 22 |
description: |
| 23 |
- Volume Name tag if you wish to attach an existing volume (requires instance). |
| 24 |
type: str |
| 25 |
id: |
| 26 |
description: |
| 27 |
- Volume ID if you wish to attach an existing volume (requires instance) or remove an existing volume. |
| 28 |
type: str |
| 29 |
volume_size: |
| 30 |
description: |
| 31 |
- Size of volume (in GiB) to create. |
| 32 |
type: int |
| 33 |
volume_type: |
| 34 |
description: |
| 35 |
- Type of EBS volume; V(standard) (magnetic), V(gp2) (SSD), V(gp3) (SSD), V(io1) (Provisioned IOPS), V(io2) (Provisioned IOPS), |
| 36 |
V(st1) (Throughput Optimized HDD), V(sc1) (Cold HDD). |
| 37 |
- V(standard) is the old EBS default and continues to remain the Ansible default for backwards compatibility. |
| 38 |
default: standard |
| 39 |
choices: ['standard', 'gp2', 'io1', 'st1', 'sc1', 'gp3', 'io2'] |
| 40 |
type: str |
| 41 |
iops: |
| 42 |
description: |
| 43 |
- The provisioned IOPs you want to associate with this volume (integer). |
| 44 |
type: int |
| 45 |
encrypted: |
| 46 |
description: |
| 47 |
- Enable encryption at rest for this volume. |
| 48 |
default: false |
| 49 |
type: bool |
| 50 |
kms_key_id: |
| 51 |
description: |
| 52 |
- Specify the ID of the KMS key to use. |
| 53 |
type: str |
| 54 |
device_name: |
| 55 |
description: |
| 56 |
- Device ID to override device mapping. Assumes /dev/sdf for Linux/UNIX and /dev/xvdf for Windows. |
| 57 |
type: str |
| 58 |
delete_on_termination: |
| 59 |
description: |
| 60 |
- When set to C(true), the volume will be deleted upon instance termination. |
| 61 |
type: bool |
| 62 |
default: false |
| 63 |
zone: |
| 64 |
description: |
| 65 |
- Zone in which to create the volume, if unset uses the zone the instance is in (if set). |
| 66 |
aliases: ['availability_zone', 'aws_zone', 'ec2_zone'] |
| 67 |
type: str |
| 68 |
snapshot: |
| 69 |
description: |
| 70 |
- Snapshot ID on which to base the volume. |
| 71 |
type: str |
| 72 |
volume_initialization_rate: |
| 73 |
description: |
| 74 |
- Rate at which to initiliaze the volume from a snapshot. |
| 75 |
type: int |
| 76 |
version_added: 11.2.0 |
| 77 |
state: |
| 78 |
description: |
| 79 |
- Whether to ensure the volume is present or absent. |
| 80 |
- O(state=list) was deprecated in release 1.1.0 and is no longer available |
| 81 |
with release 4.0.0. |
| 82 |
- The V(list) functionality has been moved to a dedicated module M(amazon.aws.ec2_vol_info). |
| 83 |
default: present |
| 84 |
choices: ['absent', 'present'] |
| 85 |
type: str |
| 86 |
modify_volume: |
| 87 |
description: |
| 88 |
- The volume won't be modified unless this key is V(true). |
| 89 |
type: bool |
| 90 |
default: false |
| 91 |
version_added: 1.4.0 |
| 92 |
throughput: |
| 93 |
description: |
| 94 |
- Volume throughput in MB/s. |
| 95 |
- This parameter is only valid for gp3 volumes. |
| 96 |
- Valid range is from 125 to 2000. |
| 97 |
type: int |
| 98 |
version_added: 1.4.0 |
| 99 |
multi_attach: |
| 100 |
description: |
| 101 |
- If set to V(true), Multi-Attach will be enabled when creating the volume. |
| 102 |
- When you create a new volume, Multi-Attach is disabled by default. |
| 103 |
- This parameter is supported with io1 and io2 volumes only. |
| 104 |
type: bool |
| 105 |
version_added: 2.0.0 |
| 106 |
outpost_arn: |
| 107 |
description: |
| 108 |
- The Amazon Resource Name (ARN) of the Outpost. |
| 109 |
- If set, allows to create volume in an Outpost. |
| 110 |
type: str |
| 111 |
version_added: 3.1.0 |
| 112 |
author: |
| 113 |
- "Lester Wade (@lwade)" |
| 114 |
notes: |
| 115 |
- Support for O(purge_tags) was added in release 1.5.0. |
| 116 |
extends_documentation_fragment: |
| 117 |
- amazon.aws.common.modules |
| 118 |
- amazon.aws.region.modules |
| 119 |
- amazon.aws.tags |
| 120 |
- amazon.aws.boto3 |
| 121 |
""" |
| 122 |
|
| 123 |
EXAMPLES = r""" |
| 124 |
# Simple attachment action |
| 125 |
- amazon.aws.ec2_vol: |
| 126 |
instance: XXXXXX |
| 127 |
volume_size: 5 |
| 128 |
device_name: sdd |
| 129 |
region: us-west-2 |
| 130 |
|
| 131 |
# Example using custom iops params |
| 132 |
- amazon.aws.ec2_vol: |
| 133 |
instance: XXXXXX |
| 134 |
volume_size: 5 |
| 135 |
iops: 100 |
| 136 |
device_name: sdd |
| 137 |
region: us-west-2 |
| 138 |
|
| 139 |
# Example using snapshot id |
| 140 |
- amazon.aws.ec2_vol: |
| 141 |
instance: XXXXXX |
| 142 |
snapshot: "{{ snapshot }}" |
| 143 |
|
| 144 |
# Playbook example combined with instance launch |
| 145 |
- amazon.aws.ec2: |
| 146 |
keypair: "{{ keypair }}" |
| 147 |
image: "{{ image }}" |
| 148 |
wait: true |
| 149 |
count: 3 |
| 150 |
register: ec2 |
| 151 |
- amazon.aws.ec2_vol: |
| 152 |
instance: "{{ item.id }}" |
| 153 |
volume_size: 5 |
| 154 |
loop: "{{ ec2.instances }}" |
| 155 |
register: ec2_vol |
| 156 |
|
| 157 |
# Example: Launch an instance and then add a volume if not already attached |
| 158 |
# * Volume will be created with the given name if not already created. |
| 159 |
# * Nothing will happen if the volume is already attached. |
| 160 |
|
| 161 |
- amazon.aws.ec2: |
| 162 |
keypair: "{{ keypair }}" |
| 163 |
image: "{{ image }}" |
| 164 |
zone: YYYYYY |
| 165 |
id: my_instance |
| 166 |
wait: true |
| 167 |
count: 1 |
| 168 |
register: ec2 |
| 169 |
|
| 170 |
- amazon.aws.ec2_vol: |
| 171 |
instance: "{{ item.id }}" |
| 172 |
name: my_existing_volume_Name_tag |
| 173 |
device_name: /dev/xvdf |
| 174 |
loop: "{{ ec2.instances }}" |
| 175 |
register: ec2_vol |
| 176 |
|
| 177 |
# Remove a volume |
| 178 |
- amazon.aws.ec2_vol: |
| 179 |
id: vol-XXXXXXXX |
| 180 |
state: absent |
| 181 |
|
| 182 |
# Detach a volume (since 1.9) |
| 183 |
- amazon.aws.ec2_vol: |
| 184 |
id: vol-XXXXXXXX |
| 185 |
instance: None |
| 186 |
region: us-west-2 |
| 187 |
|
| 188 |
# Create new volume using SSD storage |
| 189 |
- amazon.aws.ec2_vol: |
| 190 |
instance: XXXXXX |
| 191 |
volume_size: 50 |
| 192 |
volume_type: gp2 |
| 193 |
device_name: /dev/xvdf |
| 194 |
|
| 195 |
# Create new volume with multi-attach enabled |
| 196 |
- amazon.aws.ec2_vol: |
| 197 |
zone: XXXXXX |
| 198 |
multi_attach: true |
| 199 |
volume_size: 4 |
| 200 |
volume_type: io1 |
| 201 |
iops: 102 |
| 202 |
|
| 203 |
# Attach an existing volume to instance. The volume will be deleted upon instance termination. |
| 204 |
- amazon.aws.ec2_vol: |
| 205 |
instance: XXXXXX |
| 206 |
id: XXXXXX |
| 207 |
device_name: /dev/sdf |
| 208 |
delete_on_termination: true |
| 209 |
""" |
| 210 |
|
| 211 |
RETURN = r""" |
| 212 |
device: |
| 213 |
description: Device name of attached volume. |
| 214 |
returned: when success |
| 215 |
type: str |
| 216 |
sample: "/dev/sdf" |
| 217 |
volume_id: |
| 218 |
description: The id of volume. |
| 219 |
returned: when success |
| 220 |
type: str |
| 221 |
sample: "vol-35b333d9" |
| 222 |
volume_type: |
| 223 |
description: The volume type. |
| 224 |
returned: when success |
| 225 |
type: str |
| 226 |
sample: "standard" |
| 227 |
volume: |
| 228 |
description: A dictionary containing detailed attributes of the volume. |
| 229 |
returned: when success |
| 230 |
type: dict |
| 231 |
contains: |
| 232 |
attachment_set: |
| 233 |
description: |
| 234 |
- Information about the volume attachments. |
| 235 |
- This was changed in version 2.0.0 from a dictionary to a list of dictionaries. |
| 236 |
type: list |
| 237 |
elements: dict |
| 238 |
returned: when success |
| 239 |
sample: [{ |
| 240 |
"attach_time": "2015-10-23T00:22:29.000Z", |
| 241 |
"deleteOnTermination": "false", |
| 242 |
"device": "/dev/sdf", |
| 243 |
"instance_id": "i-8356263c", |
| 244 |
"status": "attached" |
| 245 |
}] |
| 246 |
create_time: |
| 247 |
description: The time stamp when volume creation was initiated. |
| 248 |
type: str |
| 249 |
returned: when success |
| 250 |
sample: "2015-10-21T14:36:08.870Z" |
| 251 |
encrypted: |
| 252 |
description: Indicates whether the volume is encrypted. |
| 253 |
type: bool |
| 254 |
returned: when success |
| 255 |
sample: False |
| 256 |
id: |
| 257 |
description: The ID of the volume. |
| 258 |
type: str |
| 259 |
returned: when success |
| 260 |
sample: "vol-35b333d9" |
| 261 |
iops: |
| 262 |
description: The number of I/O operations per second (IOPS) that the volume supports. |
| 263 |
type: int |
| 264 |
returned: when success |
| 265 |
sample: null |
| 266 |
size: |
| 267 |
description: The size of the volume, in GiBs. |
| 268 |
type: int |
| 269 |
returned: when success |
| 270 |
sample: 1 |
| 271 |
snapshot_id: |
| 272 |
description: The snapshot from which the volume was created, if applicable. |
| 273 |
type: str |
| 274 |
returned: when success |
| 275 |
sample: "" |
| 276 |
status: |
| 277 |
description: The volume state. |
| 278 |
type: str |
| 279 |
returned: when success |
| 280 |
sample: "in-use" |
| 281 |
tags: |
| 282 |
description: Any tags assigned to the volume. |
| 283 |
type: dict |
| 284 |
returned: when success |
| 285 |
sample: { |
| 286 |
env: "dev" |
| 287 |
} |
| 288 |
type: |
| 289 |
description: The volume type. This can be gp2, io1, st1, sc1, or standard. |
| 290 |
type: str |
| 291 |
returned: when success |
| 292 |
sample: "standard" |
| 293 |
zone: |
| 294 |
description: The Availability Zone of the volume. |
| 295 |
type: str |
| 296 |
returned: when success |
| 297 |
sample: "us-east-1b" |
| 298 |
throughput: |
| 299 |
description: The throughput that the volume supports, in MiB/s. |
| 300 |
type: int |
| 301 |
returned: when success |
| 302 |
sample: 131 |
| 303 |
""" |
| 304 |
|
| 305 |
import time |
| 306 |
from typing import Any |
| 307 |
from typing import Dict |
| 308 |
from typing import List |
| 309 |
from typing import Optional |
| 310 |
from typing import Tuple |
| 311 |
|
| 312 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 313 |
|
| 314 |
from ansible_collections.amazon.aws.plugins.module_utils.arn import is_outpost_arn |
| 315 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error |
| 316 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import attach_volume as attach_ec2_volume |
| 317 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_volume as create_ec2_volume |
| 318 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_volume as delete_ec2_volume |
| 319 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_ec2_tags |
| 320 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instances |
| 321 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_volumes |
| 322 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import detach_volume as detach_ec2_volume |
| 323 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags |
| 324 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_instance_attribute |
| 325 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_volume |
| 326 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 327 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 328 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications |
| 329 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list |
| 330 |
from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state |
| 331 |
|
| 332 |
|
| 333 |
def get_instance(module: AnsibleAWSModule, ec2_conn, instance_id: Optional[str] = None) -> Optional[Dict[str, Any]]: |
| 334 |
instance = None |
| 335 |
if not instance_id: |
| 336 |
return instance |
| 337 |
|
| 338 |
try: |
| 339 |
reservation_response = describe_instances(ec2_conn, InstanceIds=[instance_id]) |
| 340 |
if reservation_response: |
| 341 |
instance = camel_dict_to_snake_dict(reservation_response[0]["Instances"][0]) |
| 342 |
except AnsibleEC2Error as e: |
| 343 |
module.fail_json_aws(e, msg=f"Error while getting instance_id with id {instance_id}") |
| 344 |
|
| 345 |
return instance |
| 346 |
|
| 347 |
|
| 348 |
def get_volume(module, ec2_conn, vol_id=None, fail_on_not_found=True): |
| 349 |
name = module.params.get("name") |
| 350 |
param_id = module.params.get("id") |
| 351 |
zone = module.params.get("zone") |
| 352 |
|
| 353 |
if not vol_id: |
| 354 |
vol_id = param_id |
| 355 |
|
| 356 |
# If no name or id supplied, just try volume creation based on module parameters |
| 357 |
if vol_id is None and name is None: |
| 358 |
return None |
| 359 |
|
| 360 |
find_params = dict() |
| 361 |
vols = [] |
| 362 |
|
| 363 |
if vol_id: |
| 364 |
find_params["VolumeIds"] = [vol_id] |
| 365 |
elif name: |
| 366 |
find_params["Filters"] = ansible_dict_to_boto3_filter_list({"tag:Name": name}) |
| 367 |
elif zone: |
| 368 |
find_params["Filters"] = ansible_dict_to_boto3_filter_list({"availability-zone": zone}) |
| 369 |
|
| 370 |
try: |
| 371 |
vols = describe_volumes(ec2_conn, **find_params) |
| 372 |
if not vols: |
| 373 |
if fail_on_not_found and vol_id: |
| 374 |
msg = f"Could not find volume with id: {vol_id}" |
| 375 |
if name: |
| 376 |
msg += f" and name: {name}" |
| 377 |
module.fail_json(msg=msg) |
| 378 |
else: |
| 379 |
return None |
| 380 |
except AnsibleEC2Error as e: |
| 381 |
module.fail_json_aws(e, msg=f"Error while getting EBS volumes with the parameters {find_params}") |
| 382 |
|
| 383 |
if len(vols) > 1: |
| 384 |
module.fail_json( |
| 385 |
msg=f"Found more than one volume in zone (if specified) with name: {name}", |
| 386 |
found=[v["VolumeId"] for v in vols], |
| 387 |
) |
| 388 |
vol = camel_dict_to_snake_dict(vols[0]) |
| 389 |
return vol |
| 390 |
|
| 391 |
|
| 392 |
def delete_volume(module: AnsibleAWSModule, ec2_conn, volume_id: Optional[str] = None) -> bool: |
| 393 |
changed = False |
| 394 |
if volume_id: |
| 395 |
try: |
| 396 |
changed = delete_ec2_volume(ec2_conn, volume_id) |
| 397 |
except AnsibleEC2Error as e: |
| 398 |
module.fail_json_aws(e, msg="Error while deleting volume") |
| 399 |
wait_for_resource_state(ec2_conn, module, "volume_deleted", VolumeIds=[volume_id]) |
| 400 |
return changed |
| 401 |
|
| 402 |
|
| 403 |
def update_volume(module: AnsibleAWSModule, ec2_conn, volume: Dict[str, Any]) -> Tuple[Dict[str, Any], bool]: |
| 404 |
changed = False |
| 405 |
req_obj = {"VolumeId": volume["volume_id"]} |
| 406 |
|
| 407 |
if module.params.get("modify_volume"): |
| 408 |
target_type = module.params.get("volume_type") |
| 409 |
original_type = None |
| 410 |
type_changed = False |
| 411 |
if target_type: |
| 412 |
original_type = volume["volume_type"] |
| 413 |
if target_type != original_type: |
| 414 |
type_changed = True |
| 415 |
req_obj["VolumeType"] = target_type |
| 416 |
|
| 417 |
iops_changed = False |
| 418 |
target_iops = module.params.get("iops") |
| 419 |
original_iops = volume.get("iops") |
| 420 |
if target_iops: |
| 421 |
if target_iops != original_iops: |
| 422 |
iops_changed = True |
| 423 |
req_obj["Iops"] = target_iops |
| 424 |
else: |
| 425 |
req_obj["Iops"] = original_iops |
| 426 |
else: |
| 427 |
# If no IOPS value is specified and there was a volume_type update to gp3, |
| 428 |
# the existing value is retained, unless a volume type is modified that supports different values, |
| 429 |
# otherwise, the default iops value is applied. |
| 430 |
if type_changed and target_type == "gp3": |
| 431 |
if (original_iops and (int(original_iops) < 3000 or int(original_iops) > 80000)) or not original_iops: |
| 432 |
req_obj["Iops"] = 3000 |
| 433 |
iops_changed = True |
| 434 |
|
| 435 |
target_size = module.params.get("volume_size") |
| 436 |
size_changed = False |
| 437 |
if target_size: |
| 438 |
original_size = volume["size"] |
| 439 |
if target_size != original_size: |
| 440 |
size_changed = True |
| 441 |
req_obj["Size"] = target_size |
| 442 |
|
| 443 |
target_type = module.params.get("volume_type") |
| 444 |
original_type = None |
| 445 |
type_changed = False |
| 446 |
if target_type: |
| 447 |
original_type = volume["volume_type"] |
| 448 |
if target_type != original_type: |
| 449 |
type_changed = True |
| 450 |
req_obj["VolumeType"] = target_type |
| 451 |
|
| 452 |
target_throughput = module.params.get("throughput") |
| 453 |
throughput_changed = False |
| 454 |
if target_throughput: |
| 455 |
original_throughput = volume.get("throughput") |
| 456 |
if target_throughput != original_throughput: |
| 457 |
throughput_changed = True |
| 458 |
req_obj["Throughput"] = target_throughput |
| 459 |
|
| 460 |
target_multi_attach = module.params.get("multi_attach") |
| 461 |
multi_attach_changed = False |
| 462 |
if target_multi_attach is not None: |
| 463 |
original_multi_attach = volume["multi_attach_enabled"] |
| 464 |
if target_multi_attach != original_multi_attach: |
| 465 |
multi_attach_changed = True |
| 466 |
req_obj["MultiAttachEnabled"] = target_multi_attach |
| 467 |
|
| 468 |
changed = iops_changed or size_changed or type_changed or throughput_changed or multi_attach_changed |
| 469 |
|
| 470 |
if changed: |
| 471 |
if module.check_mode: |
| 472 |
module.exit_json(changed=True, msg="Would have updated volume if not in check mode.") |
| 473 |
try: |
| 474 |
response = modify_volume(ec2_conn, **req_obj) |
| 475 |
except AnsibleEC2Error as e: |
| 476 |
module.fail_json_aws(e, msg="Error while modifying volume") |
| 477 |
|
| 478 |
volume["size"] = response.get("TargetSize") |
| 479 |
volume["volume_type"] = response.get("TargetVolumeType") |
| 480 |
volume["iops"] = response.get("TargetIops") |
| 481 |
volume["multi_attach_enabled"] = response.get("TargetMultiAttachEnabled") |
| 482 |
volume["throughput"] = response.get("TargetThroughput") |
| 483 |
|
| 484 |
return volume, changed |
| 485 |
|
| 486 |
|
| 487 |
def create_volume(module: AnsibleAWSModule, ec2_conn, zone: str) -> Tuple[Dict[str, Any], bool]: |
| 488 |
changed = False |
| 489 |
iops = module.params.get("iops") |
| 490 |
encrypted = module.params.get("encrypted") |
| 491 |
kms_key_id = module.params.get("kms_key_id") |
| 492 |
volume_size = module.params.get("volume_size") |
| 493 |
volume_type = module.params.get("volume_type") |
| 494 |
snapshot = module.params.get("snapshot") |
| 495 |
throughput = module.params.get("throughput") |
| 496 |
multi_attach = module.params.get("multi_attach") |
| 497 |
outpost_arn = module.params.get("outpost_arn") |
| 498 |
tags = module.params.get("tags") or {} |
| 499 |
name = module.params.get("name") |
| 500 |
volume_initialization_rate = module.params.get("volume_initialization_rate") |
| 501 |
|
| 502 |
volume = get_volume(module, ec2_conn) |
| 503 |
|
| 504 |
if module.check_mode: |
| 505 |
module.exit_json(changed=True, msg="Would have created a volume if not in check mode.") |
| 506 |
|
| 507 |
if volume is None: |
| 508 |
changed = True |
| 509 |
additional_params = dict() |
| 510 |
|
| 511 |
if volume_size: |
| 512 |
additional_params["Size"] = int(volume_size) |
| 513 |
|
| 514 |
if kms_key_id: |
| 515 |
additional_params["KmsKeyId"] = kms_key_id |
| 516 |
|
| 517 |
if snapshot: |
| 518 |
additional_params["SnapshotId"] = snapshot |
| 519 |
|
| 520 |
if volume_initialization_rate: |
| 521 |
additional_params["VolumeInitializationRate"] = int(volume_initialization_rate) |
| 522 |
|
| 523 |
if iops: |
| 524 |
additional_params["Iops"] = int(iops) |
| 525 |
|
| 526 |
# Use the default value if any iops has been specified when volume_type=gp3 |
| 527 |
if volume_type == "gp3" and not iops: |
| 528 |
additional_params["Iops"] = 3000 |
| 529 |
|
| 530 |
if throughput: |
| 531 |
additional_params["Throughput"] = int(throughput) |
| 532 |
|
| 533 |
if multi_attach: |
| 534 |
additional_params["MultiAttachEnabled"] = True |
| 535 |
|
| 536 |
if outpost_arn: |
| 537 |
if is_outpost_arn(outpost_arn): |
| 538 |
additional_params["OutpostArn"] = outpost_arn |
| 539 |
else: |
| 540 |
module.fail_json("OutpostArn does not match the pattern specified in API specifications.") |
| 541 |
|
| 542 |
if name: |
| 543 |
tags["Name"] = name |
| 544 |
|
| 545 |
if tags: |
| 546 |
additional_params["TagSpecifications"] = boto3_tag_specifications(tags, types=["volume"]) |
| 547 |
|
| 548 |
try: |
| 549 |
create_vol_response = create_ec2_volume( |
| 550 |
ec2_conn, AvailabilityZone=zone, Encrypted=encrypted, VolumeType=volume_type, **additional_params |
| 551 |
) |
| 552 |
except AnsibleEC2Error as e: |
| 553 |
module.fail_json_aws(e, msg="Error while creating EBS volume") |
| 554 |
|
| 555 |
wait_for_resource_state(ec2_conn, module, "volume_available", VolumeIds=[create_vol_response["VolumeId"]]) |
| 556 |
volume = get_volume(module, ec2_conn, vol_id=create_vol_response["VolumeId"]) |
| 557 |
|
| 558 |
return volume, changed |
| 559 |
|
| 560 |
|
| 561 |
def attach_volume( |
| 562 |
module: AnsibleAWSModule, ec2_conn, volume_dict: Dict[str, Any], instance_dict: Dict[str, Any], device_name: str |
| 563 |
) -> Tuple[Dict[str, Any], bool]: |
| 564 |
changed = False |
| 565 |
|
| 566 |
# If device_name isn't set, make a choice based on best practices here: |
| 567 |
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html |
| 568 |
|
| 569 |
# In future this needs to be more dynamic but combining block device mapping best practices |
| 570 |
# (bounds for devices, as above) with instance.block_device_mapping data would be tricky. For me ;) |
| 571 |
|
| 572 |
attachment_data = get_attachment_data(volume_dict, wanted_state="attached") |
| 573 |
if attachment_data: |
| 574 |
if module.check_mode: |
| 575 |
if attachment_data[0].get("status") in ["attached", "attaching"]: |
| 576 |
instance_id = attachment_data[0].get("instance_id", "None") |
| 577 |
module.exit_json( |
| 578 |
changed=False, |
| 579 |
msg=f"IN CHECK MODE - volume already attached to instance: {instance_id}.", |
| 580 |
volume=volume_dict, |
| 581 |
) |
| 582 |
if not volume_dict["multi_attach_enabled"]: |
| 583 |
# volumes without MultiAttach Enabled can be attached to 1 instance only |
| 584 |
if attachment_data[0].get("instance_id", None) != instance_dict["instance_id"]: |
| 585 |
instance_id = attachment_data[0].get("instance_id", "None") |
| 586 |
module.fail_json( |
| 587 |
msg=f"Volume {volume_dict['volume_id']} is already attached to another instance: {instance_id}." |
| 588 |
) |
| 589 |
else: |
| 590 |
return volume_dict, changed |
| 591 |
|
| 592 |
try: |
| 593 |
if module.check_mode: |
| 594 |
module.exit_json(changed=True, msg="Would have attached volume if not in check mode.") |
| 595 |
attach_response = attach_ec2_volume( |
| 596 |
ec2_conn, device=device_name, instance_id=instance_dict["instance_id"], volume_id=volume_dict["volume_id"] |
| 597 |
) |
| 598 |
except AnsibleEC2Error as e: |
| 599 |
module.fail_json_aws(e, msg="Error while attaching EBS volume") |
| 600 |
|
| 601 |
wait_for_resource_state(ec2_conn, module, "volume_in_use", VolumeIds=[attach_response["VolumeId"]]) |
| 602 |
changed = True |
| 603 |
|
| 604 |
modify_dot_attribute(module, ec2_conn, instance_dict, device_name) |
| 605 |
|
| 606 |
volume = get_volume(module, ec2_conn, vol_id=volume_dict["volume_id"]) |
| 607 |
|
| 608 |
return volume, changed |
| 609 |
|
| 610 |
|
| 611 |
def modify_dot_attribute(module: AnsibleAWSModule, ec2_conn, instance_dict: Dict[str, Any], device_name: str) -> bool: |
| 612 |
"""Modify delete_on_termination attribute""" |
| 613 |
|
| 614 |
delete_on_termination = module.params.get("delete_on_termination") |
| 615 |
changed = False |
| 616 |
|
| 617 |
# volume_in_use can return *shortly* before it appears on the instance |
| 618 |
# description |
| 619 |
mapped_block_device = None |
| 620 |
_attempt = 0 |
| 621 |
while mapped_block_device is None: |
| 622 |
_attempt += 1 |
| 623 |
instance_dict = get_instance(module, ec2_conn=ec2_conn, instance_id=instance_dict["instance_id"]) |
| 624 |
mapped_block_device = get_mapped_block_device(instance_dict=instance_dict, device_name=device_name) |
| 625 |
if mapped_block_device is None: |
| 626 |
if _attempt > 2: |
| 627 |
module.fail_json(msg="Unable to find device on instance", device=device_name, instance=instance_dict) |
| 628 |
time.sleep(1) |
| 629 |
|
| 630 |
if delete_on_termination != mapped_block_device["ebs"].get("delete_on_termination"): |
| 631 |
try: |
| 632 |
modify_instance_attribute( |
| 633 |
ec2_conn, |
| 634 |
instance_id=instance_dict["instance_id"], |
| 635 |
BlockDeviceMappings=[ |
| 636 |
{"DeviceName": device_name, "Ebs": {"DeleteOnTermination": delete_on_termination}} |
| 637 |
], |
| 638 |
) |
| 639 |
changed = True |
| 640 |
except AnsibleEC2Error as e: |
| 641 |
module.fail_json_aws( |
| 642 |
e, msg=f"Error while modifying Block Device Mapping of instance {instance_dict['instance_id']}" |
| 643 |
) |
| 644 |
|
| 645 |
return changed |
| 646 |
|
| 647 |
|
| 648 |
def get_attachment_data(volume_dict: Dict[str, Any], wanted_state: Optional[str] = None) -> List[Dict[str, Any]]: |
| 649 |
attachment_data = [] |
| 650 |
if not volume_dict: |
| 651 |
return attachment_data |
| 652 |
resource = volume_dict.get("attachments", []) |
| 653 |
if wanted_state: |
| 654 |
# filter 'state', return attachment matching wanted state |
| 655 |
resource = [data for data in resource if data["state"] == wanted_state] |
| 656 |
|
| 657 |
for data in resource: |
| 658 |
attachment_data.append( |
| 659 |
{ |
| 660 |
"attach_time": data.get("attach_time", None), |
| 661 |
"device": data.get("device", None), |
| 662 |
"instance_id": data.get("instance_id", None), |
| 663 |
"status": data.get("state", None), |
| 664 |
"delete_on_termination": data.get("delete_on_termination", None), |
| 665 |
} |
| 666 |
) |
| 667 |
|
| 668 |
return attachment_data |
| 669 |
|
| 670 |
|
| 671 |
def detach_volume(module: AnsibleAWSModule, ec2_conn, volume_dict: Dict[str, Any]) -> Tuple[Dict[str, Any], bool]: |
| 672 |
changed = False |
| 673 |
|
| 674 |
attachment_data = get_attachment_data(volume_dict, wanted_state="attached") |
| 675 |
# The ID of the instance must be specified if you are detaching a Multi-Attach enabled volume. |
| 676 |
for attachment in attachment_data: |
| 677 |
if module.check_mode: |
| 678 |
module.exit_json(changed=True, msg="Would have detached volume if not in check mode.") |
| 679 |
try: |
| 680 |
detach_ec2_volume(ec2_conn, volume_id=volume_dict["volume_id"], InstanceId=attachment["instance_id"]) |
| 681 |
except AnsibleEC2Error as e: |
| 682 |
module.fail_json_aws(e, msg="Error while detaching volume") |
| 683 |
|
| 684 |
wait_for_resource_state(ec2_conn, module, "volume_available", VolumeIds=[volume_dict["volume_id"]]) |
| 685 |
changed = True |
| 686 |
|
| 687 |
volume_dict = get_volume(module, ec2_conn, vol_id=volume_dict["volume_id"]) |
| 688 |
return volume_dict, changed |
| 689 |
|
| 690 |
|
| 691 |
def get_volume_info(volume: Dict[str, Any], tags: Optional[Dict[str, str]] = None) -> Dict[str, Any]: |
| 692 |
if not tags: |
| 693 |
tags = boto3_tag_list_to_ansible_dict(volume.get("tags")) |
| 694 |
attachment_data = get_attachment_data(volume) |
| 695 |
volume_info = { |
| 696 |
"create_time": volume.get("create_time"), |
| 697 |
"encrypted": volume.get("encrypted"), |
| 698 |
"id": volume.get("volume_id"), |
| 699 |
"iops": volume.get("iops"), |
| 700 |
"size": volume.get("size"), |
| 701 |
"snapshot_id": volume.get("snapshot_id"), |
| 702 |
"status": volume.get("state"), |
| 703 |
"type": volume.get("volume_type"), |
| 704 |
"zone": volume.get("availability_zone"), |
| 705 |
"attachment_set": attachment_data, |
| 706 |
"multi_attach_enabled": volume.get("multi_attach_enabled"), |
| 707 |
"tags": tags, |
| 708 |
} |
| 709 |
|
| 710 |
volume_info["throughput"] = volume.get("throughput") |
| 711 |
|
| 712 |
return volume_info |
| 713 |
|
| 714 |
|
| 715 |
def get_mapped_block_device( |
| 716 |
instance_dict: Optional[Dict[str, Any]] = None, device_name: Optional[str] = None |
| 717 |
) -> Optional[str]: |
| 718 |
mapped_block_device = None |
| 719 |
if not instance_dict: |
| 720 |
return mapped_block_device |
| 721 |
if not device_name: |
| 722 |
return mapped_block_device |
| 723 |
|
| 724 |
for device in instance_dict.get("block_device_mappings", []): |
| 725 |
if device["device_name"] == device_name: |
| 726 |
mapped_block_device = device |
| 727 |
break |
| 728 |
|
| 729 |
return mapped_block_device |
| 730 |
|
| 731 |
|
| 732 |
def ensure_tags( |
| 733 |
module: AnsibleAWSModule, connection, res_id: str, res_type: str, tags: Dict[str, Any], purge_tags: bool |
| 734 |
) -> Tuple[Dict[str, Any], bool]: |
| 735 |
if module.check_mode: |
| 736 |
return {}, True |
| 737 |
changed = ensure_ec2_tags(connection, module, res_id, res_type, tags, purge_tags, ["InvalidVolume.NotFound"]) |
| 738 |
final_tags = describe_ec2_tags(connection, module, res_id, res_type) |
| 739 |
|
| 740 |
return final_tags, changed |
| 741 |
|
| 742 |
|
| 743 |
def ensure_present(ec2_conn, module: AnsibleAWSModule, volume: Optional[Dict[str, Any]]) -> None: |
| 744 |
instance = module.params.get("instance") |
| 745 |
name = module.params.get("name") |
| 746 |
zone = module.params.get("zone") |
| 747 |
device_name = module.params.get("device_name") |
| 748 |
tags = module.params.get("tags") |
| 749 |
|
| 750 |
# Ensure we have the zone or can get the zone |
| 751 |
if instance is None and zone is None: |
| 752 |
module.fail_json(msg="You must specify either instance or zone") |
| 753 |
|
| 754 |
# Set volume detach flag |
| 755 |
if instance == "None" or instance == "": |
| 756 |
instance = None |
| 757 |
detach_vol_flag = True |
| 758 |
else: |
| 759 |
detach_vol_flag = False |
| 760 |
|
| 761 |
# Here we need to get the zone info for the instance. This covers situation where |
| 762 |
# instance is specified but zone isn't. |
| 763 |
# Useful for playbooks chaining instance launch with volume create + attach and where the |
| 764 |
# zone doesn't matter to the user. |
| 765 |
inst = None |
| 766 |
if instance: |
| 767 |
inst = get_instance(module, ec2_conn, instance_id=instance) |
| 768 |
zone = inst["placement"]["availability_zone"] |
| 769 |
|
| 770 |
# Use platform attribute to guess whether the instance is Windows or Linux |
| 771 |
if device_name is None: |
| 772 |
if inst.get("platform", "") == "Windows": |
| 773 |
device_name = "/dev/xvdf" |
| 774 |
else: |
| 775 |
device_name = "/dev/sdf" |
| 776 |
|
| 777 |
# Check if there is a volume already mounted there. |
| 778 |
mapped_device = get_mapped_block_device(instance_dict=inst, device_name=device_name) |
| 779 |
if mapped_device: |
| 780 |
other_volume_mapped = False |
| 781 |
if volume: |
| 782 |
if volume["volume_id"] != mapped_device["ebs"]["volume_id"]: |
| 783 |
other_volume_mapped = True |
| 784 |
else: |
| 785 |
# No volume found so this is another volume |
| 786 |
other_volume_mapped = True |
| 787 |
|
| 788 |
if other_volume_mapped: |
| 789 |
module.exit_json( |
| 790 |
msg=f"Volume mapping for {device_name} already exists on instance {instance}", |
| 791 |
volume_id=mapped_device["ebs"]["volume_id"], |
| 792 |
found_volume=volume, |
| 793 |
device=device_name, |
| 794 |
changed=False, |
| 795 |
) |
| 796 |
final_tags = None |
| 797 |
tags_changed = False |
| 798 |
if volume: |
| 799 |
volume, changed = update_volume(module, ec2_conn, volume) |
| 800 |
if name: |
| 801 |
if not tags: |
| 802 |
tags = boto3_tag_list_to_ansible_dict(volume.get("tags")) |
| 803 |
tags["Name"] = name |
| 804 |
final_tags, tags_changed = ensure_tags( |
| 805 |
module, ec2_conn, volume["volume_id"], "volume", tags, module.params.get("purge_tags") |
| 806 |
) |
| 807 |
else: |
| 808 |
volume, changed = create_volume(module, ec2_conn, zone=zone) |
| 809 |
|
| 810 |
if detach_vol_flag: |
| 811 |
volume, attach_changed = detach_volume(module, ec2_conn, volume_dict=volume) |
| 812 |
elif inst is not None: |
| 813 |
volume, attach_changed = attach_volume( |
| 814 |
module, ec2_conn, volume_dict=volume, instance_dict=inst, device_name=device_name |
| 815 |
) |
| 816 |
else: |
| 817 |
attach_changed = False |
| 818 |
|
| 819 |
# Add device, volume_id and volume_type parameters separately to maintain backward compatibility |
| 820 |
volume_info = get_volume_info(volume, tags=final_tags) |
| 821 |
|
| 822 |
if tags_changed or attach_changed: |
| 823 |
changed = True |
| 824 |
|
| 825 |
module.exit_json( |
| 826 |
changed=changed, |
| 827 |
volume=volume_info, |
| 828 |
device=device_name, |
| 829 |
volume_id=volume_info["id"], |
| 830 |
volume_type=volume_info["type"], |
| 831 |
) |
| 832 |
|
| 833 |
|
| 834 |
def ensure_absent(ec2_conn, module: AnsibleAWSModule, volume: Optional[Dict[str, Any]]) -> None: |
| 835 |
name = module.params.get("name") |
| 836 |
param_id = module.params.get("id") |
| 837 |
changed = False |
| 838 |
if not name and not param_id: |
| 839 |
module.fail_json("A volume name or id is required for deletion") |
| 840 |
if volume and volume.get("state") not in ("deleting", "deleted"): |
| 841 |
if module.check_mode: |
| 842 |
module.exit_json(changed=True, msg="Would have deleted volume if not in check mode.") |
| 843 |
detach_volume(module, ec2_conn, volume_dict=volume) |
| 844 |
changed = delete_volume(module, ec2_conn, volume_id=volume["volume_id"]) |
| 845 |
module.exit_json(changed=changed) |
| 846 |
|
| 847 |
|
| 848 |
def main(): |
| 849 |
argument_spec = dict( |
| 850 |
instance=dict(), |
| 851 |
id=dict(), |
| 852 |
name=dict(), |
| 853 |
volume_size=dict(type="int"), |
| 854 |
volume_type=dict(default="standard", choices=["standard", "gp2", "io1", "st1", "sc1", "gp3", "io2"]), |
| 855 |
iops=dict(type="int"), |
| 856 |
encrypted=dict(default=False, type="bool"), |
| 857 |
kms_key_id=dict(), |
| 858 |
device_name=dict(), |
| 859 |
delete_on_termination=dict(default=False, type="bool"), |
| 860 |
zone=dict(aliases=["availability_zone", "aws_zone", "ec2_zone"]), |
| 861 |
snapshot=dict(), |
| 862 |
state=dict(default="present", choices=["absent", "present"]), |
| 863 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 864 |
modify_volume=dict(default=False, type="bool"), |
| 865 |
throughput=dict(type="int"), |
| 866 |
outpost_arn=dict(type="str"), |
| 867 |
purge_tags=dict(type="bool", default=True), |
| 868 |
multi_attach=dict(type="bool"), |
| 869 |
volume_initialization_rate=dict(type="int"), |
| 870 |
) |
| 871 |
|
| 872 |
module = AnsibleAWSModule( |
| 873 |
argument_spec=argument_spec, |
| 874 |
required_if=[ |
| 875 |
["volume_type", "io1", ["iops"]], |
| 876 |
["volume_type", "io2", ["iops"]], |
| 877 |
], |
| 878 |
supports_check_mode=True, |
| 879 |
) |
| 880 |
|
| 881 |
param_id = module.params.get("id") |
| 882 |
name = module.params.get("name") |
| 883 |
volume_size = module.params.get("volume_size") |
| 884 |
snapshot = module.params.get("snapshot") |
| 885 |
state = module.params.get("state") |
| 886 |
iops = module.params.get("iops") |
| 887 |
volume_type = module.params.get("volume_type") |
| 888 |
throughput = module.params.get("throughput") |
| 889 |
multi_attach = module.params.get("multi_attach") |
| 890 |
volume_initialization_rate = module.params.get("volume_initialization_rate") |
| 891 |
|
| 892 |
if iops: |
| 893 |
if volume_type in ("gp2", "st1", "sc1", "standard"): |
| 894 |
module.fail_json(msg="IOPS is not supported for gp2, st1, sc1, or standard volumes.") |
| 895 |
|
| 896 |
if volume_type == "gp3" and (int(iops) < 3000 or int(iops) > 80000): |
| 897 |
module.fail_json(msg="For a gp3 volume type, IOPS values must be between 3000 and 80000.") |
| 898 |
|
| 899 |
if volume_type in ("io1", "io2") and (int(iops) < 100 or int(iops) > 64000): |
| 900 |
module.fail_json(msg="For io1 and io2 volume types, IOPS values must be between 100 and 64000.") |
| 901 |
|
| 902 |
if throughput: |
| 903 |
if volume_type != "gp3": |
| 904 |
module.fail_json(msg="Throughput is only supported for gp3 volume.") |
| 905 |
if throughput < 125 or throughput > 2000: |
| 906 |
module.fail_json(msg="Throughput values must be between 125 and 2000.") |
| 907 |
|
| 908 |
if multi_attach is True and volume_type not in ("io1", "io2"): |
| 909 |
module.fail_json(msg="multi_attach is only supported for io1 and io2 volumes.") |
| 910 |
|
| 911 |
if volume_initialization_rate: |
| 912 |
if not snapshot: |
| 913 |
module.fail_json(msg="Volume initialization rate is only supported when creating a volume from snapshot.") |
| 914 |
if int(volume_initialization_rate) < 100 or int(volume_initialization_rate) > 300: |
| 915 |
module.fail_json(msg="Volume initialization rate must be between 100 and 300 MiB/s.") |
| 916 |
|
| 917 |
ec2_conn = module.client("ec2") |
| 918 |
|
| 919 |
# Delaying the checks until after the instance check allows us to get volume ids for existing volumes |
| 920 |
# without needing to pass an unused volume_size |
| 921 |
if not volume_size and not (param_id or name or snapshot): |
| 922 |
module.fail_json(msg="You must specify volume_size or identify an existing volume by id, name, or snapshot") |
| 923 |
|
| 924 |
# Try getting volume |
| 925 |
volume = get_volume(module, ec2_conn, fail_on_not_found=False) |
| 926 |
if state == "present": |
| 927 |
ensure_present(ec2_conn, module, volume) |
| 928 |
elif state == "absent": |
| 929 |
ensure_absent(ec2_conn, module, volume) |
| 930 |
|
| 931 |
|
| 932 |
if __name__ == "__main__": |
| 933 |
main() |