|
| 1 | +# Copyright 2025 "Google LLC" |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +locals { |
| 16 | + create_script_content = <<EOT |
| 17 | +#!/bin/bash |
| 18 | +set -e -x |
| 19 | +echo "Executing gcloud CREATE commands for ${var.module_instance_id}..." |
| 20 | +%{for cmd_pair in var.commands~} |
| 21 | +${cmd_pair.create} |
| 22 | +%{endfor~} |
| 23 | +echo "All gcloud CREATE commands executed successfully for ${var.module_instance_id}." |
| 24 | +EOT |
| 25 | + |
| 26 | + destroy_script_content = <<EOT |
| 27 | +#!/bin/bash |
| 28 | +set -x # We don't use -e here to allow other cleanup commands to run if one fails |
| 29 | +echo "Executing gcloud DELETE commands for ${var.module_instance_id}..." |
| 30 | +%{for cmd_pair in reverse(var.commands)~} |
| 31 | +${cmd_pair.delete} || echo "Delete command failed: ${cmd_pair.delete}, continuing..." |
| 32 | +%{endfor~} |
| 33 | +echo "All gcloud DELETE commands attempted for ${var.module_instance_id}." |
| 34 | +EOT |
| 35 | +} |
| 36 | + |
| 37 | +resource "null_resource" "gcloud_commands" { |
| 38 | + triggers = { |
| 39 | + commands_hash = sha256(jsonencode(var.commands)) |
| 40 | + module_instance_id = var.module_instance_id |
| 41 | + create_script_content = local.create_script_content |
| 42 | + destroy_script_content = local.destroy_script_content |
| 43 | + } |
| 44 | + |
| 45 | + provisioner "local-exec" { |
| 46 | + command = "/bin/bash <<EOT\n${self.triggers.create_script_content}\nEOT" |
| 47 | + } |
| 48 | + |
| 49 | + provisioner "local-exec" { |
| 50 | + when = destroy |
| 51 | + command = "/bin/bash <<EOT\n${self.triggers.destroy_script_content}\nEOT" |
| 52 | + } |
| 53 | +} |
0 commit comments