Skip to content

Instantly share code, notes, and snippets.

@bneutra
Last active March 28, 2024 21:00
Show Gist options
  • Save bneutra/5f83f04a66b16acd0098f17b7ff3006a to your computer and use it in GitHub Desktop.
Save bneutra/5f83f04a66b16acd0098f17b7ff3006a to your computer and use it in GitHub Desktop.
# move_blocks.py
# This script is used to generate move blocks
# as we move to the new module
# usage: python move_blocks.py <workspace_file> <variable_name> <module_name>
# The file name, the local variable map name and the module name that loops over
# workspaces, unfortunately vary
# typical example to create a moved.tf:
# account_name = account_name.replace("-","_")
# python move_blocks.py main.tf <account_name>_workspaces <account_name> >> moved.tf
import sys
import hcl2
# to move from the legacy module to the new module
source_module = "."
# to move from the default module to the ignore module
# source_module = "tfc_workspace_default[0]."
# choose between the default module and the ignore module
# (global and regional workspaces are moved to the default module)
ignore = False
def get_target_module(k):
if (
"tf-global" in k
or "tf-regional" in k
or "security-foundations" in k
or ignore is False
):
return "tfc_workspace_default[0]."
else:
return "tfc_workspace_lifecycle_ignore[0]."
def extract_workspaces(ws_file, var_name, module_name):
ws_data = hcl2.loads(open(ws_file).read())
locals = ws_data["locals"]
ws_dict = locals[0][var_name]
blocks = ""
for k, v in ws_dict.items():
target_module = get_target_module(k)
blocks += f"""
moved {{
from = module.{module_name}["{k}"]{source_module}tfe_workspace.main
to = module.{module_name}["{k}"].module.{target_module}tfe_workspace.main
}}
moved {{
from = module.{module_name}["{k}"]{source_module}tfe_workspace_settings.main
to = module.{module_name}["{k}"].module.{target_module}tfe_workspace_settings.main
}}
"""
print(blocks)
extract_workspaces(sys.argv[1], sys.argv[2], sys.argv[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment