| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) 2017, Ryan Scott Brown <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: terraform |
| 10 |
short_description: Manages a Terraform deployment (and plans) |
| 11 |
description: |
| 12 |
- Provides support for deploying resources with Terraform and pulling resource information back into Ansible. |
| 13 |
extends_documentation_fragment: |
| 14 |
- community.general._attributes |
| 15 |
attributes: |
| 16 |
check_mode: |
| 17 |
support: full |
| 18 |
diff_mode: |
| 19 |
support: full |
| 20 |
version_added: 8.3.0 |
| 21 |
options: |
| 22 |
state: |
| 23 |
choices: ['planned', 'present', 'absent'] |
| 24 |
description: |
| 25 |
- Goal state of given stage/project. |
| 26 |
type: str |
| 27 |
default: present |
| 28 |
binary_path: |
| 29 |
description: |
| 30 |
- The path of a C(terraform) binary to use, relative to the 'service_path' unless you supply an absolute path. |
| 31 |
type: path |
| 32 |
project_path: |
| 33 |
description: |
| 34 |
- The path to the root of the Terraform directory with the C(vars.tf)/C(main.tf)/etc to use. |
| 35 |
type: path |
| 36 |
required: true |
| 37 |
plugin_paths: |
| 38 |
description: |
| 39 |
- List of paths containing Terraform plugin executable files. |
| 40 |
- Plugin executables can be downloaded from U(https://releases.hashicorp.com/). |
| 41 |
- When set, the plugin discovery and auto-download behavior of Terraform is disabled. |
| 42 |
- The directory structure in the plugin path can be tricky. The Terraform docs |
| 43 |
U(https://learn.hashicorp.com/tutorials/terraform/automate-terraform#pre-installed-plugins) |
| 44 |
show a simple directory of files, but actually, the directory structure has to follow the same structure you would |
| 45 |
see if Terraform auto-downloaded the plugins. See the examples below for a tree output of an example plugin directory. |
| 46 |
type: list |
| 47 |
elements: path |
| 48 |
version_added: 3.0.0 |
| 49 |
workspace: |
| 50 |
description: |
| 51 |
- The terraform workspace to work with. This sets the E(TF_WORKSPACE) environmental variable that is used to override |
| 52 |
workspace selection. For more information about workspaces have a look at U(https://developer.hashicorp.com/terraform/language/state/workspaces). |
| 53 |
type: str |
| 54 |
default: default |
| 55 |
purge_workspace: |
| 56 |
description: |
| 57 |
- Only works with state = absent. |
| 58 |
- If V(true), the O(workspace) is deleted after the C(terraform destroy) action. |
| 59 |
- If O(workspace=default) then it is not deleted. |
| 60 |
default: false |
| 61 |
type: bool |
| 62 |
plan_file: |
| 63 |
description: |
| 64 |
- The path to an existing Terraform plan file to apply. If this is not specified, Ansible builds a new TF plan and execute |
| 65 |
it. Note that this option is required if O(state=planned). |
| 66 |
type: path |
| 67 |
state_file: |
| 68 |
description: |
| 69 |
- The path to an existing Terraform state file to use when building plan. If this is not specified, the default C(terraform.tfstate) |
| 70 |
is used. |
| 71 |
- This option is ignored when plan is specified. |
| 72 |
type: path |
| 73 |
variables_files: |
| 74 |
description: |
| 75 |
- The path to a variables file for Terraform to fill into the TF configurations. This can accept a list of paths to |
| 76 |
multiple variables files. |
| 77 |
type: list |
| 78 |
elements: path |
| 79 |
aliases: ['variables_file'] |
| 80 |
variables: |
| 81 |
description: |
| 82 |
- A group of key-values pairs to override template variables or those in variables files. By default, only string and |
| 83 |
number values are allowed, which are passed on unquoted. |
| 84 |
- Support complex variable structures (lists, dictionaries, numbers, and booleans) to reflect terraform variable syntax |
| 85 |
when O(complex_vars=true). |
| 86 |
- Ansible integers or floats are mapped to terraform numbers. |
| 87 |
- Ansible strings are mapped to terraform strings. |
| 88 |
- Ansible dictionaries are mapped to terraform objects. |
| 89 |
- Ansible lists are mapped to terraform lists. |
| 90 |
- Ansible booleans are mapped to terraform booleans. |
| 91 |
- B(Note) passwords passed as variables are visible in the log output. Make sure to use C(no_log=true) in production!. |
| 92 |
type: dict |
| 93 |
complex_vars: |
| 94 |
description: |
| 95 |
- Enable/disable capability to handle complex variable structures for C(terraform). |
| 96 |
- If V(true) the O(variables) also accepts dictionaries, lists, and booleans to be passed to C(terraform). Strings that |
| 97 |
are passed are correctly quoted. |
| 98 |
- When disabled, supports only simple variables (strings, integers, and floats), and passes them on unquoted. |
| 99 |
type: bool |
| 100 |
default: false |
| 101 |
version_added: 5.7.0 |
| 102 |
targets: |
| 103 |
description: |
| 104 |
- A list of specific resources to target in this plan/application. The resources selected here are also auto-include |
| 105 |
any dependencies. |
| 106 |
type: list |
| 107 |
elements: str |
| 108 |
default: [] |
| 109 |
lock: |
| 110 |
description: |
| 111 |
- Enable statefile locking, if you use a service that accepts locks (such as S3+DynamoDB) to store your statefile. |
| 112 |
type: bool |
| 113 |
default: true |
| 114 |
lock_timeout: |
| 115 |
description: |
| 116 |
- How long to maintain the lock on the statefile, if you use a service that accepts locks (such as S3+DynamoDB). |
| 117 |
type: int |
| 118 |
force_init: |
| 119 |
description: |
| 120 |
- To avoid duplicating infra, if a state file cannot be found this forces a C(terraform init). Generally, this should |
| 121 |
be turned off unless you intend to provision an entirely new Terraform deployment. |
| 122 |
default: false |
| 123 |
type: bool |
| 124 |
overwrite_init: |
| 125 |
description: |
| 126 |
- Run init even if C(.terraform/terraform.tfstate) already exists in O(project_path). |
| 127 |
default: true |
| 128 |
type: bool |
| 129 |
version_added: '3.2.0' |
| 130 |
backend_config: |
| 131 |
description: |
| 132 |
- A group of key-values to provide at init stage to the -backend-config parameter. |
| 133 |
type: dict |
| 134 |
backend_config_files: |
| 135 |
description: |
| 136 |
- The path to a configuration file to provide at init state to the -backend-config parameter. This can accept a list |
| 137 |
of paths to multiple configuration files. |
| 138 |
type: list |
| 139 |
elements: path |
| 140 |
version_added: '0.2.0' |
| 141 |
provider_upgrade: |
| 142 |
description: |
| 143 |
- Allows Terraform init to upgrade providers to versions specified in the project's version constraints. |
| 144 |
default: false |
| 145 |
type: bool |
| 146 |
version_added: 4.8.0 |
| 147 |
init_reconfigure: |
| 148 |
description: |
| 149 |
- Forces backend reconfiguration during init. |
| 150 |
default: false |
| 151 |
type: bool |
| 152 |
version_added: '1.3.0' |
| 153 |
check_destroy: |
| 154 |
description: |
| 155 |
- Apply only when no resources are destroyed. Note that this only prevents "destroy" actions, but not "destroy and re-create" |
| 156 |
actions. This option is ignored when O(state=absent). |
| 157 |
type: bool |
| 158 |
default: false |
| 159 |
version_added: '3.3.0' |
| 160 |
parallelism: |
| 161 |
description: |
| 162 |
- Restrict concurrent operations when Terraform applies the plan. |
| 163 |
type: int |
| 164 |
version_added: '3.8.0' |
| 165 |
no_color: |
| 166 |
description: |
| 167 |
- If V(true), suppress color codes in output from Terraform commands. |
| 168 |
- If V(false), allows Terraform to use color codes in its output. |
| 169 |
type: bool |
| 170 |
default: true |
| 171 |
version_added: 11.0.0 |
| 172 |
notes: |
| 173 |
- To just run a C(terraform plan), use check mode. |
| 174 |
requirements: ["terraform"] |
| 175 |
author: "Ryan Scott Brown (@ryansb)" |
| 176 |
""" |
| 177 |
|
| 178 |
EXAMPLES = r""" |
| 179 |
- name: Basic deploy of a service |
| 180 |
community.general.terraform: |
| 181 |
project_path: '{{ project_dir }}' |
| 182 |
state: present |
| 183 |
|
| 184 |
- name: Deploy with color output enabled |
| 185 |
community.general.terraform: |
| 186 |
project_path: '{{ project_dir }}' |
| 187 |
state: present |
| 188 |
no_color: false |
| 189 |
|
| 190 |
- name: Define the backend configuration at init |
| 191 |
community.general.terraform: |
| 192 |
project_path: 'project/' |
| 193 |
state: "{{ state }}" |
| 194 |
force_init: true |
| 195 |
backend_config: |
| 196 |
region: "eu-west-1" |
| 197 |
bucket: "some-bucket" |
| 198 |
key: "random.tfstate" |
| 199 |
|
| 200 |
- name: Define the backend configuration with one or more files at init |
| 201 |
community.general.terraform: |
| 202 |
project_path: 'project/' |
| 203 |
state: "{{ state }}" |
| 204 |
force_init: true |
| 205 |
backend_config_files: |
| 206 |
- /path/to/backend_config_file_1 |
| 207 |
- /path/to/backend_config_file_2 |
| 208 |
|
| 209 |
- name: Disable plugin discovery and auto-download by setting plugin_paths |
| 210 |
community.general.terraform: |
| 211 |
project_path: 'project/' |
| 212 |
state: "{{ state }}" |
| 213 |
force_init: true |
| 214 |
plugin_paths: |
| 215 |
- /path/to/plugins_dir_1 |
| 216 |
- /path/to/plugins_dir_2 |
| 217 |
|
| 218 |
- name: Complex variables example |
| 219 |
community.general.terraform: |
| 220 |
project_path: '{{ project_dir }}' |
| 221 |
state: present |
| 222 |
complex_vars: true |
| 223 |
variables: |
| 224 |
vm_name: "{{ inventory_hostname }}" |
| 225 |
vm_vcpus: 2 |
| 226 |
vm_mem: 2048 |
| 227 |
vm_additional_disks: |
| 228 |
- label: "Third Disk" |
| 229 |
size: 40 |
| 230 |
thin_provisioned: true |
| 231 |
unit_number: 2 |
| 232 |
- label: "Fourth Disk" |
| 233 |
size: 22 |
| 234 |
thin_provisioned: true |
| 235 |
unit_number: 3 |
| 236 |
force_init: true |
| 237 |
|
| 238 |
### Example directory structure for plugin_paths example |
| 239 |
# $ tree /path/to/plugins_dir_1 |
| 240 |
# /path/to/plugins_dir_1/ |
| 241 |
# └── registry.terraform.io |
| 242 |
# └── hashicorp |
| 243 |
# └── vsphere |
| 244 |
# ├── 1.24.0 |
| 245 |
# │ └── linux_amd64 |
| 246 |
# │ └── terraform-provider-vsphere_v1.24.0_x4 |
| 247 |
# └── 1.26.0 |
| 248 |
# └── linux_amd64 |
| 249 |
# └── terraform-provider-vsphere_v1.26.0_x4 |
| 250 |
""" |
| 251 |
|
| 252 |
RETURN = r""" |
| 253 |
outputs: |
| 254 |
type: complex |
| 255 |
description: A dictionary of all the TF outputs by their assigned name. Use RV(ignore:outputs.MyOutputName.value) to access |
| 256 |
the value. |
| 257 |
returned: on success |
| 258 |
sample: '{"bukkit_arn": {"sensitive": false, "type": "string", "value": "arn:aws:s3:::tf-test-bukkit"}' |
| 259 |
contains: |
| 260 |
sensitive: |
| 261 |
type: bool |
| 262 |
returned: always |
| 263 |
description: Whether Terraform has marked this value as sensitive. |
| 264 |
type: |
| 265 |
type: str |
| 266 |
returned: always |
| 267 |
description: The type of the value (string, int, and so on). |
| 268 |
value: |
| 269 |
type: str |
| 270 |
returned: always |
| 271 |
description: The value of the output as interpolated by Terraform. |
| 272 |
command: |
| 273 |
type: str |
| 274 |
description: Full C(terraform) command built by this module, in case you want to re-run the command outside the module or |
| 275 |
debug a problem. |
| 276 |
returned: always |
| 277 |
sample: terraform apply ... |
| 278 |
""" |
| 279 |
|
| 280 |
import json |
| 281 |
import os |
| 282 |
import tempfile |
| 283 |
from shlex import quote as shlex_quote |
| 284 |
|
| 285 |
from ansible.module_utils.basic import AnsibleModule |
| 286 |
|
| 287 |
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion |
| 288 |
|
| 289 |
module = None |
| 290 |
|
| 291 |
|
| 292 |
def get_version(bin_path): |
| 293 |
extract_version = module.run_command([bin_path, "version", "-json"]) |
| 294 |
terraform_version = (json.loads(extract_version[1]))["terraform_version"] |
| 295 |
return terraform_version |
| 296 |
|
| 297 |
|
| 298 |
def preflight_validation(bin_path, project_path, version, variables_args=None, plan_file=None, no_color=True): |
| 299 |
if project_path is None or "/" not in project_path: |
| 300 |
module.fail_json(msg="Path for Terraform project can not be None or ''.") |
| 301 |
if not os.path.exists(bin_path): |
| 302 |
module.fail_json( |
| 303 |
msg=f"Path for Terraform binary '{bin_path}' doesn't exist on this host - check the path and try again please." |
| 304 |
) |
| 305 |
if not os.path.isdir(project_path): |
| 306 |
module.fail_json( |
| 307 |
msg=f"Path for Terraform project '{project_path}' doesn't exist on this host - check the path and try again please." |
| 308 |
) |
| 309 |
cmd = [bin_path, "validate"] |
| 310 |
if no_color: |
| 311 |
cmd.append("-no-color") |
| 312 |
if LooseVersion(version) < LooseVersion("0.15.0"): |
| 313 |
module.run_command(cmd + variables_args, check_rc=True, cwd=project_path) |
| 314 |
else: |
| 315 |
module.run_command(cmd, check_rc=True, cwd=project_path) |
| 316 |
|
| 317 |
|
| 318 |
def _state_args(state_file): |
| 319 |
if not state_file: |
| 320 |
return [] |
| 321 |
if not os.path.exists(state_file): |
| 322 |
module.warn( |
| 323 |
f'Could not find state_file "{state_file}", the process will not destroy any resources, please check your state file path.' |
| 324 |
) |
| 325 |
return ["-state", state_file] |
| 326 |
|
| 327 |
|
| 328 |
def init_plugins( |
| 329 |
bin_path, |
| 330 |
project_path, |
| 331 |
backend_config, |
| 332 |
backend_config_files, |
| 333 |
init_reconfigure, |
| 334 |
provider_upgrade, |
| 335 |
plugin_paths, |
| 336 |
workspace, |
| 337 |
no_color=True, |
| 338 |
): |
| 339 |
command = [bin_path, "init", "-input=false"] |
| 340 |
if no_color: |
| 341 |
command.append("-no-color") |
| 342 |
if backend_config: |
| 343 |
for key, val in backend_config.items(): |
| 344 |
command.extend(["-backend-config", f"{key}={val}"]) |
| 345 |
if backend_config_files: |
| 346 |
for f in backend_config_files: |
| 347 |
command.extend(["-backend-config", f]) |
| 348 |
if init_reconfigure: |
| 349 |
command.extend(["-reconfigure"]) |
| 350 |
if provider_upgrade: |
| 351 |
command.extend(["-upgrade"]) |
| 352 |
if plugin_paths: |
| 353 |
for plugin_path in plugin_paths: |
| 354 |
command.extend(["-plugin-dir", plugin_path]) |
| 355 |
rc, out, err = module.run_command( |
| 356 |
command, check_rc=True, cwd=project_path, environ_update={"TF_WORKSPACE": workspace} |
| 357 |
) |
| 358 |
|
| 359 |
|
| 360 |
def get_workspace_context(bin_path, project_path, no_color=True): |
| 361 |
workspace_ctx = {"current": "default", "all": []} |
| 362 |
command = [bin_path, "workspace", "list"] |
| 363 |
if no_color: |
| 364 |
command.append("-no-color") |
| 365 |
|
| 366 |
rc, out, err = module.run_command(command, cwd=project_path) |
| 367 |
if rc != 0: |
| 368 |
module.warn(f"Failed to list Terraform workspaces:\n{err}") |
| 369 |
for item in out.split("\n"): |
| 370 |
stripped_item = item.strip() |
| 371 |
if not stripped_item: |
| 372 |
continue |
| 373 |
elif stripped_item.startswith("* "): |
| 374 |
workspace_ctx["current"] = stripped_item.replace("* ", "") |
| 375 |
workspace_ctx["all"].append(stripped_item.replace("* ", "")) |
| 376 |
else: |
| 377 |
workspace_ctx["all"].append(stripped_item) |
| 378 |
return workspace_ctx |
| 379 |
|
| 380 |
|
| 381 |
def _workspace_cmd(bin_path, project_path, action, workspace, no_color=True): |
| 382 |
command = [bin_path, "workspace", action, workspace] |
| 383 |
if no_color: |
| 384 |
command.append("-no-color") |
| 385 |
rc, out, err = module.run_command(command, check_rc=True, cwd=project_path) |
| 386 |
return rc, out, err |
| 387 |
|
| 388 |
|
| 389 |
def create_workspace(bin_path, project_path, workspace, no_color=True): |
| 390 |
_workspace_cmd(bin_path, project_path, "new", workspace, no_color) |
| 391 |
|
| 392 |
|
| 393 |
def select_workspace(bin_path, project_path, workspace, no_color=True): |
| 394 |
_workspace_cmd(bin_path, project_path, "select", workspace, no_color) |
| 395 |
|
| 396 |
|
| 397 |
def remove_workspace(bin_path, project_path, workspace, no_color=True): |
| 398 |
_workspace_cmd(bin_path, project_path, "delete", workspace, no_color) |
| 399 |
|
| 400 |
|
| 401 |
def build_plan(command, project_path, variables_args, state_file, targets, state, args, plan_path=None, no_color=True): |
| 402 |
if plan_path is None: |
| 403 |
f, plan_path = tempfile.mkstemp(suffix=".tfplan") |
| 404 |
|
| 405 |
local_command = command[:] |
| 406 |
|
| 407 |
plan_command = [command[0], "plan"] |
| 408 |
|
| 409 |
if state == "planned": |
| 410 |
for c in local_command[1:]: |
| 411 |
plan_command.append(c) |
| 412 |
|
| 413 |
if state == "present": |
| 414 |
for a in args: |
| 415 |
local_command.remove(a) |
| 416 |
for c in local_command[1:]: |
| 417 |
plan_command.append(c) |
| 418 |
|
| 419 |
if state == "absent": |
| 420 |
for a in args: |
| 421 |
plan_command.append(a) |
| 422 |
|
| 423 |
plan_options = ["-input=false", "-detailed-exitcode", "-out", plan_path] |
| 424 |
if no_color: |
| 425 |
plan_options.insert(0, "-no-color") |
| 426 |
plan_command.extend(plan_options) |
| 427 |
|
| 428 |
for t in targets: |
| 429 |
plan_command.extend(["-target", t]) |
| 430 |
|
| 431 |
plan_command.extend(_state_args(state_file)) |
| 432 |
|
| 433 |
rc, out, err = module.run_command(plan_command + variables_args, cwd=project_path) |
| 434 |
|
| 435 |
if rc == 0: |
| 436 |
# no changes |
| 437 |
return plan_path, False, out, err, plan_command if state == "planned" else command |
| 438 |
elif rc == 1: |
| 439 |
# failure to plan |
| 440 |
module.fail_json( |
| 441 |
msg=( |
| 442 |
f"Terraform plan could not be created\nSTDOUT: {out}\nSTDERR: {err}\n" |
| 443 |
f"COMMAND: {' '.join(plan_command)} {' '.join([shlex_quote(arg) for arg in variables_args])}" |
| 444 |
) |
| 445 |
) |
| 446 |
elif rc == 2: |
| 447 |
# changes, but successful |
| 448 |
return plan_path, True, out, err, plan_command if state == "planned" else command |
| 449 |
|
| 450 |
module.fail_json( |
| 451 |
msg=f"Terraform plan failed with unexpected exit code {rc}.\nSTDOUT: {out}\nSTDERR: {err}\n" |
| 452 |
f"COMMAND: {' '.join(plan_command)} {' '.join([shlex_quote(arg) for arg in variables_args])}" |
| 453 |
) |
| 454 |
|
| 455 |
|
| 456 |
def get_diff(diff_output): |
| 457 |
def get_tf_resource_address(e): |
| 458 |
return e["resource"] |
| 459 |
|
| 460 |
diff_json_output = json.loads(diff_output) |
| 461 |
|
| 462 |
# Ignore diff if resource_changes does not exists in tfplan |
| 463 |
if "resource_changes" in diff_json_output: |
| 464 |
tf_reosource_changes = diff_json_output["resource_changes"] |
| 465 |
else: |
| 466 |
module.warn("Cannot find resource_changes in terraform plan, diff/check ignored") |
| 467 |
return False, {} |
| 468 |
|
| 469 |
diff_after = [] |
| 470 |
diff_before = [] |
| 471 |
changed = False |
| 472 |
for item in tf_reosource_changes: |
| 473 |
item_change = item["change"] |
| 474 |
tf_before_state = {"resource": item["address"], "change": item["change"]["before"]} |
| 475 |
tf_after_state = {"resource": item["address"], "change": item["change"]["after"]} |
| 476 |
|
| 477 |
if item_change["actions"] == ["update"] or item_change["actions"] == ["delete", "create"]: |
| 478 |
diff_before.append(tf_before_state) |
| 479 |
diff_after.append(tf_after_state) |
| 480 |
changed = True |
| 481 |
|
| 482 |
if item_change["actions"] == ["delete"]: |
| 483 |
diff_before.append(tf_before_state) |
| 484 |
changed = True |
| 485 |
|
| 486 |
if item_change["actions"] == ["create"]: |
| 487 |
diff_after.append(tf_after_state) |
| 488 |
changed = True |
| 489 |
|
| 490 |
diff_before.sort(key=get_tf_resource_address) |
| 491 |
diff_after.sort(key=get_tf_resource_address) |
| 492 |
|
| 493 |
return changed, dict( |
| 494 |
before=({"data": diff_before}), |
| 495 |
after=({"data": diff_after}), |
| 496 |
) |
| 497 |
|
| 498 |
|
| 499 |
def main(): |
| 500 |
global module |
| 501 |
module = AnsibleModule( |
| 502 |
argument_spec=dict( |
| 503 |
project_path=dict(required=True, type="path"), |
| 504 |
binary_path=dict(type="path"), |
| 505 |
plugin_paths=dict(type="list", elements="path"), |
| 506 |
workspace=dict(type="str", default="default"), |
| 507 |
purge_workspace=dict(type="bool", default=False), |
| 508 |
state=dict(default="present", choices=["present", "absent", "planned"]), |
| 509 |
variables=dict(type="dict"), |
| 510 |
complex_vars=dict(type="bool", default=False), |
| 511 |
variables_files=dict(aliases=["variables_file"], type="list", elements="path"), |
| 512 |
plan_file=dict(type="path"), |
| 513 |
state_file=dict(type="path"), |
| 514 |
targets=dict(type="list", elements="str", default=[]), |
| 515 |
lock=dict(type="bool", default=True), |
| 516 |
lock_timeout=dict(type="int"), |
| 517 |
force_init=dict(type="bool", default=False), |
| 518 |
backend_config=dict(type="dict"), |
| 519 |
backend_config_files=dict(type="list", elements="path"), |
| 520 |
init_reconfigure=dict(type="bool", default=False), |
| 521 |
overwrite_init=dict(type="bool", default=True), |
| 522 |
check_destroy=dict(type="bool", default=False), |
| 523 |
parallelism=dict(type="int"), |
| 524 |
provider_upgrade=dict(type="bool", default=False), |
| 525 |
no_color=dict(type="bool", default=True), |
| 526 |
), |
| 527 |
required_if=[("state", "planned", ["plan_file"])], |
| 528 |
supports_check_mode=True, |
| 529 |
) |
| 530 |
|
| 531 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 532 |
|
| 533 |
project_path = module.params.get("project_path") |
| 534 |
bin_path = module.params.get("binary_path") |
| 535 |
plugin_paths = module.params.get("plugin_paths") |
| 536 |
workspace = module.params.get("workspace") |
| 537 |
purge_workspace = module.params.get("purge_workspace") |
| 538 |
state = module.params.get("state") |
| 539 |
variables = module.params.get("variables") or {} |
| 540 |
complex_vars = module.params.get("complex_vars") |
| 541 |
variables_files = module.params.get("variables_files") |
| 542 |
plan_file = module.params.get("plan_file") |
| 543 |
state_file = module.params.get("state_file") |
| 544 |
force_init = module.params.get("force_init") |
| 545 |
backend_config = module.params.get("backend_config") |
| 546 |
backend_config_files = module.params.get("backend_config_files") |
| 547 |
init_reconfigure = module.params.get("init_reconfigure") |
| 548 |
overwrite_init = module.params.get("overwrite_init") |
| 549 |
check_destroy = module.params.get("check_destroy") |
| 550 |
provider_upgrade = module.params.get("provider_upgrade") |
| 551 |
no_color = module.params.get("no_color") |
| 552 |
|
| 553 |
if bin_path is not None: |
| 554 |
command = [bin_path] |
| 555 |
else: |
| 556 |
command = [module.get_bin_path("terraform", required=True)] |
| 557 |
|
| 558 |
checked_version = get_version(command[0]) |
| 559 |
|
| 560 |
if LooseVersion(checked_version) < LooseVersion("0.15.0"): |
| 561 |
if no_color: |
| 562 |
DESTROY_ARGS = ("destroy", "-no-color", "-force") |
| 563 |
APPLY_ARGS = ("apply", "-no-color", "-input=false", "-auto-approve=true") |
| 564 |
else: |
| 565 |
DESTROY_ARGS = ("destroy", "-force") |
| 566 |
APPLY_ARGS = ("apply", "-input=false", "-auto-approve=true") |
| 567 |
else: |
| 568 |
if no_color: |
| 569 |
DESTROY_ARGS = ("destroy", "-no-color", "-auto-approve") |
| 570 |
APPLY_ARGS = ("apply", "-no-color", "-input=false", "-auto-approve") |
| 571 |
else: |
| 572 |
DESTROY_ARGS = ("destroy", "-auto-approve") |
| 573 |
APPLY_ARGS = ("apply", "-input=false", "-auto-approve") |
| 574 |
|
| 575 |
if force_init: |
| 576 |
if overwrite_init or not os.path.isfile(os.path.join(project_path, ".terraform", "terraform.tfstate")): |
| 577 |
init_plugins( |
| 578 |
command[0], |
| 579 |
project_path, |
| 580 |
backend_config, |
| 581 |
backend_config_files, |
| 582 |
init_reconfigure, |
| 583 |
provider_upgrade, |
| 584 |
plugin_paths, |
| 585 |
workspace, |
| 586 |
no_color, |
| 587 |
) |
| 588 |
|
| 589 |
workspace_ctx = get_workspace_context(command[0], project_path, no_color) |
| 590 |
if workspace_ctx["current"] != workspace: |
| 591 |
if workspace not in workspace_ctx["all"]: |
| 592 |
create_workspace(command[0], project_path, workspace, no_color) |
| 593 |
else: |
| 594 |
select_workspace(command[0], project_path, workspace, no_color) |
| 595 |
|
| 596 |
if state == "present": |
| 597 |
command.extend(APPLY_ARGS) |
| 598 |
elif state == "absent": |
| 599 |
command.extend(DESTROY_ARGS) |
| 600 |
|
| 601 |
if state == "present" and module.params.get("parallelism") is not None: |
| 602 |
command.append(f"-parallelism={module.params.get('parallelism')}") |
| 603 |
|
| 604 |
def format_args(vars): |
| 605 |
if vars is None: |
| 606 |
return "null" |
| 607 |
elif isinstance(vars, str): |
| 608 |
escaped = vars.replace("\\", "\\\\").replace('"', '\\"') |
| 609 |
return f'"{escaped}"'.replace("\n", "\\n") |
| 610 |
elif isinstance(vars, bool): |
| 611 |
if vars: |
| 612 |
return "true" |
| 613 |
else: |
| 614 |
return "false" |
| 615 |
return str(vars) |
| 616 |
|
| 617 |
def process_complex_args(vars): |
| 618 |
ret_out = [] |
| 619 |
if isinstance(vars, dict): |
| 620 |
for k, v in vars.items(): |
| 621 |
if isinstance(v, dict): |
| 622 |
ret_out.append(f"{k}={{{process_complex_args(v)}}}") |
| 623 |
elif isinstance(v, list): |
| 624 |
ret_out.append(f"{k}={process_complex_args(v)}") |
| 625 |
elif isinstance(v, (int, float, str, bool)) or v is None: |
| 626 |
ret_out.append(f"{k}={format_args(v)}") |
| 627 |
else: |
| 628 |
# only to handle anything unforeseen |
| 629 |
module.fail_json( |
| 630 |
msg="Supported types are, dictionaries, lists, strings, integers, boolean and float." |
| 631 |
) |
| 632 |
if isinstance(vars, list): |
| 633 |
l_out = [] |
| 634 |
for item in vars: |
| 635 |
if isinstance(item, dict): |
| 636 |
l_out.append(f"{{{process_complex_args(item)}}}") |
| 637 |
elif isinstance(item, list): |
| 638 |
l_out.append(f"{process_complex_args(item)}") |
| 639 |
elif isinstance(item, (str, int, float, bool)) or item is None: |
| 640 |
l_out.append(format_args(item)) |
| 641 |
else: |
| 642 |
# only to handle anything unforeseen |
| 643 |
module.fail_json( |
| 644 |
msg="Supported types are, dictionaries, lists, strings, integers, boolean and float." |
| 645 |
) |
| 646 |
|
| 647 |
ret_out.append(f"[{','.join(l_out)}]") |
| 648 |
return ",".join(ret_out) |
| 649 |
|
| 650 |
variables_args = [] |
| 651 |
if complex_vars: |
| 652 |
for k, v in variables.items(): |
| 653 |
if isinstance(v, dict): |
| 654 |
variables_args.extend(["-var", f"{k}={{{process_complex_args(v)}}}"]) |
| 655 |
elif isinstance(v, list): |
| 656 |
variables_args.extend(["-var", f"{k}={process_complex_args(v)}"]) |
| 657 |
# on the top-level we need to pass just the python string with necessary |
| 658 |
# terraform string escape sequences |
| 659 |
elif isinstance(v, str): |
| 660 |
variables_args.extend(["-var", f"{k}={v}"]) |
| 661 |
else: |
| 662 |
variables_args.extend(["-var", f"{k}={format_args(v)}"]) |
| 663 |
else: |
| 664 |
for k, v in variables.items(): |
| 665 |
variables_args.extend(["-var", f"{k}={v}"]) |
| 666 |
|
| 667 |
if variables_files: |
| 668 |
for f in variables_files: |
| 669 |
variables_args.extend(["-var-file", f]) |
| 670 |
|
| 671 |
preflight_validation(command[0], project_path, checked_version, variables_args, plan_file, no_color) |
| 672 |
|
| 673 |
if module.params.get("lock") is not None: |
| 674 |
if module.params.get("lock"): |
| 675 |
command.append("-lock=true") |
| 676 |
else: |
| 677 |
command.append("-lock=false") |
| 678 |
if module.params.get("lock_timeout") is not None: |
| 679 |
command.append(f"-lock-timeout={module.params.get('lock_timeout')}s") |
| 680 |
|
| 681 |
for t in module.params.get("targets") or []: |
| 682 |
command.extend(["-target", t]) |
| 683 |
|
| 684 |
# we aren't sure if this plan will result in changes, so assume yes |
| 685 |
needs_application, changed = True, False |
| 686 |
|
| 687 |
out, err = "", "" |
| 688 |
|
| 689 |
if state == "absent": |
| 690 |
command.extend(variables_args) |
| 691 |
elif state == "present" and plan_file: |
| 692 |
if any([os.path.isfile(f"{project_path}/{plan_file}"), os.path.isfile(plan_file)]): |
| 693 |
command.append(plan_file) |
| 694 |
else: |
| 695 |
module.fail_json(msg=f'Could not find plan_file "{plan_file}", check the path and try again.') |
| 696 |
else: |
| 697 |
plan_file, needs_application, out, err, command = build_plan( |
| 698 |
command, |
| 699 |
project_path, |
| 700 |
variables_args, |
| 701 |
state_file, |
| 702 |
module.params.get("targets"), |
| 703 |
state, |
| 704 |
APPLY_ARGS, |
| 705 |
plan_file, |
| 706 |
no_color, |
| 707 |
) |
| 708 |
if state == "present" and check_destroy and "- destroy" in out: |
| 709 |
module.fail_json( |
| 710 |
msg="Aborting command because it would destroy some resources. " |
| 711 |
"Consider switching the 'check_destroy' to false to suppress this error" |
| 712 |
) |
| 713 |
command.append(plan_file) |
| 714 |
|
| 715 |
result_diff = dict() |
| 716 |
if module._diff or module.check_mode: |
| 717 |
if state == "absent": |
| 718 |
plan_absent_args = ["-destroy"] |
| 719 |
plan_file, needs_application, out, err, command = build_plan( |
| 720 |
command, |
| 721 |
project_path, |
| 722 |
variables_args, |
| 723 |
state_file, |
| 724 |
module.params.get("targets"), |
| 725 |
state, |
| 726 |
plan_absent_args, |
| 727 |
plan_file, |
| 728 |
no_color, |
| 729 |
) |
| 730 |
diff_command = [command[0], "show", "-json", plan_file] |
| 731 |
rc, diff_output, err = module.run_command(diff_command, check_rc=False, cwd=project_path) |
| 732 |
changed, result_diff = get_diff(diff_output) |
| 733 |
if rc != 0: |
| 734 |
if workspace_ctx["current"] != workspace: |
| 735 |
select_workspace(command[0], project_path, workspace_ctx["current"], no_color) |
| 736 |
module.fail_json( |
| 737 |
msg=err.rstrip(), |
| 738 |
rc=rc, |
| 739 |
stdout=out, |
| 740 |
stdout_lines=out.splitlines(), |
| 741 |
stderr=err, |
| 742 |
stderr_lines=err.splitlines(), |
| 743 |
cmd=" ".join(command), |
| 744 |
) |
| 745 |
|
| 746 |
if needs_application and not module.check_mode and state != "planned": |
| 747 |
rc, out, err = module.run_command(command, check_rc=False, cwd=project_path) |
| 748 |
if rc != 0: |
| 749 |
if workspace_ctx["current"] != workspace: |
| 750 |
select_workspace(command[0], project_path, workspace_ctx["current"], no_color) |
| 751 |
module.fail_json( |
| 752 |
msg=err.rstrip(), |
| 753 |
rc=rc, |
| 754 |
stdout=out, |
| 755 |
stdout_lines=out.splitlines(), |
| 756 |
stderr=err, |
| 757 |
stderr_lines=err.splitlines(), |
| 758 |
cmd=" ".join(command), |
| 759 |
) |
| 760 |
# checks out to decide if changes were made during execution |
| 761 |
if " 0 added, 0 changed" not in out and state != "absent" or " 0 destroyed" not in out: |
| 762 |
changed = True |
| 763 |
|
| 764 |
if no_color: |
| 765 |
outputs_command = [command[0], "output", "-no-color", "-json"] + _state_args(state_file) |
| 766 |
else: |
| 767 |
outputs_command = [command[0], "output", "-json"] + _state_args(state_file) |
| 768 |
|
| 769 |
rc, outputs_text, outputs_err = module.run_command(outputs_command, cwd=project_path) |
| 770 |
outputs = {} |
| 771 |
if rc == 1: |
| 772 |
module.warn( |
| 773 |
f"Could not get Terraform outputs. This usually means none have been defined.\nstdout: {outputs_text}\nstderr: {outputs_err}" |
| 774 |
) |
| 775 |
elif rc != 0: |
| 776 |
module.fail_json( |
| 777 |
msg=f"Failure when getting Terraform outputs. Exited {rc}.\nstdout: {outputs_text}\nstderr: {outputs_err}", |
| 778 |
command=" ".join(outputs_command), |
| 779 |
) |
| 780 |
else: |
| 781 |
outputs = json.loads(outputs_text) |
| 782 |
|
| 783 |
# Restore the Terraform workspace found when running the module |
| 784 |
if workspace_ctx["current"] != workspace: |
| 785 |
select_workspace(command[0], project_path, workspace_ctx["current"], no_color) |
| 786 |
if state == "absent" and workspace != "default" and purge_workspace is True: |
| 787 |
remove_workspace(command[0], project_path, workspace, no_color) |
| 788 |
|
| 789 |
result = { |
| 790 |
"state": state, |
| 791 |
"workspace": workspace, |
| 792 |
"outputs": outputs, |
| 793 |
"stdout": out, |
| 794 |
"stderr": err, |
| 795 |
"command": " ".join(command), |
| 796 |
"changed": changed, |
| 797 |
"diff": result_diff, |
| 798 |
} |
| 799 |
|
| 800 |
module.exit_json(**result) |
| 801 |
|
| 802 |
|
| 803 |
if __name__ == "__main__": |
| 804 |
main() |