target = [ # dev # {"region": "us-west1", "cluster_name": "o11y-staging-regional-us-west1"}, # stg # prod {"region": "eastus2", "cluster_name": "o11y-prod-regional-eastus2"}, {"region": "japaneast", "cluster_name": "o11y-prod-regional-japaneast"}, {"region": "southeastasia", "cluster_name": "o11y-prod-regional-southeastasia"}, {"region": "westeurope", "cluster_name": "o11y-prod-regional-westeurope"}, ] def _safe_name(s: str) -> str: return "".join(c if c.isalnum() or c in "-._" else "-" for c in s) def generate_commands(targets): for i, t in enumerate(targets, start=1): region = t.get("region", "") cluster = t.get("cluster_name", "") # if the cluster name contains the region, replace that part with a shell variable reference if region and region in cluster: cluster_template = cluster.replace(region, "${region}") else: cluster_template = cluster # use shell variables for region / cluster_name / state_file # state_file references the exported region variable so each target has an independent state file plan_file = "plan-${region}.tfplan" plan_cmd = ( 'terraform plan -input=false \\\n' ' -var "region=${region}" \\\n' ' -var "cluster_name=${cluster_name}" \\\n' ' -var "resource_group_name=${cluster_name}" \\\n' ' -var "subscription_id=01f5d24b-a99c-45e1-a3e2-5ddc1e5bb71d" \\\n' ' -state="${state_file}" \\\n' f' -out={plan_file}' ) apply_cmd = 'terraform apply -input=false -state="${state_file}" ' + plan_file print(f"# target {i}") # export the region (concrete value), cluster_name (template or concrete), and state_file (uses ${region}) print(f'export region="{region}"') print(f'export cluster_name="{cluster_template}"') print('export state_file="terraform-${region}.tfstate"') print() print(plan_cmd) print() print(apply_cmd) print("\n" + ("-" * 60) + "\n") if __name__ == "__main__": generate_commands(target)